(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
function _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;
}

module.exports = _arrayLikeToArray;
},{}],2:[function(require,module,exports){
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

module.exports = _arrayWithHoles;
},{}],3:[function(require,module,exports){
var arrayLikeToArray = require("./arrayLikeToArray");

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return arrayLikeToArray(arr);
}

module.exports = _arrayWithoutHoles;
},{"./arrayLikeToArray":1}],4:[function(require,module,exports){
function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

module.exports = _assertThisInitialized;
},{}],5:[function(require,module,exports){
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }

  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}

function _asyncToGenerator(fn) {
  return function () {
    var self = this,
        args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);

      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }

      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }

      _next(undefined);
    });
  };
}

module.exports = _asyncToGenerator;
},{}],6:[function(require,module,exports){
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

module.exports = _classCallCheck;
},{}],7:[function(require,module,exports){
var setPrototypeOf = require("./setPrototypeOf");

var isNativeReflectConstruct = require("./isNativeReflectConstruct");

function _construct(Parent, args, Class) {
  if (isNativeReflectConstruct()) {
    module.exports = _construct = Reflect.construct;
  } else {
    module.exports = _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);
}

module.exports = _construct;
},{"./isNativeReflectConstruct":15,"./setPrototypeOf":21}],8:[function(require,module,exports){
function _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);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

module.exports = _createClass;
},{}],9:[function(require,module,exports){
function _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;
}

module.exports = _defineProperty;
},{}],10:[function(require,module,exports){
function _getPrototypeOf(o) {
  module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

module.exports = _getPrototypeOf;
},{}],11:[function(require,module,exports){
var setPrototypeOf = require("./setPrototypeOf");

function _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
    }
  });
  if (superClass) setPrototypeOf(subClass, superClass);
}

module.exports = _inherits;
},{"./setPrototypeOf":21}],12:[function(require,module,exports){
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
}

module.exports = _interopRequireDefault;
},{}],13:[function(require,module,exports){
var _typeof = require("@babel/runtime/helpers/typeof");

function _getRequireWildcardCache() {
  if (typeof WeakMap !== "function") return null;
  var cache = new WeakMap();

  _getRequireWildcardCache = function _getRequireWildcardCache() {
    return cache;
  };

  return cache;
}

function _interopRequireWildcard(obj) {
  if (obj && obj.__esModule) {
    return obj;
  }

  if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
    return {
      "default": obj
    };
  }

  var cache = _getRequireWildcardCache();

  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }

  var newObj = {};
  var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;

  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;

      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }

  newObj["default"] = obj;

  if (cache) {
    cache.set(obj, newObj);
  }

  return newObj;
}

module.exports = _interopRequireWildcard;
},{"@babel/runtime/helpers/typeof":24}],14:[function(require,module,exports){
function _isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}

module.exports = _isNativeFunction;
},{}],15:[function(require,module,exports){
function _isNativeReflectConstruct() {
  if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  if (Reflect.construct.sham) return false;
  if (typeof Proxy === "function") return true;

  try {
    Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
    return true;
  } catch (e) {
    return false;
  }
}

module.exports = _isNativeReflectConstruct;
},{}],16:[function(require,module,exports){
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}

module.exports = _iterableToArray;
},{}],17:[function(require,module,exports){
function _iterableToArrayLimit(arr, i) {
  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

module.exports = _iterableToArrayLimit;
},{}],18:[function(require,module,exports){
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

module.exports = _nonIterableRest;
},{}],19:[function(require,module,exports){
function _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.");
}

module.exports = _nonIterableSpread;
},{}],20:[function(require,module,exports){
var _typeof = require("@babel/runtime/helpers/typeof");

var assertThisInitialized = require("./assertThisInitialized");

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  }

  return assertThisInitialized(self);
}

module.exports = _possibleConstructorReturn;
},{"./assertThisInitialized":4,"@babel/runtime/helpers/typeof":24}],21:[function(require,module,exports){
function _setPrototypeOf(o, p) {
  module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}

module.exports = _setPrototypeOf;
},{}],22:[function(require,module,exports){
var arrayWithHoles = require("./arrayWithHoles");

var iterableToArrayLimit = require("./iterableToArrayLimit");

var unsupportedIterableToArray = require("./unsupportedIterableToArray");

var nonIterableRest = require("./nonIterableRest");

function _slicedToArray(arr, i) {
  return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}

module.exports = _slicedToArray;
},{"./arrayWithHoles":2,"./iterableToArrayLimit":17,"./nonIterableRest":18,"./unsupportedIterableToArray":25}],23:[function(require,module,exports){
var arrayWithoutHoles = require("./arrayWithoutHoles");

var iterableToArray = require("./iterableToArray");

var unsupportedIterableToArray = require("./unsupportedIterableToArray");

var nonIterableSpread = require("./nonIterableSpread");

function _toConsumableArray(arr) {
  return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}

module.exports = _toConsumableArray;
},{"./arrayWithoutHoles":3,"./iterableToArray":16,"./nonIterableSpread":19,"./unsupportedIterableToArray":25}],24:[function(require,module,exports){
function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    module.exports = _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    module.exports = _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

module.exports = _typeof;
},{}],25:[function(require,module,exports){
var arrayLikeToArray = require("./arrayLikeToArray");

function _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);
}

module.exports = _unsupportedIterableToArray;
},{"./arrayLikeToArray":1}],26:[function(require,module,exports){
var getPrototypeOf = require("./getPrototypeOf");

var setPrototypeOf = require("./setPrototypeOf");

var isNativeFunction = require("./isNativeFunction");

var construct = require("./construct");

function _wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;

  module.exports = _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);
}

module.exports = _wrapNativeSuper;
},{"./construct":7,"./getPrototypeOf":10,"./isNativeFunction":14,"./setPrototypeOf":21}],27:[function(require,module,exports){
module.exports = require("regenerator-runtime");

},{"regenerator-runtime":49}],28:[function(require,module,exports){
/* Copyright 2015 Mark Haines
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var escaped = /[\\\"\x00-\x1F]/g;
var escapes = {};
for (var i = 0; i < 0x20; ++i) {
    escapes[String.fromCharCode(i)] = (
        '\\U' + ('0000' + i.toString(16)).slice(-4).toUpperCase()
    );
}
escapes['\b'] = '\\b';
escapes['\t'] = '\\t';
escapes['\n'] = '\\n';
escapes['\f'] = '\\f';
escapes['\r'] = '\\r';
escapes['\"'] = '\\\"';
escapes['\\'] = '\\\\';

function escapeString(value) {
    escaped.lastIndex = 0;
    return value.replace(escaped, function(c) { return escapes[c]; });
}

function stringify(value) {
    switch (typeof value) {
        case 'string':
            return '"' + escapeString(value) + '"';
        case 'number':
            return isFinite(value) ? value : 'null';
        case 'boolean':
            return value;
        case 'object':
            if (value === null) {
                return 'null';
            }
            if (Array.isArray(value)) {
                return stringifyArray(value);
            }
            return stringifyObject(value);
        default:
            throw new Error('Cannot stringify: ' + typeof value);
    }
}

function stringifyArray(array) {
    var sep = '[';
    var result = '';
    for (var i = 0; i < array.length; ++i) {
        result += sep;
        sep = ',';
        result += stringify(array[i]);
    }
    if (sep != ',') {
        return '[]';
    } else {
        return result + ']';
    }
}

function stringifyObject(object) {
    var sep = '{';
    var result = '';
    var keys = Object.keys(object);
    keys.sort();
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        result += sep + '"' + escapeString(key) + '":';
        sep = ',';
        result += stringify(object[key]);
    }
    if (sep != ',') {
        return '{}';
    } else {
        return result + '}';
    }
}

/** */
module.exports = {stringify: stringify};

},{}],29:[function(require,module,exports){
'use strict'
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
// @ts-ignore
var _Buffer = require('safe-buffer').Buffer
function base (ALPHABET) {
  if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
  var BASE_MAP = new Uint8Array(256)
  for (var j = 0; j < BASE_MAP.length; j++) {
    BASE_MAP[j] = 255
  }
  for (var i = 0; i < ALPHABET.length; i++) {
    var x = ALPHABET.charAt(i)
    var xc = x.charCodeAt(0)
    if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
    BASE_MAP[xc] = i
  }
  var BASE = ALPHABET.length
  var LEADER = ALPHABET.charAt(0)
  var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
  var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
  function encode (source) {
    if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }
    if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }
    if (source.length === 0) { return '' }
        // Skip & count leading zeroes.
    var zeroes = 0
    var length = 0
    var pbegin = 0
    var pend = source.length
    while (pbegin !== pend && source[pbegin] === 0) {
      pbegin++
      zeroes++
    }
        // Allocate enough space in big-endian base58 representation.
    var size = ((pend - pbegin) * iFACTOR + 1) >>> 0
    var b58 = new Uint8Array(size)
        // Process the bytes.
    while (pbegin !== pend) {
      var carry = source[pbegin]
            // Apply "b58 = b58 * 256 + ch".
      var i = 0
      for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
        carry += (256 * b58[it1]) >>> 0
        b58[it1] = (carry % BASE) >>> 0
        carry = (carry / BASE) >>> 0
      }
      if (carry !== 0) { throw new Error('Non-zero carry') }
      length = i
      pbegin++
    }
        // Skip leading zeroes in base58 result.
    var it2 = size - length
    while (it2 !== size && b58[it2] === 0) {
      it2++
    }
        // Translate the result into a string.
    var str = LEADER.repeat(zeroes)
    for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }
    return str
  }
  function decodeUnsafe (source) {
    if (typeof source !== 'string') { throw new TypeError('Expected String') }
    if (source.length === 0) { return _Buffer.alloc(0) }
    var psz = 0
        // Skip leading spaces.
    if (source[psz] === ' ') { return }
        // Skip and count leading '1's.
    var zeroes = 0
    var length = 0
    while (source[psz] === LEADER) {
      zeroes++
      psz++
    }
        // Allocate enough space in big-endian base256 representation.
    var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
    var b256 = new Uint8Array(size)
        // Process the characters.
    while (source[psz]) {
            // Decode character
      var carry = BASE_MAP[source.charCodeAt(psz)]
            // Invalid character
      if (carry === 255) { return }
      var i = 0
      for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
        carry += (BASE * b256[it3]) >>> 0
        b256[it3] = (carry % 256) >>> 0
        carry = (carry / 256) >>> 0
      }
      if (carry !== 0) { throw new Error('Non-zero carry') }
      length = i
      psz++
    }
        // Skip trailing spaces.
    if (source[psz] === ' ') { return }
        // Skip leading zeroes in b256.
    var it4 = size - length
    while (it4 !== size && b256[it4] === 0) {
      it4++
    }
    var vch = _Buffer.allocUnsafe(zeroes + (size - it4))
    vch.fill(0x00, 0, zeroes)
    var j = zeroes
    while (it4 !== size) {
      vch[j++] = b256[it4++]
    }
    return vch
  }
  function decode (string) {
    var buffer = decodeUnsafe(string)
    if (buffer) { return buffer }
    throw new Error('Non-base' + BASE + ' character')
  }
  return {
    encode: encode,
    decodeUnsafe: decodeUnsafe,
    decode: decode
  }
}
module.exports = base

},{"safe-buffer":53}],30:[function(require,module,exports){
'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}

},{}],31:[function(require,module,exports){
// Browser Request
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// UMD HEADER START 
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.returnExports = factory();
  }
}(this, function () {
// UMD HEADER END

var XHR = XMLHttpRequest
if (!XHR) throw new Error('missing XMLHttpRequest')
request.log = {
  'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop
}

var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes

//
// request
//

function request(options, callback) {
  // The entry-point to the API: prep the options object and pass the real work to run_xhr.
  if(typeof callback !== 'function')
    throw new Error('Bad callback given: ' + callback)

  if(!options)
    throw new Error('No options given')

  var options_onResponse = options.onResponse; // Save this for later.

  if(typeof options === 'string')
    options = {'uri':options};
  else
    options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.

  options.onResponse = options_onResponse // And put it back.

  if (options.verbose) request.log = getLogger();

  if(options.url) {
    options.uri = options.url;
    delete options.url;
  }

  if(!options.uri && options.uri !== "")
    throw new Error("options.uri is a required argument");

  if(typeof options.uri != "string")
    throw new Error("options.uri must be a string");

  var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']
  for (var i = 0; i < unsupported_options.length; i++)
    if(options[ unsupported_options[i] ])
      throw new Error("options." + unsupported_options[i] + " is not supported")

  options.callback = callback
  options.method = options.method || 'GET';
  options.headers = options.headers || {};
  options.body    = options.body || null
  options.timeout = options.timeout || request.DEFAULT_TIMEOUT

  if(options.headers.host)
    throw new Error("Options.headers.host is not supported");

  if(options.json) {
    options.headers.accept = options.headers.accept || 'application/json'
    if(options.method !== 'GET')
      options.headers['content-type'] = 'application/json'

    if(typeof options.json !== 'boolean')
      options.body = JSON.stringify(options.json)
    else if(typeof options.body !== 'string')
      options.body = JSON.stringify(options.body)
  }
  
  //BEGIN QS Hack
  var serialize = function(obj) {
    var str = [];
    for(var p in obj)
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    return str.join("&");
  }
  
  if(options.qs){
    var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);
    if(options.uri.indexOf('?') !== -1){ //no get params
        options.uri = options.uri+'&'+qs;
    }else{ //existing get params
        options.uri = options.uri+'?'+qs;
    }
  }
  //END QS Hack
  
  //BEGIN FORM Hack
  var multipart = function(obj) {
    //todo: support file type (useful?)
    var result = {};
    result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
    var lines = [];
    for(var p in obj){
        if (obj.hasOwnProperty(p)) {
            lines.push(
                '--'+result.boundry+"\n"+
                'Content-Disposition: form-data; name="'+p+'"'+"\n"+
                "\n"+
                obj[p]+"\n"
            );
        }
    }
    lines.push( '--'+result.boundry+'--' );
    result.body = lines.join('');
    result.length = result.body.length;
    result.type = 'multipart/form-data; boundary='+result.boundry;
    return result;
  }
  
  if(options.form){
    if(typeof options.form == 'string') throw('form name unsupported');
    if(options.method === 'POST'){
        var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();
        options.headers['content-type'] = encoding;
        switch(encoding){
            case 'application/x-www-form-urlencoded':
                options.body = serialize(options.form).replace(/%20/g, "+");
                break;
            case 'multipart/form-data':
                var multi = multipart(options.form);
                //options.headers['content-length'] = multi.length;
                options.body = multi.body;
                options.headers['content-type'] = multi.type;
                break;
            default : throw new Error('unsupported encoding:'+encoding);
        }
    }
  }
  //END FORM Hack

  // If onResponse is boolean true, call back immediately when the response is known,
  // not when the full request is complete.
  options.onResponse = options.onResponse || noop
  if(options.onResponse === true) {
    options.onResponse = callback
    options.callback = noop
  }

  // XXX Browsers do not like this.
  //if(options.body)
  //  options.headers['content-length'] = options.body.length;

  // HTTP basic authentication
  if(!options.headers.authorization && options.auth)
    options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);

  return run_xhr(options)
}

var req_seq = 0
function run_xhr(options) {
  var xhr = new XHR
    , timed_out = false
    , is_cors = is_crossDomain(options.uri)
    , supports_cors = ('withCredentials' in xhr)

  req_seq += 1
  xhr.seq_id = req_seq
  xhr.id = req_seq + ': ' + options.method + ' ' + options.uri
  xhr._id = xhr.id // I know I will type "_id" from habit all the time.

  if(is_cors && !supports_cors) {
    var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)
    cors_err.cors = 'unsupported'
    return options.callback(cors_err, xhr)
  }

  xhr.timeoutTimer = setTimeout(too_late, options.timeout)
  function too_late() {
    timed_out = true
    var er = new Error('ETIMEDOUT')
    er.code = 'ETIMEDOUT'
    er.duration = options.timeout

    request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })
    return options.callback(er, xhr)
  }

  // Some states can be skipped over, so remember what is still incomplete.
  var did = {'response':false, 'loading':false, 'end':false}

  xhr.onreadystatechange = on_state_change
  xhr.open(options.method, options.uri, true) // asynchronous
  if(is_cors)
    xhr.withCredentials = !! options.withCredentials
  xhr.send(options.body)
  return xhr

  function on_state_change(event) {
    if(timed_out)
      return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})

    request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})

    if(xhr.readyState === XHR.OPENED) {
      request.log.debug('Request started', {'id':xhr.id})
      for (var key in options.headers)
        xhr.setRequestHeader(key, options.headers[key])
    }

    else if(xhr.readyState === XHR.HEADERS_RECEIVED)
      on_response()

    else if(xhr.readyState === XHR.LOADING) {
      on_response()
      on_loading()
    }

    else if(xhr.readyState === XHR.DONE) {
      on_response()
      on_loading()
      on_end()
    }
  }

  function on_response() {
    if(did.response)
      return

    did.response = true
    request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})
    clearTimeout(xhr.timeoutTimer)
    xhr.statusCode = xhr.status // Node request compatibility

    // Detect failed CORS requests.
    if(is_cors && xhr.statusCode == 0) {
      var cors_err = new Error('CORS request rejected: ' + options.uri)
      cors_err.cors = 'rejected'

      // Do not process this request further.
      did.loading = true
      did.end = true

      return options.callback(cors_err, xhr)
    }

    options.onResponse(null, xhr)
  }

  function on_loading() {
    if(did.loading)
      return

    did.loading = true
    request.log.debug('Response body loading', {'id':xhr.id})
    // TODO: Maybe simulate "data" events by watching xhr.responseText
  }

  function on_end() {
    if(did.end)
      return

    did.end = true
    request.log.debug('Request done', {'id':xhr.id})

    xhr.body = xhr.responseText
    if(options.json) {
      try        { xhr.body = JSON.parse(xhr.responseText) }
      catch (er) { return options.callback(er, xhr)        }
    }

    options.callback(null, xhr, xhr.body)
  }

} // request

request.withCredentials = false;
request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;

//
// defaults
//

request.defaults = function(options, requester) {
  var def = function (method) {
    var d = function (params, callback) {
      if(typeof params === 'string')
        params = {'uri': params};
      else {
        params = JSON.parse(JSON.stringify(params));
      }
      for (var i in options) {
        if (params[i] === undefined) params[i] = options[i]
      }
      return method(params, callback)
    }
    return d
  }
  var de = def(request)
  de.get = def(request.get)
  de.post = def(request.post)
  de.put = def(request.put)
  de.head = def(request.head)
  return de
}

//
// HTTP method shortcuts
//

var shortcuts = [ 'get', 'put', 'post', 'head' ];
shortcuts.forEach(function(shortcut) {
  var method = shortcut.toUpperCase();
  var func   = shortcut.toLowerCase();

  request[func] = function(opts) {
    if(typeof opts === 'string')
      opts = {'method':method, 'uri':opts};
    else {
      opts = JSON.parse(JSON.stringify(opts));
      opts.method = method;
    }

    var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));
    return request.apply(this, args);
  }
})

//
// CouchDB shortcut
//

request.couch = function(options, callback) {
  if(typeof options === 'string')
    options = {'uri':options}

  // Just use the request API to do JSON.
  options.json = true
  if(options.body)
    options.json = options.body
  delete options.body

  callback = callback || noop

  var xhr = request(options, couch_handler)
  return xhr

  function couch_handler(er, resp, body) {
    if(er)
      return callback(er, resp, body)

    if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {
      // The body is a Couch JSON object indicating the error.
      er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))
      for (var key in body)
        er[key] = body[key]
      return callback(er, resp, body);
    }

    return callback(er, resp, body);
  }
}

//
// Utility
//

function noop() {}

function getLogger() {
  var logger = {}
    , levels = ['trace', 'debug', 'info', 'warn', 'error']
    , level, i

  for(i = 0; i < levels.length; i++) {
    level = levels[i]

    logger[level] = noop
    if(typeof console !== 'undefined' && console && console[level])
      logger[level] = formatted(console, level)
  }

  return logger
}

function formatted(obj, method) {
  return formatted_logger

  function formatted_logger(str, context) {
    if(typeof context === 'object')
      str += ' ' + JSON.stringify(context)

    return obj[method].call(obj, str)
  }
}

// Return whether a URL is a cross-domain request.
function is_crossDomain(url) {
  var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/

  // jQuery #8138, IE may throw an exception when accessing
  // a field from window.location if document.domain has been set
  var ajaxLocation
  try { ajaxLocation = location.href }
  catch (e) {
    // Use the href attribute of an A element since IE will modify it given document.location
    ajaxLocation = document.createElement( "a" );
    ajaxLocation.href = "";
    ajaxLocation = ajaxLocation.href;
  }

  var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
    , parts = rurl.exec(url.toLowerCase() )

  var result = !!(
    parts &&
    (  parts[1] != ajaxLocParts[1]
    || parts[2] != ajaxLocParts[2]
    || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
    )
  )

  //console.debug('is_crossDomain('+url+') -> ' + result)
  return result
}

// MIT License from http://phpjs.org/functions/base64_encode:358
function b64_enc (data) {
    // Encodes string using MIME base64 algorithm
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    // assume utf8 data
    // data = this.utf8_encode(data+'');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}
    return request;
//UMD FOOTER START
}));
//UMD FOOTER END

},{}],32:[function(require,module,exports){
(function (global){(function (){
/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {

	/** Detect free variables */
	var freeExports = typeof exports == 'object' && exports &&
		!exports.nodeType && exports;
	var freeModule = typeof module == 'object' && module &&
		!module.nodeType && module;
	var freeGlobal = typeof global == 'object' && global;
	if (
		freeGlobal.global === freeGlobal ||
		freeGlobal.window === freeGlobal ||
		freeGlobal.self === freeGlobal
	) {
		root = freeGlobal;
	}

	/**
	 * The `punycode` object.
	 * @name punycode
	 * @type Object
	 */
	var punycode,

	/** Highest positive signed 32-bit float value */
	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1

	/** Bootstring parameters */
	base = 36,
	tMin = 1,
	tMax = 26,
	skew = 38,
	damp = 700,
	initialBias = 72,
	initialN = 128, // 0x80
	delimiter = '-', // '\x2D'

	/** Regular expressions */
	regexPunycode = /^xn--/,
	regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
	regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators

	/** Error messages */
	errors = {
		'overflow': 'Overflow: input needs wider integers to process',
		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
		'invalid-input': 'Invalid input'
	},

	/** Convenience shortcuts */
	baseMinusTMin = base - tMin,
	floor = Math.floor,
	stringFromCharCode = String.fromCharCode,

	/** Temporary variable */
	key;

	/*--------------------------------------------------------------------------*/

	/**
	 * A generic error utility function.
	 * @private
	 * @param {String} type The error type.
	 * @returns {Error} Throws a `RangeError` with the applicable error message.
	 */
	function error(type) {
		throw new RangeError(errors[type]);
	}

	/**
	 * A generic `Array#map` utility function.
	 * @private
	 * @param {Array} array The array to iterate over.
	 * @param {Function} callback The function that gets called for every array
	 * item.
	 * @returns {Array} A new array of values returned by the callback function.
	 */
	function map(array, fn) {
		var length = array.length;
		var result = [];
		while (length--) {
			result[length] = fn(array[length]);
		}
		return result;
	}

	/**
	 * A simple `Array#map`-like wrapper to work with domain name strings or email
	 * addresses.
	 * @private
	 * @param {String} domain The domain name or email address.
	 * @param {Function} callback The function that gets called for every
	 * character.
	 * @returns {Array} A new string of characters returned by the callback
	 * function.
	 */
	function mapDomain(string, fn) {
		var parts = string.split('@');
		var result = '';
		if (parts.length > 1) {
			// In email addresses, only the domain name should be punycoded. Leave
			// the local part (i.e. everything up to `@`) intact.
			result = parts[0] + '@';
			string = parts[1];
		}
		// Avoid `split(regex)` for IE8 compatibility. See #17.
		string = string.replace(regexSeparators, '\x2E');
		var labels = string.split('.');
		var encoded = map(labels, fn).join('.');
		return result + encoded;
	}

	/**
	 * Creates an array containing the numeric code points of each Unicode
	 * character in the string. While JavaScript uses UCS-2 internally,
	 * this function will convert a pair of surrogate halves (each of which
	 * UCS-2 exposes as separate characters) into a single code point,
	 * matching UTF-16.
	 * @see `punycode.ucs2.encode`
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode.ucs2
	 * @name decode
	 * @param {String} string The Unicode input string (UCS-2).
	 * @returns {Array} The new array of code points.
	 */
	function ucs2decode(string) {
		var output = [],
		    counter = 0,
		    length = string.length,
		    value,
		    extra;
		while (counter < length) {
			value = string.charCodeAt(counter++);
			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
				// high surrogate, and there is a next character
				extra = string.charCodeAt(counter++);
				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
				} else {
					// unmatched surrogate; only append this code unit, in case the next
					// code unit is the high surrogate of a surrogate pair
					output.push(value);
					counter--;
				}
			} else {
				output.push(value);
			}
		}
		return output;
	}

	/**
	 * Creates a string based on an array of numeric code points.
	 * @see `punycode.ucs2.decode`
	 * @memberOf punycode.ucs2
	 * @name encode
	 * @param {Array} codePoints The array of numeric code points.
	 * @returns {String} The new Unicode string (UCS-2).
	 */
	function ucs2encode(array) {
		return map(array, function(value) {
			var output = '';
			if (value > 0xFFFF) {
				value -= 0x10000;
				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
				value = 0xDC00 | value & 0x3FF;
			}
			output += stringFromCharCode(value);
			return output;
		}).join('');
	}

	/**
	 * Converts a basic code point into a digit/integer.
	 * @see `digitToBasic()`
	 * @private
	 * @param {Number} codePoint The basic numeric code point value.
	 * @returns {Number} The numeric value of a basic code point (for use in
	 * representing integers) in the range `0` to `base - 1`, or `base` if
	 * the code point does not represent a value.
	 */
	function basicToDigit(codePoint) {
		if (codePoint - 48 < 10) {
			return codePoint - 22;
		}
		if (codePoint - 65 < 26) {
			return codePoint - 65;
		}
		if (codePoint - 97 < 26) {
			return codePoint - 97;
		}
		return base;
	}

	/**
	 * Converts a digit/integer into a basic code point.
	 * @see `basicToDigit()`
	 * @private
	 * @param {Number} digit The numeric value of a basic code point.
	 * @returns {Number} The basic code point whose value (when used for
	 * representing integers) is `digit`, which needs to be in the range
	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
	 * used; else, the lowercase form is used. The behavior is undefined
	 * if `flag` is non-zero and `digit` has no uppercase form.
	 */
	function digitToBasic(digit, flag) {
		//  0..25 map to ASCII a..z or A..Z
		// 26..35 map to ASCII 0..9
		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
	}

	/**
	 * Bias adaptation function as per section 3.4 of RFC 3492.
	 * https://tools.ietf.org/html/rfc3492#section-3.4
	 * @private
	 */
	function adapt(delta, numPoints, firstTime) {
		var k = 0;
		delta = firstTime ? floor(delta / damp) : delta >> 1;
		delta += floor(delta / numPoints);
		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
			delta = floor(delta / baseMinusTMin);
		}
		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
	}

	/**
	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
	 * symbols.
	 * @memberOf punycode
	 * @param {String} input The Punycode string of ASCII-only symbols.
	 * @returns {String} The resulting string of Unicode symbols.
	 */
	function decode(input) {
		// Don't use UCS-2
		var output = [],
		    inputLength = input.length,
		    out,
		    i = 0,
		    n = initialN,
		    bias = initialBias,
		    basic,
		    j,
		    index,
		    oldi,
		    w,
		    k,
		    digit,
		    t,
		    /** Cached calculation results */
		    baseMinusT;

		// Handle the basic code points: let `basic` be the number of input code
		// points before the last delimiter, or `0` if there is none, then copy
		// the first basic code points to the output.

		basic = input.lastIndexOf(delimiter);
		if (basic < 0) {
			basic = 0;
		}

		for (j = 0; j < basic; ++j) {
			// if it's not a basic code point
			if (input.charCodeAt(j) >= 0x80) {
				error('not-basic');
			}
			output.push(input.charCodeAt(j));
		}

		// Main decoding loop: start just after the last delimiter if any basic code
		// points were copied; start at the beginning otherwise.

		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

			// `index` is the index of the next character to be consumed.
			// Decode a generalized variable-length integer into `delta`,
			// which gets added to `i`. The overflow checking is easier
			// if we increase `i` as we go, then subtract off its starting
			// value at the end to obtain `delta`.
			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {

				if (index >= inputLength) {
					error('invalid-input');
				}

				digit = basicToDigit(input.charCodeAt(index++));

				if (digit >= base || digit > floor((maxInt - i) / w)) {
					error('overflow');
				}

				i += digit * w;
				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

				if (digit < t) {
					break;
				}

				baseMinusT = base - t;
				if (w > floor(maxInt / baseMinusT)) {
					error('overflow');
				}

				w *= baseMinusT;

			}

			out = output.length + 1;
			bias = adapt(i - oldi, out, oldi == 0);

			// `i` was supposed to wrap around from `out` to `0`,
			// incrementing `n` each time, so we'll fix that now:
			if (floor(i / out) > maxInt - n) {
				error('overflow');
			}

			n += floor(i / out);
			i %= out;

			// Insert `n` at position `i` of the output
			output.splice(i++, 0, n);

		}

		return ucs2encode(output);
	}

	/**
	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
	 * Punycode string of ASCII-only symbols.
	 * @memberOf punycode
	 * @param {String} input The string of Unicode symbols.
	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
	 */
	function encode(input) {
		var n,
		    delta,
		    handledCPCount,
		    basicLength,
		    bias,
		    j,
		    m,
		    q,
		    k,
		    t,
		    currentValue,
		    output = [],
		    /** `inputLength` will hold the number of code points in `input`. */
		    inputLength,
		    /** Cached calculation results */
		    handledCPCountPlusOne,
		    baseMinusT,
		    qMinusT;

		// Convert the input in UCS-2 to Unicode
		input = ucs2decode(input);

		// Cache the length
		inputLength = input.length;

		// Initialize the state
		n = initialN;
		delta = 0;
		bias = initialBias;

		// Handle the basic code points
		for (j = 0; j < inputLength; ++j) {
			currentValue = input[j];
			if (currentValue < 0x80) {
				output.push(stringFromCharCode(currentValue));
			}
		}

		handledCPCount = basicLength = output.length;

		// `handledCPCount` is the number of code points that have been handled;
		// `basicLength` is the number of basic code points.

		// Finish the basic string - if it is not empty - with a delimiter
		if (basicLength) {
			output.push(delimiter);
		}

		// Main encoding loop:
		while (handledCPCount < inputLength) {

			// All non-basic code points < n have been handled already. Find the next
			// larger one:
			for (m = maxInt, j = 0; j < inputLength; ++j) {
				currentValue = input[j];
				if (currentValue >= n && currentValue < m) {
					m = currentValue;
				}
			}

			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
			// but guard against overflow
			handledCPCountPlusOne = handledCPCount + 1;
			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
				error('overflow');
			}

			delta += (m - n) * handledCPCountPlusOne;
			n = m;

			for (j = 0; j < inputLength; ++j) {
				currentValue = input[j];

				if (currentValue < n && ++delta > maxInt) {
					error('overflow');
				}

				if (currentValue == n) {
					// Represent delta as a generalized variable-length integer
					for (q = delta, k = base; /* no condition */; k += base) {
						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
						if (q < t) {
							break;
						}
						qMinusT = q - t;
						baseMinusT = base - t;
						output.push(
							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
						);
						q = floor(qMinusT / baseMinusT);
					}

					output.push(stringFromCharCode(digitToBasic(q, 0)));
					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
					delta = 0;
					++handledCPCount;
				}
			}

			++delta;
			++n;

		}
		return output.join('');
	}

	/**
	 * Converts a Punycode string representing a domain name or an email address
	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
	 * it doesn't matter if you call it on a string that has already been
	 * converted to Unicode.
	 * @memberOf punycode
	 * @param {String} input The Punycoded domain name or email address to
	 * convert to Unicode.
	 * @returns {String} The Unicode representation of the given Punycode
	 * string.
	 */
	function toUnicode(input) {
		return mapDomain(input, function(string) {
			return regexPunycode.test(string)
				? decode(string.slice(4).toLowerCase())
				: string;
		});
	}

	/**
	 * Converts a Unicode string representing a domain name or an email address to
	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
	 * i.e. it doesn't matter if you call it with a domain that's already in
	 * ASCII.
	 * @memberOf punycode
	 * @param {String} input The domain name or email address to convert, as a
	 * Unicode string.
	 * @returns {String} The Punycode representation of the given domain name or
	 * email address.
	 */
	function toASCII(input) {
		return mapDomain(input, function(string) {
			return regexNonASCII.test(string)
				? 'xn--' + encode(string)
				: string;
		});
	}

	/*--------------------------------------------------------------------------*/

	/** Define the public API */
	punycode = {
		/**
		 * A string representing the current Punycode.js version number.
		 * @memberOf punycode
		 * @type String
		 */
		'version': '1.4.1',
		/**
		 * An object of methods to convert from JavaScript's internal character
		 * representation (UCS-2) to Unicode code points, and back.
		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
		 * @memberOf punycode
		 * @type Object
		 */
		'ucs2': {
			'decode': ucs2decode,
			'encode': ucs2encode
		},
		'decode': decode,
		'encode': encode,
		'toASCII': toASCII,
		'toUnicode': toUnicode
	};

	/** Expose `punycode` */
	// Some AMD build optimizers, like r.js, check for specific condition patterns
	// like the following:
	if (
		typeof define == 'function' &&
		typeof define.amd == 'object' &&
		define.amd
	) {
		define('punycode', function() {
			return punycode;
		});
	} else if (freeExports && freeModule) {
		if (module.exports == freeExports) {
			// in Node.js, io.js, or RingoJS v0.8.0+
			freeModule.exports = punycode;
		} else {
			// in Narwhal or RingoJS v0.7.0-
			for (key in punycode) {
				punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
			}
		}
	} else {
		// in Rhino or a web browser
		root.punycode = punycode;
	}

}(this));

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{}],33:[function(require,module,exports){
var basex = require('base-x')
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

module.exports = basex(ALPHABET)

},{"base-x":29}],34:[function(require,module,exports){
(function (Buffer){(function (){
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */

'use strict'

var base64 = require('base64-js')
var ieee754 = require('ieee754')

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  var buf = new Uint8Array(length)
  buf.__proto__ = Buffer.prototype
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
    Buffer[Symbol.species] === Buffer) {
  Object.defineProperty(Buffer, Symbol.species, {
    value: null,
    configurable: true,
    enumerable: false,
    writable: false
  })
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayLike(value)
  }

  if (value == null) {
    throw TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  var valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  var b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(
      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
    )
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  var length = byteLength(string, encoding) | 0
  var buf = createBuffer(length)

  var actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  var buf = createBuffer(length)
  for (var i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  var buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  buf.__proto__ = Buffer.prototype
  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    var buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      buf = Buffer.from(buf)
    }
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  var len = string.length
  var mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  var strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
          : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  newBuf.__proto__ = Buffer.prototype
  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (var i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    var len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

}).call(this)}).call(this,require("buffer").Buffer)

},{"base64-js":30,"buffer":34,"ieee754":37}],35:[function(require,module,exports){
/*!
 * content-type
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
 *
 * parameter     = token "=" ( token / quoted-string )
 * token         = 1*tchar
 * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
 *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
 *               / DIGIT / ALPHA
 *               ; any VCHAR, except delimiters
 * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
 * qdtext        = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
 * obs-text      = %x80-FF
 * quoted-pair   = "\" ( HTAB / SP / VCHAR / obs-text )
 */
var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g
var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/

/**
 * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
 *
 * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
 * obs-text    = %x80-FF
 */
var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g

/**
 * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
 */
var QUOTE_REGEXP = /([\\"])/g

/**
 * RegExp to match type in RFC 7231 sec 3.1.1.1
 *
 * media-type = type "/" subtype
 * type       = token
 * subtype    = token
 */
var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/

/**
 * Module exports.
 * @public
 */

exports.format = format
exports.parse = parse

/**
 * Format object to media type.
 *
 * @param {object} obj
 * @return {string}
 * @public
 */

function format (obj) {
  if (!obj || typeof obj !== 'object') {
    throw new TypeError('argument obj is required')
  }

  var parameters = obj.parameters
  var type = obj.type

  if (!type || !TYPE_REGEXP.test(type)) {
    throw new TypeError('invalid type')
  }

  var string = type

  // append parameters
  if (parameters && typeof parameters === 'object') {
    var param
    var params = Object.keys(parameters).sort()

    for (var i = 0; i < params.length; i++) {
      param = params[i]

      if (!TOKEN_REGEXP.test(param)) {
        throw new TypeError('invalid parameter name')
      }

      string += '; ' + param + '=' + qstring(parameters[param])
    }
  }

  return string
}

/**
 * Parse media type to object.
 *
 * @param {string|object} string
 * @return {Object}
 * @public
 */

function parse (string) {
  if (!string) {
    throw new TypeError('argument string is required')
  }

  // support req/res-like objects as argument
  var header = typeof string === 'object'
    ? getcontenttype(string)
    : string

  if (typeof header !== 'string') {
    throw new TypeError('argument string is required to be a string')
  }

  var index = header.indexOf(';')
  var type = index !== -1
    ? header.substr(0, index).trim()
    : header.trim()

  if (!TYPE_REGEXP.test(type)) {
    throw new TypeError('invalid media type')
  }

  var obj = new ContentType(type.toLowerCase())

  // parse parameters
  if (index !== -1) {
    var key
    var match
    var value

    PARAM_REGEXP.lastIndex = index

    while ((match = PARAM_REGEXP.exec(header))) {
      if (match.index !== index) {
        throw new TypeError('invalid parameter format')
      }

      index += match[0].length
      key = match[1].toLowerCase()
      value = match[2]

      if (value[0] === '"') {
        // remove quotes and escapes
        value = value
          .substr(1, value.length - 2)
          .replace(QESC_REGEXP, '$1')
      }

      obj.parameters[key] = value
    }

    if (index !== header.length) {
      throw new TypeError('invalid parameter format')
    }
  }

  return obj
}

/**
 * Get content-type from req/res objects.
 *
 * @param {object}
 * @return {Object}
 * @private
 */

function getcontenttype (obj) {
  var header

  if (typeof obj.getHeader === 'function') {
    // res-like
    header = obj.getHeader('content-type')
  } else if (typeof obj.headers === 'object') {
    // req-like
    header = obj.headers && obj.headers['content-type']
  }

  if (typeof header !== 'string') {
    throw new TypeError('content-type header is missing from object')
  }

  return header
}

/**
 * Quote a string if necessary.
 *
 * @param {string} val
 * @return {string}
 * @private
 */

function qstring (val) {
  var str = String(val)

  // no need to quote tokens
  if (TOKEN_REGEXP.test(str)) {
    return str
  }

  if (str.length > 0 && !TEXT_REGEXP.test(str)) {
    throw new TypeError('invalid parameter value')
  }

  return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
}

/**
 * Class to represent a content type.
 * @private
 */
function ContentType (type) {
  this.parameters = Object.create(null)
  this.type = type
}

},{}],36:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
  ? R.apply
  : function ReflectApply(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  }

var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
  ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target)
      .concat(Object.getOwnPropertySymbols(target));
  };
} else {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target);
  };
}

function ProcessEmitWarning(warning) {
  if (console && console.warn) console.warn(warning);
}

var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  return value !== value;
}

function EventEmitter() {
  EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

function checkListener(listener) {
  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }
}

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  enumerable: true,
  get: function() {
    return defaultMaxListeners;
  },
  set: function(arg) {
    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
    }
    defaultMaxListeners = arg;
  }
});

EventEmitter.init = function() {

  if (this._events === undefined ||
      this._events === Object.getPrototypeOf(this)._events) {
    this._events = Object.create(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  }
  this._maxListeners = n;
  return this;
};

function _getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return _getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
  var args = [];
  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  var doError = (type === 'error');

  var events = this._events;
  if (events !== undefined)
    doError = (doError && events.error === undefined);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    var er;
    if (args.length > 0)
      er = args[0];
    if (er instanceof Error) {
      // Note: The comments on the `throw` lines are intentional, they show
      // up in Node's output if this results in an unhandled exception.
      throw er; // Unhandled 'error' event
    }
    // At least give some kind of context to the user
    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
    err.context = er;
    throw err; // Unhandled 'error' event
  }

  var handler = events[type];

  if (handler === undefined)
    return false;

  if (typeof handler === 'function') {
    ReflectApply(handler, this, args);
  } else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      ReflectApply(listeners[i], this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  checkListener(listener);

  events = target._events;
  if (events === undefined) {
    events = target._events = Object.create(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener !== undefined) {
      target.emit('newListener', type,
                  listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (existing === undefined) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
        prepend ? [listener, existing] : [existing, listener];
      // If we've already got an array, just append.
    } else if (prepend) {
      existing.unshift(listener);
    } else {
      existing.push(listener);
    }

    // Check for listener leak
    m = _getMaxListeners(target);
    if (m > 0 && existing.length > m && !existing.warned) {
      existing.warned = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      var w = new Error('Possible EventEmitter memory leak detected. ' +
                          existing.length + ' ' + String(type) + ' listeners ' +
                          'added. Use emitter.setMaxListeners() to ' +
                          'increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.emitter = target;
      w.type = type;
      w.count = existing.length;
      ProcessEmitWarning(w);
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    if (arguments.length === 0)
      return this.listener.call(this.target);
    return this.listener.apply(this.target, arguments);
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = onceWrapper.bind(state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  checkListener(listener);
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      checkListener(listener);
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      checkListener(listener);

      events = this._events;
      if (events === undefined)
        return this;

      list = events[type];
      if (list === undefined)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener !== undefined)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (events === undefined)
        return this;

      // not listening for removeListener, no need to emit
      if (events.removeListener === undefined) {
        if (arguments.length === 0) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== undefined) {
          if (--this._eventsCount === 0)
            this._events = Object.create(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners !== undefined) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (events === undefined)
    return [];

  var evlistener = events[type];
  if (evlistener === undefined)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ?
    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events !== undefined) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener !== undefined) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}

function once(emitter, name) {
  return new Promise(function (resolve, reject) {
    function eventListener() {
      if (errorListener !== undefined) {
        emitter.removeListener('error', errorListener);
      }
      resolve([].slice.call(arguments));
    };
    var errorListener;

    // Adding an error listener is not optional because
    // if an error is thrown on an event emitter we cannot
    // guarantee that the actual event we are waiting will
    // be fired. The result could be a silent way to create
    // memory or file descriptor leaks, which is something
    // we should avoid.
    if (name !== 'error') {
      errorListener = function errorListener(err) {
        emitter.removeListener(name, eventListener);
        reject(err);
      };

      emitter.once('error', errorListener);
    }

    emitter.once(name, eventListener);
  });
}

},{}],37:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}

},{}],38:[function(require,module,exports){
/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
(function (root, definition) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define(definition);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = definition();
    } else {
        root.log = definition();
    }
}(this, function () {
    "use strict";

    // Slightly dubious tricks to cut down minimized file size
    var noop = function() {};
    var undefinedType = "undefined";
    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
        /Trident\/|MSIE /.test(window.navigator.userAgent)
    );

    var logMethods = [
        "trace",
        "debug",
        "info",
        "warn",
        "error"
    ];

    // Cross-browser bind equivalent that works at least back to IE6
    function bindMethod(obj, methodName) {
        var method = obj[methodName];
        if (typeof method.bind === 'function') {
            return method.bind(obj);
        } else {
            try {
                return Function.prototype.bind.call(method, obj);
            } catch (e) {
                // Missing bind shim or IE8 + Modernizr, fallback to wrapping
                return function() {
                    return Function.prototype.apply.apply(method, [obj, arguments]);
                };
            }
        }
    }

    // Trace() doesn't print the message in IE, so for that case we need to wrap it
    function traceForIE() {
        if (console.log) {
            if (console.log.apply) {
                console.log.apply(console, arguments);
            } else {
                // In old IE, native console methods themselves don't have apply().
                Function.prototype.apply.apply(console.log, [console, arguments]);
            }
        }
        if (console.trace) console.trace();
    }

    // Build the best logging method possible for this env
    // Wherever possible we want to bind, not wrap, to preserve stack traces
    function realMethod(methodName) {
        if (methodName === 'debug') {
            methodName = 'log';
        }

        if (typeof console === undefinedType) {
            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
        } else if (methodName === 'trace' && isIE) {
            return traceForIE;
        } else if (console[methodName] !== undefined) {
            return bindMethod(console, methodName);
        } else if (console.log !== undefined) {
            return bindMethod(console, 'log');
        } else {
            return noop;
        }
    }

    // These private functions always need `this` to be set properly

    function replaceLoggingMethods(level, loggerName) {
        /*jshint validthis:true */
        for (var i = 0; i < logMethods.length; i++) {
            var methodName = logMethods[i];
            this[methodName] = (i < level) ?
                noop :
                this.methodFactory(methodName, level, loggerName);
        }

        // Define log.log as an alias for log.debug
        this.log = this.debug;
    }

    // In old IE versions, the console isn't present until you first open it.
    // We build realMethod() replacements here that regenerate logging methods
    function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
        return function () {
            if (typeof console !== undefinedType) {
                replaceLoggingMethods.call(this, level, loggerName);
                this[methodName].apply(this, arguments);
            }
        };
    }

    // By default, we use closely bound real methods wherever possible, and
    // otherwise we wait for a console to appear, and then try again.
    function defaultMethodFactory(methodName, level, loggerName) {
        /*jshint validthis:true */
        return realMethod(methodName) ||
               enableLoggingWhenConsoleArrives.apply(this, arguments);
    }

    function Logger(name, defaultLevel, factory) {
      var self = this;
      var currentLevel;

      var storageKey = "loglevel";
      if (typeof name === "string") {
        storageKey += ":" + name;
      } else if (typeof name === "symbol") {
        storageKey = undefined;
      }

      function persistLevelIfPossible(levelNum) {
          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();

          if (typeof window === undefinedType || !storageKey) return;

          // Use localStorage if available
          try {
              window.localStorage[storageKey] = levelName;
              return;
          } catch (ignore) {}

          // Use session cookie as fallback
          try {
              window.document.cookie =
                encodeURIComponent(storageKey) + "=" + levelName + ";";
          } catch (ignore) {}
      }

      function getPersistedLevel() {
          var storedLevel;

          if (typeof window === undefinedType || !storageKey) return;

          try {
              storedLevel = window.localStorage[storageKey];
          } catch (ignore) {}

          // Fallback to cookies if local storage gives us nothing
          if (typeof storedLevel === undefinedType) {
              try {
                  var cookie = window.document.cookie;
                  var location = cookie.indexOf(
                      encodeURIComponent(storageKey) + "=");
                  if (location !== -1) {
                      storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
                  }
              } catch (ignore) {}
          }

          // If the stored level is not valid, treat it as if nothing was stored.
          if (self.levels[storedLevel] === undefined) {
              storedLevel = undefined;
          }

          return storedLevel;
      }

      /*
       *
       * Public logger API - see https://github.com/pimterry/loglevel for details
       *
       */

      self.name = name;

      self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
          "ERROR": 4, "SILENT": 5};

      self.methodFactory = factory || defaultMethodFactory;

      self.getLevel = function () {
          return currentLevel;
      };

      self.setLevel = function (level, persist) {
          if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
              level = self.levels[level.toUpperCase()];
          }
          if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
              currentLevel = level;
              if (persist !== false) {  // defaults to true
                  persistLevelIfPossible(level);
              }
              replaceLoggingMethods.call(self, level, name);
              if (typeof console === undefinedType && level < self.levels.SILENT) {
                  return "No console available for logging";
              }
          } else {
              throw "log.setLevel() called with invalid level: " + level;
          }
      };

      self.setDefaultLevel = function (level) {
          if (!getPersistedLevel()) {
              self.setLevel(level, false);
          }
      };

      self.enableAll = function(persist) {
          self.setLevel(self.levels.TRACE, persist);
      };

      self.disableAll = function(persist) {
          self.setLevel(self.levels.SILENT, persist);
      };

      // Initialize with the right level
      var initialLevel = getPersistedLevel();
      if (initialLevel == null) {
          initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
      }
      self.setLevel(initialLevel, false);
    }

    /*
     *
     * Top-level API
     *
     */

    var defaultLogger = new Logger();

    var _loggersByName = {};
    defaultLogger.getLogger = function getLogger(name) {
        if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
          throw new TypeError("You must supply a name when creating a logger.");
        }

        var logger = _loggersByName[name];
        if (!logger) {
          logger = _loggersByName[name] = new Logger(
            name, defaultLogger.getLevel(), defaultLogger.methodFactory);
        }
        return logger;
    };

    // Grab the current global log variable in case of overwrite
    var _log = (typeof window !== undefinedType) ? window.log : undefined;
    defaultLogger.noConflict = function() {
        if (typeof window !== undefinedType &&
               window.log === defaultLogger) {
            window.log = _log;
        }

        return defaultLogger;
    };

    defaultLogger.getLoggers = function getLoggers() {
        return _loggersByName;
    };

    // ES6 default export, for compatibility
    defaultLogger['default'] = defaultLogger;

    return defaultLogger;
}));

},{}],39:[function(require,module,exports){
'use strict';
const retry = require('retry');

const networkErrorMsgs = [
	'Failed to fetch', // Chrome
	'NetworkError when attempting to fetch resource', // Firefox
	'The Internet connection appears to be offline', // Safari
	'Network request failed' // `cross-fetch`
];

class AbortError extends Error {
	constructor(message) {
		super();

		if (message instanceof Error) {
			this.originalError = message;
			({message} = message);
		} else {
			this.originalError = new Error(message);
			this.originalError.stack = this.stack;
		}

		this.name = 'AbortError';
		this.message = message;
	}
}

const decorateErrorWithCounts = (error, attemptNumber, options) => {
	// Minus 1 from attemptNumber because the first attempt does not count as a retry
	const retriesLeft = options.retries - (attemptNumber - 1);

	error.attemptNumber = attemptNumber;
	error.retriesLeft = retriesLeft;
	return error;
};

const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);

const pRetry = (input, options) => new Promise((resolve, reject) => {
	options = {
		onFailedAttempt: () => {},
		retries: 10,
		...options
	};

	const operation = retry.operation(options);

	operation.attempt(async attemptNumber => {
		try {
			resolve(await input(attemptNumber));
		} catch (error) {
			if (!(error instanceof Error)) {
				reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
				return;
			}

			if (error instanceof AbortError) {
				operation.stop();
				reject(error.originalError);
			} else if (error instanceof TypeError && !isNetworkError(error.message)) {
				operation.stop();
				reject(error);
			} else {
				decorateErrorWithCounts(error, attemptNumber, options);

				try {
					await options.onFailedAttempt(error);
				} catch (error) {
					reject(error);
					return;
				}

				if (!operation.retry(error)) {
					reject(operation.mainError());
				}
			}
		}
	});
});

module.exports = pRetry;
// TODO: remove this in the next major version
module.exports.default = pRetry;

module.exports.AbortError = AbortError;

},{"retry":50}],40:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}],41:[function(require,module,exports){
'use strict';

var replace = String.prototype.replace;
var percentTwenties = /%20/g;

var Format = {
    RFC1738: 'RFC1738',
    RFC3986: 'RFC3986'
};

module.exports = {
    'default': Format.RFC3986,
    formatters: {
        RFC1738: function (value) {
            return replace.call(value, percentTwenties, '+');
        },
        RFC3986: function (value) {
            return String(value);
        }
    },
    RFC1738: Format.RFC1738,
    RFC3986: Format.RFC3986
};

},{}],42:[function(require,module,exports){
'use strict';

var stringify = require('./stringify');
var parse = require('./parse');
var formats = require('./formats');

module.exports = {
    formats: formats,
    parse: parse,
    stringify: stringify
};

},{"./formats":41,"./parse":43,"./stringify":44}],43:[function(require,module,exports){
'use strict';

var utils = require('./utils');

var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;

var defaults = {
    allowDots: false,
    allowPrototypes: false,
    arrayLimit: 20,
    charset: 'utf-8',
    charsetSentinel: false,
    comma: false,
    decoder: utils.decode,
    delimiter: '&',
    depth: 5,
    ignoreQueryPrefix: false,
    interpretNumericEntities: false,
    parameterLimit: 1000,
    parseArrays: true,
    plainObjects: false,
    strictNullHandling: false
};

var interpretNumericEntities = function (str) {
    return str.replace(/&#(\d+);/g, function ($0, numberStr) {
        return String.fromCharCode(parseInt(numberStr, 10));
    });
};

var parseArrayValue = function (val, options) {
    if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
        return val.split(',');
    }

    return val;
};

// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')

// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')

var parseValues = function parseQueryStringValues(str, options) {
    var obj = {};
    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
    var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
    var parts = cleanStr.split(options.delimiter, limit);
    var skipIndex = -1; // Keep track of where the utf8 sentinel was found
    var i;

    var charset = options.charset;
    if (options.charsetSentinel) {
        for (i = 0; i < parts.length; ++i) {
            if (parts[i].indexOf('utf8=') === 0) {
                if (parts[i] === charsetSentinel) {
                    charset = 'utf-8';
                } else if (parts[i] === isoSentinel) {
                    charset = 'iso-8859-1';
                }
                skipIndex = i;
                i = parts.length; // The eslint settings do not allow break;
            }
        }
    }

    for (i = 0; i < parts.length; ++i) {
        if (i === skipIndex) {
            continue;
        }
        var part = parts[i];

        var bracketEqualsPos = part.indexOf(']=');
        var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;

        var key, val;
        if (pos === -1) {
            key = options.decoder(part, defaults.decoder, charset, 'key');
            val = options.strictNullHandling ? null : '';
        } else {
            key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
            val = utils.maybeMap(
                parseArrayValue(part.slice(pos + 1), options),
                function (encodedVal) {
                    return options.decoder(encodedVal, defaults.decoder, charset, 'value');
                }
            );
        }

        if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
            val = interpretNumericEntities(val);
        }

        if (part.indexOf('[]=') > -1) {
            val = isArray(val) ? [val] : val;
        }

        if (has.call(obj, key)) {
            obj[key] = utils.combine(obj[key], val);
        } else {
            obj[key] = val;
        }
    }

    return obj;
};

var parseObject = function (chain, val, options, valuesParsed) {
    var leaf = valuesParsed ? val : parseArrayValue(val, options);

    for (var i = chain.length - 1; i >= 0; --i) {
        var obj;
        var root = chain[i];

        if (root === '[]' && options.parseArrays) {
            obj = [].concat(leaf);
        } else {
            obj = options.plainObjects ? Object.create(null) : {};
            var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
            var index = parseInt(cleanRoot, 10);
            if (!options.parseArrays && cleanRoot === '') {
                obj = { 0: leaf };
            } else if (
                !isNaN(index)
                && root !== cleanRoot
                && String(index) === cleanRoot
                && index >= 0
                && (options.parseArrays && index <= options.arrayLimit)
            ) {
                obj = [];
                obj[index] = leaf;
            } else {
                obj[cleanRoot] = leaf;
            }
        }

        leaf = obj;
    }

    return leaf;
};

var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
    if (!givenKey) {
        return;
    }

    // Transform dot notation to bracket notation
    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;

    // The regex chunks

    var brackets = /(\[[^[\]]*])/;
    var child = /(\[[^[\]]*])/g;

    // Get the parent

    var segment = options.depth > 0 && brackets.exec(key);
    var parent = segment ? key.slice(0, segment.index) : key;

    // Stash the parent if it exists

    var keys = [];
    if (parent) {
        // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
        if (!options.plainObjects && has.call(Object.prototype, parent)) {
            if (!options.allowPrototypes) {
                return;
            }
        }

        keys.push(parent);
    }

    // Loop through children appending to the array until we hit depth

    var i = 0;
    while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
        i += 1;
        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
            if (!options.allowPrototypes) {
                return;
            }
        }
        keys.push(segment[1]);
    }

    // If there's a remainder, just add whatever is left

    if (segment) {
        keys.push('[' + key.slice(segment.index) + ']');
    }

    return parseObject(keys, val, options, valuesParsed);
};

var normalizeParseOptions = function normalizeParseOptions(opts) {
    if (!opts) {
        return defaults;
    }

    if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
        throw new TypeError('Decoder has to be a function.');
    }

    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    }
    var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;

    return {
        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
        allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
        arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
        charset: charset,
        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
        comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
        decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
        delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
        depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
        interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
        parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
        parseArrays: opts.parseArrays !== false,
        plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
    };
};

module.exports = function (str, opts) {
    var options = normalizeParseOptions(opts);

    if (str === '' || str === null || typeof str === 'undefined') {
        return options.plainObjects ? Object.create(null) : {};
    }

    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
    var obj = options.plainObjects ? Object.create(null) : {};

    // Iterate over the keys and setup the new object

    var keys = Object.keys(tempObj);
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
        obj = utils.merge(obj, newObj, options);
    }

    return utils.compact(obj);
};

},{"./utils":45}],44:[function(require,module,exports){
'use strict';

var utils = require('./utils');
var formats = require('./formats');
var has = Object.prototype.hasOwnProperty;

var arrayPrefixGenerators = {
    brackets: function brackets(prefix) {
        return prefix + '[]';
    },
    comma: 'comma',
    indices: function indices(prefix, key) {
        return prefix + '[' + key + ']';
    },
    repeat: function repeat(prefix) {
        return prefix;
    }
};

var isArray = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function (arr, valueOrArray) {
    push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
};

var toISO = Date.prototype.toISOString;

var defaultFormat = formats['default'];
var defaults = {
    addQueryPrefix: false,
    allowDots: false,
    charset: 'utf-8',
    charsetSentinel: false,
    delimiter: '&',
    encode: true,
    encoder: utils.encode,
    encodeValuesOnly: false,
    format: defaultFormat,
    formatter: formats.formatters[defaultFormat],
    // deprecated
    indices: false,
    serializeDate: function serializeDate(date) {
        return toISO.call(date);
    },
    skipNulls: false,
    strictNullHandling: false
};

var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
    return typeof v === 'string'
        || typeof v === 'number'
        || typeof v === 'boolean'
        || typeof v === 'symbol'
        || typeof v === 'bigint';
};

var stringify = function stringify(
    object,
    prefix,
    generateArrayPrefix,
    strictNullHandling,
    skipNulls,
    encoder,
    filter,
    sort,
    allowDots,
    serializeDate,
    format,
    formatter,
    encodeValuesOnly,
    charset
) {
    var obj = object;
    if (typeof filter === 'function') {
        obj = filter(prefix, obj);
    } else if (obj instanceof Date) {
        obj = serializeDate(obj);
    } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
        obj = utils.maybeMap(obj, function (value) {
            if (value instanceof Date) {
                return serializeDate(value);
            }
            return value;
        });
    }

    if (obj === null) {
        if (strictNullHandling) {
            return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
        }

        obj = '';
    }

    if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
        if (encoder) {
            var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
            return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
        }
        return [formatter(prefix) + '=' + formatter(String(obj))];
    }

    var values = [];

    if (typeof obj === 'undefined') {
        return values;
    }

    var objKeys;
    if (generateArrayPrefix === 'comma' && isArray(obj)) {
        // we need to join elements in
        objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];
    } else if (isArray(filter)) {
        objKeys = filter;
    } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
    }

    for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];
        var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];

        if (skipNulls && value === null) {
            continue;
        }

        var keyPrefix = isArray(obj)
            ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
            : prefix + (allowDots ? '.' + key : '[' + key + ']');

        pushToArray(values, stringify(
            value,
            keyPrefix,
            generateArrayPrefix,
            strictNullHandling,
            skipNulls,
            encoder,
            filter,
            sort,
            allowDots,
            serializeDate,
            format,
            formatter,
            encodeValuesOnly,
            charset
        ));
    }

    return values;
};

var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
    if (!opts) {
        return defaults;
    }

    if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
        throw new TypeError('Encoder has to be a function.');
    }

    var charset = opts.charset || defaults.charset;
    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    }

    var format = formats['default'];
    if (typeof opts.format !== 'undefined') {
        if (!has.call(formats.formatters, opts.format)) {
            throw new TypeError('Unknown format option provided.');
        }
        format = opts.format;
    }
    var formatter = formats.formatters[format];

    var filter = defaults.filter;
    if (typeof opts.filter === 'function' || isArray(opts.filter)) {
        filter = opts.filter;
    }

    return {
        addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
        charset: charset,
        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
        delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
        encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
        encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
        encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
        filter: filter,
        format: format,
        formatter: formatter,
        serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
        skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
        sort: typeof opts.sort === 'function' ? opts.sort : null,
        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
    };
};

module.exports = function (object, opts) {
    var obj = object;
    var options = normalizeStringifyOptions(opts);

    var objKeys;
    var filter;

    if (typeof options.filter === 'function') {
        filter = options.filter;
        obj = filter('', obj);
    } else if (isArray(options.filter)) {
        filter = options.filter;
        objKeys = filter;
    }

    var keys = [];

    if (typeof obj !== 'object' || obj === null) {
        return '';
    }

    var arrayFormat;
    if (opts && opts.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = opts.arrayFormat;
    } else if (opts && 'indices' in opts) {
        arrayFormat = opts.indices ? 'indices' : 'repeat';
    } else {
        arrayFormat = 'indices';
    }

    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];

    if (!objKeys) {
        objKeys = Object.keys(obj);
    }

    if (options.sort) {
        objKeys.sort(options.sort);
    }

    for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];

        if (options.skipNulls && obj[key] === null) {
            continue;
        }
        pushToArray(keys, stringify(
            obj[key],
            key,
            generateArrayPrefix,
            options.strictNullHandling,
            options.skipNulls,
            options.encode ? options.encoder : null,
            options.filter,
            options.sort,
            options.allowDots,
            options.serializeDate,
            options.format,
            options.formatter,
            options.encodeValuesOnly,
            options.charset
        ));
    }

    var joined = keys.join(options.delimiter);
    var prefix = options.addQueryPrefix === true ? '?' : '';

    if (options.charsetSentinel) {
        if (options.charset === 'iso-8859-1') {
            // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
            prefix += 'utf8=%26%2310003%3B&';
        } else {
            // encodeURIComponent('✓')
            prefix += 'utf8=%E2%9C%93&';
        }
    }

    return joined.length > 0 ? prefix + joined : '';
};

},{"./formats":41,"./utils":45}],45:[function(require,module,exports){
'use strict';

var formats = require('./formats');

var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;

var hexTable = (function () {
    var array = [];
    for (var i = 0; i < 256; ++i) {
        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
    }

    return array;
}());

var compactQueue = function compactQueue(queue) {
    while (queue.length > 1) {
        var item = queue.pop();
        var obj = item.obj[item.prop];

        if (isArray(obj)) {
            var compacted = [];

            for (var j = 0; j < obj.length; ++j) {
                if (typeof obj[j] !== 'undefined') {
                    compacted.push(obj[j]);
                }
            }

            item.obj[item.prop] = compacted;
        }
    }
};

var arrayToObject = function arrayToObject(source, options) {
    var obj = options && options.plainObjects ? Object.create(null) : {};
    for (var i = 0; i < source.length; ++i) {
        if (typeof source[i] !== 'undefined') {
            obj[i] = source[i];
        }
    }

    return obj;
};

var merge = function merge(target, source, options) {
    /* eslint no-param-reassign: 0 */
    if (!source) {
        return target;
    }

    if (typeof source !== 'object') {
        if (isArray(target)) {
            target.push(source);
        } else if (target && typeof target === 'object') {
            if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
                target[source] = true;
            }
        } else {
            return [target, source];
        }

        return target;
    }

    if (!target || typeof target !== 'object') {
        return [target].concat(source);
    }

    var mergeTarget = target;
    if (isArray(target) && !isArray(source)) {
        mergeTarget = arrayToObject(target, options);
    }

    if (isArray(target) && isArray(source)) {
        source.forEach(function (item, i) {
            if (has.call(target, i)) {
                var targetItem = target[i];
                if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
                    target[i] = merge(targetItem, item, options);
                } else {
                    target.push(item);
                }
            } else {
                target[i] = item;
            }
        });
        return target;
    }

    return Object.keys(source).reduce(function (acc, key) {
        var value = source[key];

        if (has.call(acc, key)) {
            acc[key] = merge(acc[key], value, options);
        } else {
            acc[key] = value;
        }
        return acc;
    }, mergeTarget);
};

var assign = function assignSingleSource(target, source) {
    return Object.keys(source).reduce(function (acc, key) {
        acc[key] = source[key];
        return acc;
    }, target);
};

var decode = function (str, decoder, charset) {
    var strWithoutPlus = str.replace(/\+/g, ' ');
    if (charset === 'iso-8859-1') {
        // unescape never throws, no try...catch needed:
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
    }
    // utf-8
    try {
        return decodeURIComponent(strWithoutPlus);
    } catch (e) {
        return strWithoutPlus;
    }
};

var encode = function encode(str, defaultEncoder, charset, kind, format) {
    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
    // It has been adapted here for stricter adherence to RFC 3986
    if (str.length === 0) {
        return str;
    }

    var string = str;
    if (typeof str === 'symbol') {
        string = Symbol.prototype.toString.call(str);
    } else if (typeof str !== 'string') {
        string = String(str);
    }

    if (charset === 'iso-8859-1') {
        return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
            return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
        });
    }

    var out = '';
    for (var i = 0; i < string.length; ++i) {
        var c = string.charCodeAt(i);

        if (
            c === 0x2D // -
            || c === 0x2E // .
            || c === 0x5F // _
            || c === 0x7E // ~
            || (c >= 0x30 && c <= 0x39) // 0-9
            || (c >= 0x41 && c <= 0x5A) // a-z
            || (c >= 0x61 && c <= 0x7A) // A-Z
            || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
        ) {
            out += string.charAt(i);
            continue;
        }

        if (c < 0x80) {
            out = out + hexTable[c];
            continue;
        }

        if (c < 0x800) {
            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }

        if (c < 0xD800 || c >= 0xE000) {
            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }

        i += 1;
        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
        out += hexTable[0xF0 | (c >> 18)]
            + hexTable[0x80 | ((c >> 12) & 0x3F)]
            + hexTable[0x80 | ((c >> 6) & 0x3F)]
            + hexTable[0x80 | (c & 0x3F)];
    }

    return out;
};

var compact = function compact(value) {
    var queue = [{ obj: { o: value }, prop: 'o' }];
    var refs = [];

    for (var i = 0; i < queue.length; ++i) {
        var item = queue[i];
        var obj = item.obj[item.prop];

        var keys = Object.keys(obj);
        for (var j = 0; j < keys.length; ++j) {
            var key = keys[j];
            var val = obj[key];
            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
                queue.push({ obj: obj, prop: key });
                refs.push(val);
            }
        }
    }

    compactQueue(queue);

    return value;
};

var isRegExp = function isRegExp(obj) {
    return Object.prototype.toString.call(obj) === '[object RegExp]';
};

var isBuffer = function isBuffer(obj) {
    if (!obj || typeof obj !== 'object') {
        return false;
    }

    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};

var combine = function combine(a, b) {
    return [].concat(a, b);
};

var maybeMap = function maybeMap(val, fn) {
    if (isArray(val)) {
        var mapped = [];
        for (var i = 0; i < val.length; i += 1) {
            mapped.push(fn(val[i]));
        }
        return mapped;
    }
    return fn(val);
};

module.exports = {
    arrayToObject: arrayToObject,
    assign: assign,
    combine: combine,
    compact: compact,
    decode: decode,
    encode: encode,
    isBuffer: isBuffer,
    isRegExp: isRegExp,
    maybeMap: maybeMap,
    merge: merge
};

},{"./formats":41}],46:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

module.exports = function(qs, sep, eq, options) {
  sep = sep || '&';
  eq = eq || '=';
  var obj = {};

  if (typeof qs !== 'string' || qs.length === 0) {
    return obj;
  }

  var regexp = /\+/g;
  qs = qs.split(sep);

  var maxKeys = 1000;
  if (options && typeof options.maxKeys === 'number') {
    maxKeys = options.maxKeys;
  }

  var len = qs.length;
  // maxKeys <= 0 means that we should not limit keys count
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }

  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, '%20'),
        idx = x.indexOf(eq),
        kstr, vstr, k, v;

    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = '';
    }

    k = decodeURIComponent(kstr);
    v = decodeURIComponent(vstr);

    if (!hasOwnProperty(obj, k)) {
      obj[k] = v;
    } else if (isArray(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }

  return obj;
};

var isArray = Array.isArray || function (xs) {
  return Object.prototype.toString.call(xs) === '[object Array]';
};

},{}],47:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

var stringifyPrimitive = function(v) {
  switch (typeof v) {
    case 'string':
      return v;

    case 'boolean':
      return v ? 'true' : 'false';

    case 'number':
      return isFinite(v) ? v : '';

    default:
      return '';
  }
};

module.exports = function(obj, sep, eq, name) {
  sep = sep || '&';
  eq = eq || '=';
  if (obj === null) {
    obj = undefined;
  }

  if (typeof obj === 'object') {
    return map(objectKeys(obj), function(k) {
      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
      if (isArray(obj[k])) {
        return map(obj[k], function(v) {
          return ks + encodeURIComponent(stringifyPrimitive(v));
        }).join(sep);
      } else {
        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
      }
    }).join(sep);

  }

  if (!name) return '';
  return encodeURIComponent(stringifyPrimitive(name)) + eq +
         encodeURIComponent(stringifyPrimitive(obj));
};

var isArray = Array.isArray || function (xs) {
  return Object.prototype.toString.call(xs) === '[object Array]';
};

function map (xs, f) {
  if (xs.map) return xs.map(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    res.push(f(xs[i], i));
  }
  return res;
}

var objectKeys = Object.keys || function (obj) {
  var res = [];
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  }
  return res;
};

},{}],48:[function(require,module,exports){
'use strict';

exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');

},{"./decode":46,"./encode":47}],49:[function(require,module,exports){
/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var runtime = (function (exports) {
  "use strict";

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined; // More compressible than void 0.
  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

  function define(obj, key, value) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
    return obj[key];
  }
  try {
    // IE 8 has a broken Object.defineProperty that only works on DOM objects.
    define({}, "");
  } catch (err) {
    define = function(obj, key, value) {
      return obj[key] = value;
    };
  }

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []);

    // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.
    generator._invoke = makeInvokeMethod(innerFn, self, context);

    return generator;
  }
  exports.wrap = wrap;

  // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.
  function tryCatch(fn, obj, arg) {
    try {
      return { type: "normal", arg: fn.call(obj, arg) };
    } catch (err) {
      return { type: "throw", arg: err };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}

  // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.
  var IteratorPrototype = {};
  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  if (NativeIteratorPrototype &&
      NativeIteratorPrototype !== Op &&
      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype =
    Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunction.displayName = define(
    GeneratorFunctionPrototype,
    toStringTagSymbol,
    "GeneratorFunction"
  );

  // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.
  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function(method) {
      define(prototype, method, function(arg) {
        return this._invoke(method, arg);
      });
    });
  }

  exports.isGeneratorFunction = function(genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor
      ? ctor === GeneratorFunction ||
        // For the native GeneratorFunction constructor, the best we can
        // do is to check its .name property.
        (ctor.displayName || ctor.name) === "GeneratorFunction"
      : false;
  };

  exports.mark = function(genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;
      define(genFun, toStringTagSymbol, "GeneratorFunction");
    }
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.
  exports.awrap = function(arg) {
    return { __await: arg };
  };

  function AsyncIterator(generator, PromiseImpl) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);
      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;
        if (value &&
            typeof value === "object" &&
            hasOwn.call(value, "__await")) {
          return PromiseImpl.resolve(value.__await).then(function(value) {
            invoke("next", value, resolve, reject);
          }, function(err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return PromiseImpl.resolve(value).then(function(unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration.
          result.value = unwrapped;
          resolve(result);
        }, function(error) {
          // If a rejected Promise was yielded, throw the rejection back
          // into the async generator function so it can be handled there.
          return invoke("throw", error, resolve, reject);
        });
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new PromiseImpl(function(resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise =
        // If enqueue has been called before, then we want to wait until
        // all previous Promises have been resolved before calling invoke,
        // so that results are always delivered in the correct order. If
        // enqueue has not been called before, then it is important to
        // call invoke immediately, without waiting on a callback to fire,
        // so that the async generator function has the opportunity to do
        // any necessary setup in a predictable way. This predictability
        // is why the Promise constructor synchronously invokes its
        // executor callback, and why async functions synchronously
        // execute code before the first await. Since we implement simple
        // async functions in terms of async generators, it is especially
        // important to get this right, even though it requires care.
        previousPromise ? previousPromise.then(
          callInvokeWithMethodAndArg,
          // Avoid propagating failures to Promises returned by later
          // invocations of the iterator.
          callInvokeWithMethodAndArg
        ) : callInvokeWithMethodAndArg();
    }

    // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).
    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);
  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };
  exports.AsyncIterator = AsyncIterator;

  // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.
  exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
    if (PromiseImpl === void 0) PromiseImpl = Promise;

    var iter = new AsyncIterator(
      wrap(innerFn, outerFn, self, tryLocsList),
      PromiseImpl
    );

    return exports.isGeneratorFunction(outerFn)
      ? iter // If outerFn is a generator, return the full iterator.
      : iter.next().then(function(result) {
          return result.done ? result.value : iter.next();
        });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;

    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        }

        // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);
          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;

        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);

        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;

        var record = tryCatch(innerFn, self, context);
        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };

        } else if (record.type === "throw") {
          state = GenStateCompleted;
          // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.
          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  }

  // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.
  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];
    if (method === undefined) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        // Note: ["return"] must be used for ES3 parsing compatibility.
        if (delegate.iterator["return"]) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError(
          "The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (! info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value;

      // Resume execution at the desired location (see delegateYield).
      context.next = delegate.nextLoc;

      // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.
      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined;
      }

    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    }

    // The delegate iterator is finished, so forget it and continue with
    // the outer generator.
    context.delegate = null;
    return ContinueSentinel;
  }

  // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.
  defineIteratorMethods(Gp);

  define(Gp, toStringTagSymbol, "Generator");

  // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.
  Gp[iteratorSymbol] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = { tryLoc: locs[0] };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  exports.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];
      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1, next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined;
          next.done = true;

          return next;
        };

        return next.next = next;
      }
    }

    // Return an iterator with no values.
    return { next: doneResult };
  }
  exports.values = values;

  function doneResult() {
    return { value: undefined, done: true };
  }

  Context.prototype = {
    constructor: Context,

    reset: function(skipTempReset) {
      this.prev = 0;
      this.next = 0;
      // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.
      this.sent = this._sent = undefined;
      this.done = false;
      this.delegate = null;

      this.method = "next";
      this.arg = undefined;

      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" &&
              hasOwn.call(this, name) &&
              !isNaN(+name.slice(1))) {
            this[name] = undefined;
          }
        }
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined;
        }

        return !! caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    abrupt: function(type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") &&
            this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry &&
          (type === "break" ||
           type === "continue") &&
          finallyEntry.tryLoc <= arg &&
          arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },

    complete: function(record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined;
      }

      return ContinueSentinel;
    }
  };

  // Regardless of whether this script is executing as a CommonJS module
  // or not, return the runtime object so that we can declare the variable
  // regeneratorRuntime in the outer scope, which allows this module to be
  // injected easily by `bin/regenerator --include-runtime script.js`.
  return exports;

}(
  // If this script is executing as a CommonJS module, use module.exports
  // as the regeneratorRuntime namespace. Otherwise create a new empty
  // object. Either way, the resulting object will be used to initialize
  // the regeneratorRuntime variable at the top of this file.
  typeof module === "object" ? module.exports : {}
));

try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  // This module should not be running in strict mode, so the above
  // assignment should always work unless something is misconfigured. Just
  // in case runtime.js accidentally runs in strict mode, we can escape
  // strict mode using a global Function call. This could conceivably fail
  // if a Content Security Policy forbids using Function, but in that case
  // the proper solution is to fix the accidental strict mode problem. If
  // you've misconfigured your bundler to force strict mode and applied a
  // CSP to forbid Function, and you're not willing to fix either of those
  // problems, please detail your unique predicament in a GitHub issue.
  Function("r", "regeneratorRuntime = r")(runtime);
}

},{}],50:[function(require,module,exports){
module.exports = require('./lib/retry');
},{"./lib/retry":51}],51:[function(require,module,exports){
var RetryOperation = require('./retry_operation');

exports.operation = function(options) {
  var timeouts = exports.timeouts(options);
  return new RetryOperation(timeouts, {
      forever: options && options.forever,
      unref: options && options.unref,
      maxRetryTime: options && options.maxRetryTime
  });
};

exports.timeouts = function(options) {
  if (options instanceof Array) {
    return [].concat(options);
  }

  var opts = {
    retries: 10,
    factor: 2,
    minTimeout: 1 * 1000,
    maxTimeout: Infinity,
    randomize: false
  };
  for (var key in options) {
    opts[key] = options[key];
  }

  if (opts.minTimeout > opts.maxTimeout) {
    throw new Error('minTimeout is greater than maxTimeout');
  }

  var timeouts = [];
  for (var i = 0; i < opts.retries; i++) {
    timeouts.push(this.createTimeout(i, opts));
  }

  if (options && options.forever && !timeouts.length) {
    timeouts.push(this.createTimeout(i, opts));
  }

  // sort the array numerically ascending
  timeouts.sort(function(a,b) {
    return a - b;
  });

  return timeouts;
};

exports.createTimeout = function(attempt, opts) {
  var random = (opts.randomize)
    ? (Math.random() + 1)
    : 1;

  var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  timeout = Math.min(timeout, opts.maxTimeout);

  return timeout;
};

exports.wrap = function(obj, options, methods) {
  if (options instanceof Array) {
    methods = options;
    options = null;
  }

  if (!methods) {
    methods = [];
    for (var key in obj) {
      if (typeof obj[key] === 'function') {
        methods.push(key);
      }
    }
  }

  for (var i = 0; i < methods.length; i++) {
    var method   = methods[i];
    var original = obj[method];

    obj[method] = function retryWrapper(original) {
      var op       = exports.operation(options);
      var args     = Array.prototype.slice.call(arguments, 1);
      var callback = args.pop();

      args.push(function(err) {
        if (op.retry(err)) {
          return;
        }
        if (err) {
          arguments[0] = op.mainError();
        }
        callback.apply(this, arguments);
      });

      op.attempt(function() {
        original.apply(obj, args);
      });
    }.bind(obj, original);
    obj[method].options = options;
  }
};

},{"./retry_operation":52}],52:[function(require,module,exports){
function RetryOperation(timeouts, options) {
  // Compatibility for the old (timeouts, retryForever) signature
  if (typeof options === 'boolean') {
    options = { forever: options };
  }

  this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
  this._timeouts = timeouts;
  this._options = options || {};
  this._maxRetryTime = options && options.maxRetryTime || Infinity;
  this._fn = null;
  this._errors = [];
  this._attempts = 1;
  this._operationTimeout = null;
  this._operationTimeoutCb = null;
  this._timeout = null;
  this._operationStart = null;

  if (this._options.forever) {
    this._cachedTimeouts = this._timeouts.slice(0);
  }
}
module.exports = RetryOperation;

RetryOperation.prototype.reset = function() {
  this._attempts = 1;
  this._timeouts = this._originalTimeouts;
}

RetryOperation.prototype.stop = function() {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }

  this._timeouts       = [];
  this._cachedTimeouts = null;
};

RetryOperation.prototype.retry = function(err) {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }

  if (!err) {
    return false;
  }
  var currentTime = new Date().getTime();
  if (err && currentTime - this._operationStart >= this._maxRetryTime) {
    this._errors.unshift(new Error('RetryOperation timeout occurred'));
    return false;
  }

  this._errors.push(err);

  var timeout = this._timeouts.shift();
  if (timeout === undefined) {
    if (this._cachedTimeouts) {
      // retry forever, only keep last error
      this._errors.splice(this._errors.length - 1, this._errors.length);
      this._timeouts = this._cachedTimeouts.slice(0);
      timeout = this._timeouts.shift();
    } else {
      return false;
    }
  }

  var self = this;
  var timer = setTimeout(function() {
    self._attempts++;

    if (self._operationTimeoutCb) {
      self._timeout = setTimeout(function() {
        self._operationTimeoutCb(self._attempts);
      }, self._operationTimeout);

      if (self._options.unref) {
          self._timeout.unref();
      }
    }

    self._fn(self._attempts);
  }, timeout);

  if (this._options.unref) {
      timer.unref();
  }

  return true;
};

RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  this._fn = fn;

  if (timeoutOps) {
    if (timeoutOps.timeout) {
      this._operationTimeout = timeoutOps.timeout;
    }
    if (timeoutOps.cb) {
      this._operationTimeoutCb = timeoutOps.cb;
    }
  }

  var self = this;
  if (this._operationTimeoutCb) {
    this._timeout = setTimeout(function() {
      self._operationTimeoutCb();
    }, self._operationTimeout);
  }

  this._operationStart = new Date().getTime();

  this._fn(this._attempts);
};

RetryOperation.prototype.try = function(fn) {
  console.log('Using RetryOperation.try() is deprecated');
  this.attempt(fn);
};

RetryOperation.prototype.start = function(fn) {
  console.log('Using RetryOperation.start() is deprecated');
  this.attempt(fn);
};

RetryOperation.prototype.start = RetryOperation.prototype.try;

RetryOperation.prototype.errors = function() {
  return this._errors;
};

RetryOperation.prototype.attempts = function() {
  return this._attempts;
};

RetryOperation.prototype.mainError = function() {
  if (this._errors.length === 0) {
    return null;
  }

  var counts = {};
  var mainError = null;
  var mainErrorCount = 0;

  for (var i = 0; i < this._errors.length; i++) {
    var error = this._errors[i];
    var message = error.message;
    var count = (counts[message] || 0) + 1;

    counts[message] = count;

    if (count >= mainErrorCount) {
      mainError = error;
      mainErrorCount = count;
    }
  }

  return mainError;
};

},{}],53:[function(require,module,exports){
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.prototype = Object.create(Buffer.prototype)

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}

},{"buffer":34}],54:[function(require,module,exports){
module.exports={
  "0": "O",
  "1": "l",
  "֭": "֖",
  "֮": "֘",
  "֨": "֙",
  "֤": "֚",
  "᪴": "ۛ",
  "⃛": "ۛ",
  "ؙ": "̓",
  "ࣳ": "̓",
  "̓": "̓",
  "̕": "̓",
  "ُ": "̓",
  "ٝ": "̔",
  "֜": "́",
  "֝": "́",
  "ؘ": "́",
  "݇": "́",
  "́": "́",
  "॔": "́",
  "َ": "́",
  "̀": "̀",
  "॓": "̀",
  "̌": "̆",
  "꙼": "̆",
  "٘": "̆",
  "ٚ": "̆",
  "ͮ": "̆",
  "ۨ": "̆̇",
  "̐": "̆̇",
  "ँ": "̆̇",
  "ঁ": "̆̇",
  "ઁ": "̆̇",
  "ଁ": "̆̇",
  "ఀ": "̆̇",
  "ಁ": "̆̇",
  "ഁ": "̆̇",
  "𑒿": "̆̇",
  "᳐": "̂",
  "̑": "̂",
  "ٛ": "̂",
  "߮": "̂",
  "꛰": "̂",
  "֯": "̊",
  "۟": "̊",
  "៓": "̊",
  "゚": "̊",
  "ْ": "̊",
  "ஂ": "̊",
  "ံ": "̊",
  "ំ": "̊",
  "𑌀": "̊",
  "ํ": "̊",
  "ໍ": "̊",
  "ͦ": "̊",
  "ⷪ": "̊",
  "࣫": "̈",
  "߳": "̈",
  "ً": "̋",
  "ࣰ": "̋",
  "͂": "̃",
  "ٓ": "̃",
  "ׄ": "̇",
  "۬": "̇",
  "݀": "̇",
  "࣪": "̇",
  "݁": "̇",
  "͘": "̇",
  "ֹ": "̇",
  "ֺ": "̇",
  "ׂ": "̇",
  "ׁ": "̇",
  "߭": "̇",
  "ं": "̇",
  "ਂ": "̇",
  "ં": "̇",
  "்": "̇",
  "̷": "̸",
  "᪷": "̨",
  "̢": "̨",
  "ͅ": "̨",
  "᳒": "̄",
  "̅": "̄",
  "ٙ": "̄",
  "߫": "̄",
  "꛱": "̄",
  "᳚": "̎",
  "ٗ": "̒",
  "͗": "͐",
  "ࣿ": "͐",
  "ࣸ": "͐",
  "ऀ": "͒",
  "᳭": "̖",
  "᳜": "̩",
  "ٖ": "̩",
  "᳕": "̫",
  "͇": "̳",
  "ࣹ": "͔",
  "ࣺ": "͕",
  "゛": "ﾞ",
  "゜": "ﾟ",
  "̶": "̵",
  "〬": "̉",
  "ׅ": "̣",
  "࣭": "̣",
  "᳝": "̣",
  "ִ": "̣",
  "ٜ": "̣",
  "़": "̣",
  "়": "̣",
  "਼": "̣",
  "઼": "̣",
  "଼": "̣",
  "𑇊": "̣",
  "𑓃": "̣",
  "𐨺": "̣",
  "࣮": "̤",
  "᳞": "̤",
  "༷": "̥",
  "〭": "̥",
  "̧": "̦",
  "̡": "̦",
  "̹": "̦",
  "᳙": "̭",
  "᳘": "̮",
  "॒": "̱",
  "̠": "̱",
  "ࣱ": "ٌ",
  "ࣨ": "ٌ",
  "ࣥ": "ٌ",
  "ﱞ": "ﹲّ",
  "ࣲ": "ٍ",
  "ﱟ": "ﹴّ",
  "ﳲ": "ﹷّ",
  "ﱠ": "ﹶّ",
  "ﳳ": "ﹹّ",
  "ﱡ": "ﹸّ",
  "ؚ": "ِ",
  "̗": "ِ",
  "ﳴ": "ﹻّ",
  "ﱢ": "ﹺّ",
  "ﱣ": "ﹼٰ",
  "ٟ": "ٕ",
  "̍": "ٰ",
  "݂": "ܼ",
  "ਃ": "ঃ",
  "ః": "ঃ",
  "ಃ": "ঃ",
  "ഃ": "ঃ",
  "ඃ": "ঃ",
  "း": "ঃ",
  "𑓁": "ঃ",
  "់": "่",
  "່": "่",
  "້": "้",
  "໊": "๊",
  "໋": "๋",
  "꙯": "⃩",
  "\u2028": " ",
  "\u2029": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  " ": " ",
  "ߺ": "_",
  "﹍": "_",
  "﹎": "_",
  "﹏": "_",
  "‐": "-",
  "‑": "-",
  "‒": "-",
  "–": "-",
  "﹘": "-",
  "۔": "-",
  "⁃": "-",
  "˗": "-",
  "−": "-",
  "➖": "-",
  "Ⲻ": "-",
  "⨩": "-̓",
  "⸚": "-̈",
  "﬩": "-̇",
  "∸": "-̇",
  "⨪": "-̣",
  "꓾": "-.",
  "～": "〜",
  "؍": ",",
  "٫": ",",
  "‚": ",",
  "¸": ",",
  "ꓹ": ",",
  "⸲": "،",
  "٬": "،",
  ";": ";",
  "⸵": "؛",
  "ः": ":",
  "ઃ": ":",
  "：": ":",
  "։": ":",
  "܃": ":",
  "܄": ":",
  "᛬": ":",
  "︰": ":",
  "᠃": ":",
  "᠉": ":",
  "⁚": ":",
  "׃": ":",
  "˸": ":",
  "꞉": ":",
  "∶": ":",
  "ː": ":",
  "ꓽ": ":",
  "⩴": "::=",
  "⧴": ":→",
  "！": "!",
  "ǃ": "!",
  "ⵑ": "!",
  "‼": "!!",
  "⁉": "!?",
  "ʔ": "?",
  "Ɂ": "?",
  "ॽ": "?",
  "Ꭾ": "?",
  "ꛫ": "?",
  "⁈": "?!",
  "⁇": "??",
  "⸮": "؟",
  "𝅭": ".",
  "․": ".",
  "܁": ".",
  "܂": ".",
  "꘎": ".",
  "𐩐": ".",
  "٠": ".",
  "۰": ".",
  "ꓸ": ".",
  "ꓻ": ".,",
  "‥": "..",
  "ꓺ": "..",
  "…": "...",
  "꛴": "꛳꛳",
  "・": "·",
  "･": "·",
  "᛫": "·",
  "·": "·",
  "⸱": "·",
  "𐄁": "·",
  "•": "·",
  "‧": "·",
  "∙": "·",
  "⋅": "·",
  "ꞏ": "·",
  "ᐧ": "·",
  "⋯": "···",
  "ⵈ": "···",
  "ᑄ": "·<",
  "⋗": "·>",
  "ᐷ": "·>",
  "ᑀ": "·>",
  "ᔯ": "·4",
  "ᑾ": "·b",
  "ᒀ": "·ḃ",
  "ᑺ": "·d",
  "ᒘ": "·J",
  "ᒶ": "·L",
  "ᑶ": "·P",
  "ᑗ": "·U",
  "ᐺ": "·V",
  "ᐼ": "·Ʌ",
  "ᒮ": "·Γ",
  "ᐎ": "·Δ",
  "ᑙ": "·Ո",
  "ᐌ": "·ᐁ",
  "ᐐ": "·ᐄ",
  "ᐒ": "·ᐅ",
  "ᐔ": "·ᐆ",
  "ᐗ": "·ᐊ",
  "ᐙ": "·ᐋ",
  "ᐾ": "·ᐲ",
  "ᑂ": "·ᐴ",
  "ᑆ": "·ᐹ",
  "ᑛ": "·ᑏ",
  "ᑔ": "·ᑐ",
  "ᑝ": "·ᑐ",
  "ᑟ": "·ᑑ",
  "ᑡ": "·ᑕ",
  "ᑣ": "·ᑖ",
  "ᑴ": "·ᑫ",
  "ᑸ": "·ᑮ",
  "ᑼ": "·ᑰ",
  "ᒒ": "·ᒉ",
  "ᒔ": "·ᒋ",
  "ᒖ": "·ᒌ",
  "ᒚ": "·ᒎ",
  "ᒜ": "·ᒐ",
  "ᒞ": "·ᒑ",
  "ᒬ": "·ᒣ",
  "ᒰ": "·ᒦ",
  "ᒲ": "·ᒧ",
  "ᒴ": "·ᒨ",
  "ᒸ": "·ᒫ",
  "ᓉ": "·ᓀ",
  "ᣆ": "·ᓂ",
  "ᣈ": "·ᓃ",
  "ᣊ": "·ᓄ",
  "ᣌ": "·ᓅ",
  "ᓋ": "·ᓇ",
  "ᓍ": "·ᓈ",
  "ᓜ": "·ᓓ",
  "ᓞ": "·ᓕ",
  "ᓠ": "·ᓖ",
  "ᓢ": "·ᓗ",
  "ᓤ": "·ᓘ",
  "ᓦ": "·ᓚ",
  "ᓨ": "·ᓛ",
  "ᓶ": "·ᓭ",
  "ᓸ": "·ᓯ",
  "ᓺ": "·ᓰ",
  "ᓼ": "·ᓱ",
  "ᓾ": "·ᓲ",
  "ᔀ": "·ᓴ",
  "ᔂ": "·ᓵ",
  "ᔗ": "·ᔐ",
  "ᔙ": "·ᔑ",
  "ᔛ": "·ᔒ",
  "ᔝ": "·ᔓ",
  "ᔟ": "·ᔔ",
  "ᔡ": "·ᔕ",
  "ᔣ": "·ᔖ",
  "ᔱ": "·ᔨ",
  "ᔳ": "·ᔩ",
  "ᔵ": "·ᔪ",
  "ᔷ": "·ᔫ",
  "ᔹ": "·ᔭ",
  "ᔻ": "·ᔮ",
  "ᣎ": "·ᕃ",
  "ᣏ": "·ᕆ",
  "ᣐ": "·ᕇ",
  "ᣑ": "·ᕈ",
  "ᣒ": "·ᕉ",
  "ᣓ": "·ᕋ",
  "ᕎ": "·ᕌ",
  "ᕛ": "·ᕚ",
  "ᕨ": "·ᕧ",
  "ᢳ": "·ᢱ",
  "ᢶ": "·ᢴ",
  "ᢹ": "·ᢸ",
  "ᣂ": "·ᣀ",
  "꠰": "।",
  "॥": "।।",
  "᰼": "᰻᰻",
  "။": "၊၊",
  "᪩": "᪨᪨",
  "᪫": "᪪᪨",
  "᭟": "᭞᭞",
  "𐩗": "𐩖𐩖",
  "𑑌": "𑑋𑑋",
  "𑙂": "𑙁𑙁",
  "𑱂": "𑱁𑱁",
  "᱿": "᱾᱾",
  "՝": "'",
  "＇": "'",
  "‘": "'",
  "’": "'",
  "‛": "'",
  "′": "'",
  "‵": "'",
  "՚": "'",
  "׳": "'",
  "`": "'",
  "`": "'",
  "｀": "'",
  "´": "'",
  "΄": "'",
  "´": "'",
  "᾽": "'",
  "᾿": "'",
  "῾": "'",
  "ʹ": "'",
  "ʹ": "'",
  "ˈ": "'",
  "ˊ": "'",
  "ˋ": "'",
  "˴": "'",
  "ʻ": "'",
  "ʽ": "'",
  "ʼ": "'",
  "ʾ": "'",
  "ꞌ": "'",
  "י": "'",
  "ߴ": "'",
  "ߵ": "'",
  "ᑊ": "'",
  "ᛌ": "'",
  "𖽑": "'",
  "𖽒": "'",
  "᳓": "''",
  "\"": "''",
  "＂": "''",
  "“": "''",
  "”": "''",
  "‟": "''",
  "″": "''",
  "‶": "''",
  "〃": "''",
  "״": "''",
  "˝": "''",
  "ʺ": "''",
  "˶": "''",
  "ˮ": "''",
  "ײ": "''",
  "‴": "'''",
  "‷": "'''",
  "⁗": "''''",
  "Ɓ": "'B",
  "Ɗ": "'D",
  "ŉ": "'n",
  "Ƥ": "'P",
  "Ƭ": "'T",
  "Ƴ": "'Y",
  "［": "(",
  "❨": "(",
  "❲": "(",
  "〔": "(",
  "﴾": "(",
  "⸨": "((",
  "㈠": "(ー)",
  "⑵": "(2)",
  "⒇": "(2O)",
  "⑶": "(3)",
  "⑷": "(4)",
  "⑸": "(5)",
  "⑹": "(6)",
  "⑺": "(7)",
  "⑻": "(8)",
  "⑼": "(9)",
  "⒜": "(a)",
  "🄐": "(A)",
  "⒝": "(b)",
  "🄑": "(B)",
  "⒞": "(c)",
  "🄒": "(C)",
  "⒟": "(d)",
  "🄓": "(D)",
  "⒠": "(e)",
  "🄔": "(E)",
  "⒡": "(f)",
  "🄕": "(F)",
  "⒢": "(g)",
  "🄖": "(G)",
  "⒣": "(h)",
  "🄗": "(H)",
  "⒤": "(i)",
  "⒥": "(j)",
  "🄙": "(J)",
  "⒦": "(k)",
  "🄚": "(K)",
  "⑴": "(l)",
  "🄘": "(l)",
  "⒧": "(l)",
  "🄛": "(L)",
  "⑿": "(l2)",
  "⒀": "(l3)",
  "⒁": "(l4)",
  "⒂": "(l5)",
  "⒃": "(l6)",
  "⒄": "(l7)",
  "⒅": "(l8)",
  "⒆": "(l9)",
  "⑾": "(ll)",
  "⑽": "(lO)",
  "🄜": "(M)",
  "⒩": "(n)",
  "🄝": "(N)",
  "⒪": "(o)",
  "🄞": "(O)",
  "⒫": "(p)",
  "🄟": "(P)",
  "⒬": "(q)",
  "🄠": "(Q)",
  "⒭": "(r)",
  "🄡": "(R)",
  "⒨": "(rn)",
  "⒮": "(s)",
  "🄢": "(S)",
  "🄪": "(S)",
  "⒯": "(t)",
  "🄣": "(T)",
  "⒰": "(u)",
  "🄤": "(U)",
  "⒱": "(v)",
  "🄥": "(V)",
  "⒲": "(w)",
  "🄦": "(W)",
  "⒳": "(x)",
  "🄧": "(X)",
  "⒴": "(y)",
  "🄨": "(Y)",
  "⒵": "(z)",
  "🄩": "(Z)",
  "㈀": "(ᄀ)",
  "㈎": "(가)",
  "㈁": "(ᄂ)",
  "㈏": "(나)",
  "㈂": "(ᄃ)",
  "㈐": "(다)",
  "㈃": "(ᄅ)",
  "㈑": "(라)",
  "㈄": "(ᄆ)",
  "㈒": "(마)",
  "㈅": "(ᄇ)",
  "㈓": "(바)",
  "㈆": "(ᄉ)",
  "㈔": "(사)",
  "㈇": "(ᄋ)",
  "㈕": "(아)",
  "㈝": "(오전)",
  "㈞": "(오후)",
  "㈈": "(ᄌ)",
  "㈖": "(자)",
  "㈜": "(주)",
  "㈉": "(ᄎ)",
  "㈗": "(차)",
  "㈊": "(ᄏ)",
  "㈘": "(카)",
  "㈋": "(ᄐ)",
  "㈙": "(타)",
  "㈌": "(ᄑ)",
  "㈚": "(파)",
  "㈍": "(ᄒ)",
  "㈛": "(하)",
  "㈦": "(七)",
  "㈢": "(三)",
  "🉁": "(三)",
  "㈨": "(九)",
  "㈡": "(二)",
  "🉂": "(二)",
  "㈤": "(五)",
  "㈹": "(代)",
  "㈽": "(企)",
  "㉁": "(休)",
  "㈧": "(八)",
  "㈥": "(六)",
  "㈸": "(労)",
  "🉇": "(勝)",
  "㈩": "(十)",
  "㈿": "(協)",
  "㈴": "(名)",
  "㈺": "(呼)",
  "㈣": "(四)",
  "㈯": "(土)",
  "㈻": "(学)",
  "🉃": "(安)",
  "🉅": "(打)",
  "🉈": "(敗)",
  "㈰": "(日)",
  "㈪": "(月)",
  "㈲": "(有)",
  "㈭": "(木)",
  "🉀": "(本)",
  "㈱": "(株)",
  "㈬": "(水)",
  "㈫": "(火)",
  "🉄": "(点)",
  "㈵": "(特)",
  "🉆": "(盗)",
  "㈼": "(監)",
  "㈳": "(社)",
  "㈷": "(祝)",
  "㉀": "(祭)",
  "㉂": "(自)",
  "㉃": "(至)",
  "㈶": "(財)",
  "㈾": "(資)",
  "㈮": "(金)",
  "］": ")",
  "❩": ")",
  "❳": ")",
  "〕": ")",
  "﴿": ")",
  "⸩": "))",
  "❴": "{",
  "𝄔": "{",
  "❵": "}",
  "〚": "⟦",
  "〛": "⟧",
  "⟨": "❬",
  "〈": "❬",
  "〈": "❬",
  "㇛": "❬",
  "く": "❬",
  "𡿨": "❬",
  "⟩": "❭",
  "〉": "❭",
  "〉": "❭",
  "＾": "︿",
  "⸿": "¶",
  "⁎": "*",
  "٭": "*",
  "∗": "*",
  "𐌟": "*",
  "᜵": "/",
  "⁁": "/",
  "∕": "/",
  "⁄": "/",
  "╱": "/",
  "⟋": "/",
  "⧸": "/",
  "𝈺": "/",
  "㇓": "/",
  "〳": "/",
  "Ⳇ": "/",
  "ノ": "/",
  "丿": "/",
  "⼃": "/",
  "⧶": "/̄",
  "⫽": "//",
  "⫻": "///",
  "＼": "\\",
  "﹨": "\\",
  "∖": "\\",
  "⟍": "\\",
  "⧵": "\\",
  "⧹": "\\",
  "𝈏": "\\",
  "𝈻": "\\",
  "㇔": "\\",
  "丶": "\\",
  "⼂": "\\",
  "⳹": "\\\\",
  "⑊": "\\\\",
  "⟈": "\\ᑕ",
  "ꝸ": "&",
  "૰": "॰",
  "𑂻": "॰",
  "𑇇": "॰",
  "⚬": "॰",
  "𑇛": "꣼",
  "៙": "๏",
  "៕": "๚",
  "៚": "๛",
  "༌": "་",
  "༎": "།།",
  "˄": "^",
  "ˆ": "^",
  "꙾": "ˇ",
  "˘": "ˇ",
  "‾": "ˉ",
  "﹉": "ˉ",
  "﹊": "ˉ",
  "﹋": "ˉ",
  "﹌": "ˉ",
  "¯": "ˉ",
  "￣": "ˉ",
  "▔": "ˉ",
  "ъ": "ˉb",
  "ꙑ": "ˉbi",
  "͵": "ˏ",
  "˻": "˪",
  "꜖": "˪",
  "꜔": "˫",
  "。": "˳",
  "⸰": "°",
  "˚": "°",
  "∘": "°",
  "○": "°",
  "◦": "°",
  "⍜": "°̲",
  "⍤": "°̈",
  "℃": "°C",
  "℉": "°F",
  "௵": "௳",
  "༛": "༚༚",
  "༟": "༚༝",
  "࿎": "༝༚",
  "༞": "༝༝",
  "Ⓒ": "©",
  "Ⓡ": "®",
  "Ⓟ": "℗",
  "𝈛": "⅄",
  "⯬": "↞",
  "⯭": "↟",
  "⯮": "↠",
  "⯯": "↡",
  "↵": "↲",
  "⥥": "⇃⇂",
  "⥯": "⇃ᛚ",
  "𝛛": "∂",
  "𝜕": "∂",
  "𝝏": "∂",
  "𝞉": "∂",
  "𝟃": "∂",
  "𞣌": "∂",
  "𞣍": "∂̵",
  "ð": "∂̵",
  "⌀": "∅",
  "𝛁": "∇",
  "𝛻": "∇",
  "𝜵": "∇",
  "𝝯": "∇",
  "𝞩": "∇",
  "𑢨": "∇",
  "⍢": "∇̈",
  "⍫": "∇̴",
  "█": "∎",
  "■": "∎",
  "⨿": "∐",
  "᛭": "+",
  "➕": "+",
  "𐊛": "+",
  "⨣": "+̂",
  "⨢": "+̊",
  "⨤": "+̃",
  "∔": "+̇",
  "⨥": "+̣",
  "⨦": "+̰",
  "⨧": "+₂",
  "➗": "÷",
  "‹": "<",
  "❮": "<",
  "˂": "<",
  "𝈶": "<",
  "ᐸ": "<",
  "ᚲ": "<",
  "⋖": "<·",
  "Ⲵ": "<·",
  "ᑅ": "<·",
  "≪": "<<",
  "⋘": "<<<",
  "᐀": "=",
  "⹀": "=",
  "゠": "=",
  "꓿": "=",
  "≚": "=̆",
  "≙": "=̂",
  "≗": "=̊",
  "≐": "=̇",
  "≑": "=̣̇",
  "⩮": "=⃰",
  "⩵": "==",
  "⩶": "===",
  "≞": "=ͫ",
  "›": ">",
  "❯": ">",
  "˃": ">",
  "𝈷": ">",
  "ᐳ": ">",
  "𖼿": ">",
  "ᑁ": ">·",
  "⪥": "><",
  "≫": ">>",
  "⨠": ">>",
  "⋙": ">>>",
  "⁓": "~",
  "˜": "~",
  "῀": "~",
  "∼": "~",
  "⍨": "~̈",
  "⸞": "~̇",
  "⩪": "~̇",
  "⸟": "~̣",
  "𞣈": "∠",
  "⋀": "∧",
  "∯": "∮∮",
  "∰": "∮∮∮",
  "⸫": "∴",
  "⸪": "∵",
  "⸬": "∷",
  "𑇞": "≈",
  "♎": "≏",
  "🝞": "≏",
  "≣": "≡",
  "⨃": "⊍",
  "⨄": "⊎",
  "𝈸": "⊏",
  "𝈹": "⊐",
  "⨅": "⊓",
  "⨆": "⊔",
  "⨂": "⊗",
  "⍟": "⊛",
  "🝱": "⊠",
  "🝕": "⊡",
  "◁": "⊲",
  "▷": "⊳",
  "⍣": "⋆̈",
  "︴": "⌇",
  "◠": "⌒",
  "⨽": "⌙",
  "⌥": "⌤",
  "⧇": "⌻",
  "◎": "⌾",
  "⦾": "⌾",
  "⧅": "⍂",
  "⦰": "⍉",
  "⏃": "⍋",
  "⏂": "⍎",
  "⏁": "⍕",
  "⏆": "⍭",
  "☸": "⎈",
  "︵": "⏜",
  "︶": "⏝",
  "︷": "⏞",
  "︸": "⏟",
  "︹": "⏠",
  "︺": "⏡",
  "▱": "⏥",
  "⏼": "⏻",
  "︱": "│",
  "｜": "│",
  "┃": "│",
  "┏": "┌",
  "┣": "├",
  "▐": "▌",
  "▗": "▖",
  "▝": "▘",
  "☐": "□",
  "￭": "▪",
  "▸": "▶",
  "►": "▶",
  "⳩": "☧",
  "🜊": "☩",
  "🌒": "☽",
  "🌙": "☽",
  "⏾": "☾",
  "🌘": "☾",
  "⧙": "⦚",
  "🜺": "⧟",
  "⨾": "⨟",
  "𐆠": "⳨",
  "♩": "𝅘𝅥",
  "♪": "𝅘𝅥𝅮",
  "⓪": "🄍",
  "↺": "🄎",
  "˙": "ॱ",
  "ൎ": "ॱ",
  "－": "ー",
  "—": "ー",
  "―": "ー",
  "─": "ー",
  "━": "ー",
  "㇐": "ー",
  "ꟷ": "ー",
  "ᅳ": "ー",
  "ㅡ": "ー",
  "一": "ー",
  "⼀": "ー",
  "ᆖ": "ーー",
  "ힹ": "ーᅡ",
  "ힺ": "ーᅥ",
  "ힻ": "ーᅥ丨",
  "ힼ": "ーᅩ",
  "ᆕ": "ーᅮ",
  "ᅴ": "ー丨",
  "ㅢ": "ー丨",
  "ᆗ": "ー丨ᅮ",
  "🄏": "$⃠",
  "₤": "£",
  "〒": "₸",
  "〶": "₸",
  "᭜": "᭐",
  "꧆": "꧐",
  "𑓑": "১",
  "೧": "౧",
  "ၥ": "၁",
  "①": "➀",
  "⑩": "➉",
  "⏨": "₁₀",
  "𝟐": "2",
  "𝟚": "2",
  "𝟤": "2",
  "𝟮": "2",
  "𝟸": "2",
  "🯲": "2",
  "Ꝛ": "2",
  "Ƨ": "2",
  "Ϩ": "2",
  "Ꙅ": "2",
  "ᒿ": "2",
  "ꛯ": "2",
  "ꧏ": "٢",
  "۲": "٢",
  "૨": "२",
  "𑓒": "২",
  "೨": "౨",
  "②": "➁",
  "ƻ": "2̵",
  "🄃": "2,",
  "⒉": "2.",
  "㏵": "22日",
  "㍮": "22点",
  "㏶": "23日",
  "㍯": "23点",
  "㏷": "24日",
  "㍰": "24点",
  "㏸": "25日",
  "㏹": "26日",
  "㏺": "27日",
  "㏻": "28日",
  "㏼": "29日",
  "㏴": "2l日",
  "㍭": "2l点",
  "⒛": "2O.",
  "㏳": "2O日",
  "㍬": "2O点",
  "෩": "෨ා",
  "෯": "෨ී",
  "㏡": "2日",
  "㋁": "2月",
  "㍚": "2点",
  "𝈆": "3",
  "𝟑": "3",
  "𝟛": "3",
  "𝟥": "3",
  "𝟯": "3",
  "𝟹": "3",
  "🯳": "3",
  "Ɜ": "3",
  "Ȝ": "3",
  "Ʒ": "3",
  "Ꝫ": "3",
  "Ⳍ": "3",
  "З": "3",
  "Ӡ": "3",
  "𖼻": "3",
  "𑣊": "3",
  "۳": "٣",
  "𞣉": "٣",
  "૩": "३",
  "③": "➂",
  "Ҙ": "3̦",
  "🄄": "3,",
  "⒊": "3.",
  "㏾": "3l日",
  "㏽": "3O日",
  "㏢": "3日",
  "㋂": "3月",
  "㍛": "3点",
  "𝟒": "4",
  "𝟜": "4",
  "𝟦": "4",
  "𝟰": "4",
  "𝟺": "4",
  "🯴": "4",
  "Ꮞ": "4",
  "𑢯": "4",
  "۴": "٤",
  "૪": "४",
  "④": "➃",
  "🄅": "4,",
  "⒋": "4.",
  "ᔰ": "4·",
  "㏣": "4日",
  "㋃": "4月",
  "㍜": "4点",
  "𝟓": "5",
  "𝟝": "5",
  "𝟧": "5",
  "𝟱": "5",
  "𝟻": "5",
  "🯵": "5",
  "Ƽ": "5",
  "𑢻": "5",
  "⑤": "➄",
  "🄆": "5,",
  "⒌": "5.",
  "㏤": "5日",
  "㋄": "5月",
  "㍝": "5点",
  "𝟔": "6",
  "𝟞": "6",
  "𝟨": "6",
  "𝟲": "6",
  "𝟼": "6",
  "🯶": "6",
  "Ⳓ": "6",
  "б": "6",
  "Ꮾ": "6",
  "𑣕": "6",
  "۶": "٦",
  "𑓖": "৬",
  "⑥": "➅",
  "🄇": "6,",
  "⒍": "6.",
  "㏥": "6日",
  "㋅": "6月",
  "㍞": "6点",
  "𝈒": "7",
  "𝟕": "7",
  "𝟟": "7",
  "𝟩": "7",
  "𝟳": "7",
  "𝟽": "7",
  "🯷": "7",
  "𐓒": "7",
  "𑣆": "7",
  "⑦": "➆",
  "🄈": "7,",
  "⒎": "7.",
  "㏦": "7日",
  "㋆": "7月",
  "㍟": "7点",
  "ଃ": "8",
  "৪": "8",
  "੪": "8",
  "𞣋": "8",
  "𝟖": "8",
  "𝟠": "8",
  "𝟪": "8",
  "𝟴": "8",
  "𝟾": "8",
  "🯸": "8",
  "ȣ": "8",
  "Ȣ": "8",
  "𐌚": "8",
  "૮": "८",
  "⑧": "➇",
  "🄉": "8,",
  "⒏": "8.",
  "㏧": "8日",
  "㋇": "8月",
  "㍠": "8点",
  "੧": "9",
  "୨": "9",
  "৭": "9",
  "൭": "9",
  "𝟗": "9",
  "𝟡": "9",
  "𝟫": "9",
  "𝟵": "9",
  "𝟿": "9",
  "🯹": "9",
  "Ꝯ": "9",
  "Ⳋ": "9",
  "𑣌": "9",
  "𑢬": "9",
  "𑣖": "9",
  "१": "٩",
  "𑣤": "٩",
  "۹": "٩",
  "೯": "౯",
  "⑨": "➈",
  "🄊": "9,",
  "⒐": "9.",
  "㏨": "9日",
  "㋈": "9月",
  "㍡": "9点",
  "⍺": "a",
  "ａ": "a",
  "𝐚": "a",
  "𝑎": "a",
  "𝒂": "a",
  "𝒶": "a",
  "𝓪": "a",
  "𝔞": "a",
  "𝕒": "a",
  "𝖆": "a",
  "𝖺": "a",
  "𝗮": "a",
  "𝘢": "a",
  "𝙖": "a",
  "𝚊": "a",
  "ɑ": "a",
  "α": "a",
  "𝛂": "a",
  "𝛼": "a",
  "𝜶": "a",
  "𝝰": "a",
  "𝞪": "a",
  "а": "a",
  "ⷶ": "ͣ",
  "Ａ": "A",
  "𝐀": "A",
  "𝐴": "A",
  "𝑨": "A",
  "𝒜": "A",
  "𝓐": "A",
  "𝔄": "A",
  "𝔸": "A",
  "𝕬": "A",
  "𝖠": "A",
  "𝗔": "A",
  "𝘈": "A",
  "𝘼": "A",
  "𝙰": "A",
  "Α": "A",
  "𝚨": "A",
  "𝛢": "A",
  "𝜜": "A",
  "𝝖": "A",
  "𝞐": "A",
  "А": "A",
  "Ꭺ": "A",
  "ᗅ": "A",
  "ꓮ": "A",
  "𖽀": "A",
  "𐊠": "A",
  "⍶": "a̲",
  "ǎ": "ă",
  "Ǎ": "Ă",
  "ȧ": "å",
  "Ȧ": "Å",
  "ẚ": "ả",
  "℀": "a/c",
  "℁": "a/s",
  "ꜳ": "aa",
  "Ꜳ": "AA",
  "æ": "ae",
  "ӕ": "ae",
  "Æ": "AE",
  "Ӕ": "AE",
  "ꜵ": "ao",
  "Ꜵ": "AO",
  "🜇": "AR",
  "ꜷ": "au",
  "Ꜷ": "AU",
  "ꜹ": "av",
  "ꜻ": "av",
  "Ꜹ": "AV",
  "Ꜻ": "AV",
  "ꜽ": "ay",
  "Ꜽ": "AY",
  "ꭺ": "ᴀ",
  "∀": "Ɐ",
  "𝈗": "Ɐ",
  "ᗄ": "Ɐ",
  "ꓯ": "Ɐ",
  "𐐟": "Ɒ",
  "𝐛": "b",
  "𝑏": "b",
  "𝒃": "b",
  "𝒷": "b",
  "𝓫": "b",
  "𝔟": "b",
  "𝕓": "b",
  "𝖇": "b",
  "𝖻": "b",
  "𝗯": "b",
  "𝘣": "b",
  "𝙗": "b",
  "𝚋": "b",
  "Ƅ": "b",
  "Ь": "b",
  "Ꮟ": "b",
  "ᑲ": "b",
  "ᖯ": "b",
  "Ｂ": "B",
  "ℬ": "B",
  "𝐁": "B",
  "𝐵": "B",
  "𝑩": "B",
  "𝓑": "B",
  "𝔅": "B",
  "𝔹": "B",
  "𝕭": "B",
  "𝖡": "B",
  "𝗕": "B",
  "𝘉": "B",
  "𝘽": "B",
  "𝙱": "B",
  "Ꞵ": "B",
  "Β": "B",
  "𝚩": "B",
  "𝛣": "B",
  "𝜝": "B",
  "𝝗": "B",
  "𝞑": "B",
  "В": "B",
  "Ᏼ": "B",
  "ᗷ": "B",
  "ꓐ": "B",
  "𐊂": "B",
  "𐊡": "B",
  "𐌁": "B",
  "ɓ": "b̔",
  "ᑳ": "ḃ",
  "ƃ": "b̄",
  "Ƃ": "b̄",
  "Б": "b̄",
  "ƀ": "b̵",
  "ҍ": "b̵",
  "Ҍ": "b̵",
  "ѣ": "b̵",
  "Ѣ": "b̵",
  "ᑿ": "b·",
  "ᒁ": "ḃ·",
  "ᒈ": "b'",
  "Ы": "bl",
  "в": "ʙ",
  "ᏼ": "ʙ",
  "ｃ": "c",
  "ⅽ": "c",
  "𝐜": "c",
  "𝑐": "c",
  "𝒄": "c",
  "𝒸": "c",
  "𝓬": "c",
  "𝔠": "c",
  "𝕔": "c",
  "𝖈": "c",
  "𝖼": "c",
  "𝗰": "c",
  "𝘤": "c",
  "𝙘": "c",
  "𝚌": "c",
  "ᴄ": "c",
  "ϲ": "c",
  "ⲥ": "c",
  "с": "c",
  "ꮯ": "c",
  "𐐽": "c",
  "ⷭ": "ͨ",
  "🝌": "C",
  "𑣲": "C",
  "𑣩": "C",
  "Ｃ": "C",
  "Ⅽ": "C",
  "ℂ": "C",
  "ℭ": "C",
  "𝐂": "C",
  "𝐶": "C",
  "𝑪": "C",
  "𝒞": "C",
  "𝓒": "C",
  "𝕮": "C",
  "𝖢": "C",
  "𝗖": "C",
  "𝘊": "C",
  "𝘾": "C",
  "𝙲": "C",
  "Ϲ": "C",
  "Ⲥ": "C",
  "С": "C",
  "Ꮯ": "C",
  "ꓚ": "C",
  "𐊢": "C",
  "𐌂": "C",
  "𐐕": "C",
  "𐔜": "C",
  "¢": "c̸",
  "ȼ": "c̸",
  "₡": "C⃫",
  "🅮": "C⃠",
  "ç": "c̦",
  "ҫ": "c̦",
  "Ç": "C̦",
  "Ҫ": "C̦",
  "Ƈ": "C'",
  "℅": "c/o",
  "℆": "c/u",
  "🅭": "㏄\t⃝",
  "⋴": "ꞓ",
  "ɛ": "ꞓ",
  "ε": "ꞓ",
  "ϵ": "ꞓ",
  "𝛆": "ꞓ",
  "𝛜": "ꞓ",
  "𝜀": "ꞓ",
  "𝜖": "ꞓ",
  "𝜺": "ꞓ",
  "𝝐": "ꞓ",
  "𝝴": "ꞓ",
  "𝞊": "ꞓ",
  "𝞮": "ꞓ",
  "𝟄": "ꞓ",
  "ⲉ": "ꞓ",
  "є": "ꞓ",
  "ԑ": "ꞓ",
  "ꮛ": "ꞓ",
  "𑣎": "ꞓ",
  "𐐩": "ꞓ",
  "€": "Ꞓ",
  "Ⲉ": "Ꞓ",
  "Є": "Ꞓ",
  "⍷": "ꞓ̲",
  "ͽ": "ꜿ",
  "Ͽ": "Ꜿ",
  "ⅾ": "d",
  "ⅆ": "d",
  "𝐝": "d",
  "𝑑": "d",
  "𝒅": "d",
  "𝒹": "d",
  "𝓭": "d",
  "𝔡": "d",
  "𝕕": "d",
  "𝖉": "d",
  "𝖽": "d",
  "𝗱": "d",
  "𝘥": "d",
  "𝙙": "d",
  "𝚍": "d",
  "ԁ": "d",
  "Ꮷ": "d",
  "ᑯ": "d",
  "ꓒ": "d",
  "Ⅾ": "D",
  "ⅅ": "D",
  "𝐃": "D",
  "𝐷": "D",
  "𝑫": "D",
  "𝒟": "D",
  "𝓓": "D",
  "𝔇": "D",
  "𝔻": "D",
  "𝕯": "D",
  "𝖣": "D",
  "𝗗": "D",
  "𝘋": "D",
  "𝘿": "D",
  "𝙳": "D",
  "Ꭰ": "D",
  "ᗞ": "D",
  "ᗪ": "D",
  "ꓓ": "D",
  "ɗ": "d̔",
  "ɖ": "d̨",
  "ƌ": "d̄",
  "đ": "d̵",
  "Đ": "D̵",
  "Ð": "D̵",
  "Ɖ": "D̵",
  "₫": "ḏ̵",
  "ꝺ": "Ꝺ",
  "ᑻ": "d·",
  "ᒇ": "d'",
  "ʤ": "dȝ",
  "ǳ": "dz",
  "ʣ": "dz",
  "ǲ": "Dz",
  "Ǳ": "DZ",
  "ǆ": "dž",
  "ǅ": "Dž",
  "Ǆ": "DŽ",
  "ʥ": "dʑ",
  "ꭰ": "ᴅ",
  "⸹": "ẟ",
  "δ": "ẟ",
  "𝛅": "ẟ",
  "𝛿": "ẟ",
  "𝜹": "ẟ",
  "𝝳": "ẟ",
  "𝞭": "ẟ",
  "ծ": "ẟ",
  "ᕷ": "ẟ",
  "℮": "e",
  "ｅ": "e",
  "ℯ": "e",
  "ⅇ": "e",
  "𝐞": "e",
  "𝑒": "e",
  "𝒆": "e",
  "𝓮": "e",
  "𝔢": "e",
  "𝕖": "e",
  "𝖊": "e",
  "𝖾": "e",
  "𝗲": "e",
  "𝘦": "e",
  "𝙚": "e",
  "𝚎": "e",
  "ꬲ": "e",
  "е": "e",
  "ҽ": "e",
  "ⷷ": "ͤ",
  "⋿": "E",
  "Ｅ": "E",
  "ℰ": "E",
  "𝐄": "E",
  "𝐸": "E",
  "𝑬": "E",
  "𝓔": "E",
  "𝔈": "E",
  "𝔼": "E",
  "𝕰": "E",
  "𝖤": "E",
  "𝗘": "E",
  "𝘌": "E",
  "𝙀": "E",
  "𝙴": "E",
  "Ε": "E",
  "𝚬": "E",
  "𝛦": "E",
  "𝜠": "E",
  "𝝚": "E",
  "𝞔": "E",
  "Е": "E",
  "ⴹ": "E",
  "Ꭼ": "E",
  "ꓰ": "E",
  "𑢦": "E",
  "𑢮": "E",
  "𐊆": "E",
  "ě": "ĕ",
  "Ě": "Ĕ",
  "ɇ": "e̸",
  "Ɇ": "E̸",
  "ҿ": "ę",
  "ꭼ": "ᴇ",
  "ə": "ǝ",
  "ә": "ǝ",
  "∃": "Ǝ",
  "ⴺ": "Ǝ",
  "ꓱ": "Ǝ",
  "ɚ": "ǝ˞",
  "ᴔ": "ǝo",
  "ꭁ": "ǝo̸",
  "ꭂ": "ǝo̵",
  "Ә": "Ə",
  "𝈡": "Ɛ",
  "ℇ": "Ɛ",
  "Ԑ": "Ɛ",
  "Ꮛ": "Ɛ",
  "𖼭": "Ɛ",
  "𐐁": "Ɛ",
  "ᶟ": "ᵋ",
  "ᴈ": "ɜ",
  "з": "ɜ",
  "ҙ": "ɜ̦",
  "𐑂": "ɞ",
  "ꞝ": "ʚ",
  "𐐪": "ʚ",
  "𝐟": "f",
  "𝑓": "f",
  "𝒇": "f",
  "𝒻": "f",
  "𝓯": "f",
  "𝔣": "f",
  "𝕗": "f",
  "𝖋": "f",
  "𝖿": "f",
  "𝗳": "f",
  "𝘧": "f",
  "𝙛": "f",
  "𝚏": "f",
  "ꬵ": "f",
  "ꞙ": "f",
  "ſ": "f",
  "ẝ": "f",
  "ք": "f",
  "𝈓": "F",
  "ℱ": "F",
  "𝐅": "F",
  "𝐹": "F",
  "𝑭": "F",
  "𝓕": "F",
  "𝔉": "F",
  "𝔽": "F",
  "𝕱": "F",
  "𝖥": "F",
  "𝗙": "F",
  "𝘍": "F",
  "𝙁": "F",
  "𝙵": "F",
  "Ꞙ": "F",
  "Ϝ": "F",
  "𝟊": "F",
  "ᖴ": "F",
  "ꓝ": "F",
  "𑣂": "F",
  "𑢢": "F",
  "𐊇": "F",
  "𐊥": "F",
  "𐔥": "F",
  "ƒ": "f̦",
  "Ƒ": "F̦",
  "ᵮ": "f̴",
  "℻": "FAX",
  "ﬀ": "ff",
  "ﬃ": "ffi",
  "ﬄ": "ffl",
  "ﬁ": "fi",
  "ﬂ": "fl",
  "ʩ": "fŋ",
  "ᖵ": "Ⅎ",
  "ꓞ": "Ⅎ",
  "𝈰": "ꟻ",
  "ᖷ": "ꟻ",
  "ｇ": "g",
  "ℊ": "g",
  "𝐠": "g",
  "𝑔": "g",
  "𝒈": "g",
  "𝓰": "g",
  "𝔤": "g",
  "𝕘": "g",
  "𝖌": "g",
  "𝗀": "g",
  "𝗴": "g",
  "𝘨": "g",
  "𝙜": "g",
  "𝚐": "g",
  "ɡ": "g",
  "ᶃ": "g",
  "ƍ": "g",
  "ց": "g",
  "𝐆": "G",
  "𝐺": "G",
  "𝑮": "G",
  "𝒢": "G",
  "𝓖": "G",
  "𝔊": "G",
  "𝔾": "G",
  "𝕲": "G",
  "𝖦": "G",
  "𝗚": "G",
  "𝘎": "G",
  "𝙂": "G",
  "𝙶": "G",
  "Ԍ": "G",
  "Ꮐ": "G",
  "Ᏻ": "G",
  "ꓖ": "G",
  "ᶢ": "ᵍ",
  "ɠ": "g̔",
  "ǧ": "ğ",
  "Ǧ": "Ğ",
  "ǵ": "ģ",
  "ǥ": "g̵",
  "Ǥ": "G̵",
  "Ɠ": "G'",
  "ԍ": "ɢ",
  "ꮐ": "ɢ",
  "ᏻ": "ɢ",
  "ｈ": "h",
  "ℎ": "h",
  "𝐡": "h",
  "𝒉": "h",
  "𝒽": "h",
  "𝓱": "h",
  "𝔥": "h",
  "𝕙": "h",
  "𝖍": "h",
  "𝗁": "h",
  "𝗵": "h",
  "𝘩": "h",
  "𝙝": "h",
  "𝚑": "h",
  "һ": "h",
  "հ": "h",
  "Ꮒ": "h",
  "Ｈ": "H",
  "ℋ": "H",
  "ℌ": "H",
  "ℍ": "H",
  "𝐇": "H",
  "𝐻": "H",
  "𝑯": "H",
  "𝓗": "H",
  "𝕳": "H",
  "𝖧": "H",
  "𝗛": "H",
  "𝘏": "H",
  "𝙃": "H",
  "𝙷": "H",
  "Η": "H",
  "𝚮": "H",
  "𝛨": "H",
  "𝜢": "H",
  "𝝜": "H",
  "𝞖": "H",
  "Ⲏ": "H",
  "Н": "H",
  "Ꮋ": "H",
  "ᕼ": "H",
  "ꓧ": "H",
  "𐋏": "H",
  "ᵸ": "ᴴ",
  "ɦ": "h̔",
  "ꚕ": "h̔",
  "Ᏺ": "h̔",
  "Ⱨ": "H̩",
  "Ң": "H̩",
  "ħ": "h̵",
  "ℏ": "h̵",
  "ћ": "h̵",
  "Ħ": "H̵",
  "Ӊ": "H̦",
  "Ӈ": "H̦",
  "н": "ʜ",
  "ꮋ": "ʜ",
  "ң": "ʜ̩",
  "ӊ": "ʜ̦",
  "ӈ": "ʜ̦",
  "Ԋ": "Ƕ",
  "ꮀ": "ⱶ",
  "Ͱ": "Ⱶ",
  "Ꭸ": "Ⱶ",
  "Ꮀ": "Ⱶ",
  "ꚱ": "Ⱶ",
  "ꞕ": "ꜧ",
  "˛": "i",
  "⍳": "i",
  "ｉ": "i",
  "ⅰ": "i",
  "ℹ": "i",
  "ⅈ": "i",
  "𝐢": "i",
  "𝑖": "i",
  "𝒊": "i",
  "𝒾": "i",
  "𝓲": "i",
  "𝔦": "i",
  "𝕚": "i",
  "𝖎": "i",
  "𝗂": "i",
  "𝗶": "i",
  "𝘪": "i",
  "𝙞": "i",
  "𝚒": "i",
  "ı": "i",
  "𝚤": "i",
  "ɪ": "i",
  "ɩ": "i",
  "ι": "i",
  "ι": "i",
  "ͺ": "i",
  "𝛊": "i",
  "𝜄": "i",
  "𝜾": "i",
  "𝝸": "i",
  "𝞲": "i",
  "і": "i",
  "ꙇ": "i",
  "ӏ": "i",
  "ꭵ": "i",
  "Ꭵ": "i",
  "𑣃": "i",
  "ⓛ": "Ⓘ",
  "⍸": "i̲",
  "ǐ": "ĭ",
  "Ǐ": "Ĭ",
  "ɨ": "i̵",
  "ᵻ": "i̵",
  "ᵼ": "i̵",
  "ⅱ": "ii",
  "ⅲ": "iii",
  "ĳ": "ij",
  "ⅳ": "iv",
  "ⅸ": "ix",
  "ｊ": "j",
  "ⅉ": "j",
  "𝐣": "j",
  "𝑗": "j",
  "𝒋": "j",
  "𝒿": "j",
  "𝓳": "j",
  "𝔧": "j",
  "𝕛": "j",
  "𝖏": "j",
  "𝗃": "j",
  "𝗷": "j",
  "𝘫": "j",
  "𝙟": "j",
  "𝚓": "j",
  "ϳ": "j",
  "ј": "j",
  "Ｊ": "J",
  "𝐉": "J",
  "𝐽": "J",
  "𝑱": "J",
  "𝒥": "J",
  "𝓙": "J",
  "𝔍": "J",
  "𝕁": "J",
  "𝕵": "J",
  "𝖩": "J",
  "𝗝": "J",
  "𝘑": "J",
  "𝙅": "J",
  "𝙹": "J",
  "Ʝ": "J",
  "Ϳ": "J",
  "Ј": "J",
  "Ꭻ": "J",
  "ᒍ": "J",
  "ꓙ": "J",
  "ɉ": "j̵",
  "Ɉ": "J̵",
  "ᒙ": "J·",
  "𝚥": "ȷ",
  "յ": "ȷ",
  "ꭻ": "ᴊ",
  "𝐤": "k",
  "𝑘": "k",
  "𝒌": "k",
  "𝓀": "k",
  "𝓴": "k",
  "𝔨": "k",
  "𝕜": "k",
  "𝖐": "k",
  "𝗄": "k",
  "𝗸": "k",
  "𝘬": "k",
  "𝙠": "k",
  "𝚔": "k",
  "K": "K",
  "Ｋ": "K",
  "𝐊": "K",
  "𝐾": "K",
  "𝑲": "K",
  "𝒦": "K",
  "𝓚": "K",
  "𝔎": "K",
  "𝕂": "K",
  "𝕶": "K",
  "𝖪": "K",
  "𝗞": "K",
  "𝘒": "K",
  "𝙆": "K",
  "𝙺": "K",
  "Κ": "K",
  "𝚱": "K",
  "𝛫": "K",
  "𝜥": "K",
  "𝝟": "K",
  "𝞙": "K",
  "Ⲕ": "K",
  "К": "K",
  "Ꮶ": "K",
  "ᛕ": "K",
  "ꓗ": "K",
  "𐔘": "K",
  "ƙ": "k̔",
  "Ⱪ": "K̩",
  "Қ": "K̩",
  "₭": "K̵",
  "Ꝁ": "K̵",
  "Ҟ": "K̵",
  "Ƙ": "K'",
  "׀": "l",
  "|": "l",
  "∣": "l",
  "⏽": "l",
  "￨": "l",
  "١": "l",
  "۱": "l",
  "𐌠": "l",
  "𞣇": "l",
  "𝟏": "l",
  "𝟙": "l",
  "𝟣": "l",
  "𝟭": "l",
  "𝟷": "l",
  "🯱": "l",
  "I": "l",
  "Ｉ": "l",
  "Ⅰ": "l",
  "ℐ": "l",
  "ℑ": "l",
  "𝐈": "l",
  "𝐼": "l",
  "𝑰": "l",
  "𝓘": "l",
  "𝕀": "l",
  "𝕴": "l",
  "𝖨": "l",
  "𝗜": "l",
  "𝘐": "l",
  "𝙄": "l",
  "𝙸": "l",
  "Ɩ": "l",
  "ｌ": "l",
  "ⅼ": "l",
  "ℓ": "l",
  "𝐥": "l",
  "𝑙": "l",
  "𝒍": "l",
  "𝓁": "l",
  "𝓵": "l",
  "𝔩": "l",
  "𝕝": "l",
  "𝖑": "l",
  "𝗅": "l",
  "𝗹": "l",
  "𝘭": "l",
  "𝙡": "l",
  "𝚕": "l",
  "ǀ": "l",
  "Ι": "l",
  "𝚰": "l",
  "𝛪": "l",
  "𝜤": "l",
  "𝝞": "l",
  "𝞘": "l",
  "Ⲓ": "l",
  "І": "l",
  "Ӏ": "l",
  "ו": "l",
  "ן": "l",
  "ا": "l",
  "𞸀": "l",
  "𞺀": "l",
  "ﺎ": "l",
  "ﺍ": "l",
  "ߊ": "l",
  "ⵏ": "l",
  "ᛁ": "l",
  "ꓲ": "l",
  "𖼨": "l",
  "𐊊": "l",
  "𐌉": "l",
  "𝈪": "L",
  "Ⅼ": "L",
  "ℒ": "L",
  "𝐋": "L",
  "𝐿": "L",
  "𝑳": "L",
  "𝓛": "L",
  "𝔏": "L",
  "𝕃": "L",
  "𝕷": "L",
  "𝖫": "L",
  "𝗟": "L",
  "𝘓": "L",
  "𝙇": "L",
  "𝙻": "L",
  "Ⳑ": "L",
  "Ꮮ": "L",
  "ᒪ": "L",
  "ꓡ": "L",
  "𖼖": "L",
  "𑢣": "L",
  "𑢲": "L",
  "𐐛": "L",
  "𐔦": "L",
  "ﴼ": "l̋",
  "ﴽ": "l̋",
  "ł": "l̸",
  "Ł": "L̸",
  "ɭ": "l̨",
  "Ɨ": "l̵",
  "ƚ": "l̵",
  "ɫ": "l̴",
  "إ": "lٕ",
  "ﺈ": "lٕ",
  "ﺇ": "lٕ",
  "ٳ": "lٕ",
  "ŀ": "l·",
  "Ŀ": "l·",
  "ᒷ": "l·",
  "🄂": "l,",
  "⒈": "l.",
  "ױ": "l'",
  "⒓": "l2.",
  "㏫": "l2日",
  "㋋": "l2月",
  "㍤": "l2点",
  "⒔": "l3.",
  "㏬": "l3日",
  "㍥": "l3点",
  "⒕": "l4.",
  "㏭": "l4日",
  "㍦": "l4点",
  "⒖": "l5.",
  "㏮": "l5日",
  "㍧": "l5点",
  "⒗": "l6.",
  "㏯": "l6日",
  "㍨": "l6点",
  "⒘": "l7.",
  "㏰": "l7日",
  "㍩": "l7点",
  "⒙": "l8.",
  "㏱": "l8日",
  "㍪": "l8点",
  "⒚": "l9.",
  "㏲": "l9日",
  "㍫": "l9点",
  "ǉ": "lj",
  "Ĳ": "lJ",
  "ǈ": "Lj",
  "Ǉ": "LJ",
  "‖": "ll",
  "∥": "ll",
  "Ⅱ": "ll",
  "ǁ": "ll",
  "װ": "ll",
  "𐆙": "l̵l̵",
  "⒒": "ll.",
  "Ⅲ": "lll",
  "𐆘": "l̵l̵S̵",
  "㏪": "ll日",
  "㋊": "ll月",
  "㍣": "ll点",
  "Ю": "lO",
  "⒑": "lO.",
  "㏩": "lO日",
  "㋉": "lO月",
  "㍢": "lO点",
  "ʪ": "ls",
  "₶": "lt",
  "Ⅳ": "lV",
  "Ⅸ": "lX",
  "ɮ": "lȝ",
  "ʫ": "lz",
  "أ": "lٴ",
  "ﺄ": "lٴ",
  "ﺃ": "lٴ",
  "ٲ": "lٴ",
  "ٵ": "lٴ",
  "ﷳ": "lكبر",
  "ﷲ": "lللّٰo",
  "㏠": "l日",
  "㋀": "l月",
  "㍙": "l点",
  "ⳑ": "ʟ",
  "ꮮ": "ʟ",
  "𐑃": "ʟ",
  "Ｍ": "M",
  "Ⅿ": "M",
  "ℳ": "M",
  "𝐌": "M",
  "𝑀": "M",
  "𝑴": "M",
  "𝓜": "M",
  "𝔐": "M",
  "𝕄": "M",
  "𝕸": "M",
  "𝖬": "M",
  "𝗠": "M",
  "𝘔": "M",
  "𝙈": "M",
  "𝙼": "M",
  "Μ": "M",
  "𝚳": "M",
  "𝛭": "M",
  "𝜧": "M",
  "𝝡": "M",
  "𝞛": "M",
  "Ϻ": "M",
  "Ⲙ": "M",
  "М": "M",
  "Ꮇ": "M",
  "ᗰ": "M",
  "ᛖ": "M",
  "ꓟ": "M",
  "𐊰": "M",
  "𐌑": "M",
  "Ӎ": "M̦",
  "🝫": "MB",
  "ⷨ": "ᷟ",
  "𝐧": "n",
  "𝑛": "n",
  "𝒏": "n",
  "𝓃": "n",
  "𝓷": "n",
  "𝔫": "n",
  "𝕟": "n",
  "𝖓": "n",
  "𝗇": "n",
  "𝗻": "n",
  "𝘯": "n",
  "𝙣": "n",
  "𝚗": "n",
  "ո": "n",
  "ռ": "n",
  "Ｎ": "N",
  "ℕ": "N",
  "𝐍": "N",
  "𝑁": "N",
  "𝑵": "N",
  "𝒩": "N",
  "𝓝": "N",
  "𝔑": "N",
  "𝕹": "N",
  "𝖭": "N",
  "𝗡": "N",
  "𝘕": "N",
  "𝙉": "N",
  "𝙽": "N",
  "Ν": "N",
  "𝚴": "N",
  "𝛮": "N",
  "𝜨": "N",
  "𝝢": "N",
  "𝞜": "N",
  "Ⲛ": "N",
  "ꓠ": "N",
  "𐔓": "N",
  "𐆎": "N̊",
  "ɳ": "n̨",
  "ƞ": "n̩",
  "η": "n̩",
  "𝛈": "n̩",
  "𝜂": "n̩",
  "𝜼": "n̩",
  "𝝶": "n̩",
  "𝞰": "n̩",
  "Ɲ": "N̦",
  "ᵰ": "n̴",
  "ǌ": "nj",
  "ǋ": "Nj",
  "Ǌ": "NJ",
  "№": "No",
  "ͷ": "ᴎ",
  "и": "ᴎ",
  "𐑍": "ᴎ",
  "ņ": "ɲ",
  "ం": "o",
  "ಂ": "o",
  "ം": "o",
  "ං": "o",
  "०": "o",
  "੦": "o",
  "૦": "o",
  "௦": "o",
  "౦": "o",
  "೦": "o",
  "൦": "o",
  "๐": "o",
  "໐": "o",
  "၀": "o",
  "٥": "o",
  "۵": "o",
  "ｏ": "o",
  "ℴ": "o",
  "𝐨": "o",
  "𝑜": "o",
  "𝒐": "o",
  "𝓸": "o",
  "𝔬": "o",
  "𝕠": "o",
  "𝖔": "o",
  "𝗈": "o",
  "𝗼": "o",
  "𝘰": "o",
  "𝙤": "o",
  "𝚘": "o",
  "ᴏ": "o",
  "ᴑ": "o",
  "ꬽ": "o",
  "ο": "o",
  "𝛐": "o",
  "𝜊": "o",
  "𝝄": "o",
  "𝝾": "o",
  "𝞸": "o",
  "σ": "o",
  "𝛔": "o",
  "𝜎": "o",
  "𝝈": "o",
  "𝞂": "o",
  "𝞼": "o",
  "ⲟ": "o",
  "о": "o",
  "ჿ": "o",
  "օ": "o",
  "ס": "o",
  "ه": "o",
  "𞸤": "o",
  "𞹤": "o",
  "𞺄": "o",
  "ﻫ": "o",
  "ﻬ": "o",
  "ﻪ": "o",
  "ﻩ": "o",
  "ھ": "o",
  "ﮬ": "o",
  "ﮭ": "o",
  "ﮫ": "o",
  "ﮪ": "o",
  "ہ": "o",
  "ﮨ": "o",
  "ﮩ": "o",
  "ﮧ": "o",
  "ﮦ": "o",
  "ە": "o",
  "ഠ": "o",
  "ဝ": "o",
  "𐓪": "o",
  "𑣈": "o",
  "𑣗": "o",
  "𐐬": "o",
  "߀": "O",
  "০": "O",
  "୦": "O",
  "〇": "O",
  "𑓐": "O",
  "𑣠": "O",
  "𝟎": "O",
  "𝟘": "O",
  "𝟢": "O",
  "𝟬": "O",
  "𝟶": "O",
  "🯰": "O",
  "Ｏ": "O",
  "𝐎": "O",
  "𝑂": "O",
  "𝑶": "O",
  "𝒪": "O",
  "𝓞": "O",
  "𝔒": "O",
  "𝕆": "O",
  "𝕺": "O",
  "𝖮": "O",
  "𝗢": "O",
  "𝘖": "O",
  "𝙊": "O",
  "𝙾": "O",
  "Ο": "O",
  "𝚶": "O",
  "𝛰": "O",
  "𝜪": "O",
  "𝝤": "O",
  "𝞞": "O",
  "Ⲟ": "O",
  "О": "O",
  "Օ": "O",
  "ⵔ": "O",
  "ዐ": "O",
  "ଠ": "O",
  "𐓂": "O",
  "ꓳ": "O",
  "𑢵": "O",
  "𐊒": "O",
  "𐊫": "O",
  "𐐄": "O",
  "𐔖": "O",
  "⁰": "º",
  "ᵒ": "º",
  "ǒ": "ŏ",
  "Ǒ": "Ŏ",
  "ۿ": "ô",
  "Ő": "Ö",
  "ø": "o̸",
  "ꬾ": "o̸",
  "Ø": "O̸",
  "ⵁ": "O̸",
  "Ǿ": "Ó̸",
  "ɵ": "o̵",
  "ꝋ": "o̵",
  "ө": "o̵",
  "ѳ": "o̵",
  "ꮎ": "o̵",
  "ꮻ": "o̵",
  "⊖": "O̵",
  "⊝": "O̵",
  "⍬": "O̵",
  "𝈚": "O̵",
  "🜔": "O̵",
  "Ɵ": "O̵",
  "Ꝋ": "O̵",
  "θ": "O̵",
  "ϑ": "O̵",
  "𝛉": "O̵",
  "𝛝": "O̵",
  "𝜃": "O̵",
  "𝜗": "O̵",
  "𝜽": "O̵",
  "𝝑": "O̵",
  "𝝷": "O̵",
  "𝞋": "O̵",
  "𝞱": "O̵",
  "𝟅": "O̵",
  "Θ": "O̵",
  "ϴ": "O̵",
  "𝚯": "O̵",
  "𝚹": "O̵",
  "𝛩": "O̵",
  "𝛳": "O̵",
  "𝜣": "O̵",
  "𝜭": "O̵",
  "𝝝": "O̵",
  "𝝧": "O̵",
  "𝞗": "O̵",
  "𝞡": "O̵",
  "Ө": "O̵",
  "Ѳ": "O̵",
  "ⴱ": "O̵",
  "Ꮎ": "O̵",
  "Ꮻ": "O̵",
  "ꭴ": "ơ",
  "ﳙ": "oٰ",
  "🄁": "O,",
  "🄀": "O.",
  "ơ": "o'",
  "Ơ": "O'",
  "Ꭴ": "O'",
  "%": "º/₀",
  "٪": "º/₀",
  "⁒": "º/₀",
  "‰": "º/₀₀",
  "؉": "º/₀₀",
  "‱": "º/₀₀₀",
  "؊": "º/₀₀₀",
  "œ": "oe",
  "Œ": "OE",
  "ɶ": "oᴇ",
  "∞": "oo",
  "ꝏ": "oo",
  "ꚙ": "oo",
  "Ꝏ": "OO",
  "Ꚙ": "OO",
  "ﳗ": "oج",
  "ﱑ": "oج",
  "ﳘ": "oم",
  "ﱒ": "oم",
  "ﶓ": "oمج",
  "ﶔ": "oمم",
  "ﱓ": "oى",
  "ﱔ": "oى",
  "ൟ": "oരo",
  "တ": "oာ",
  "㍘": "O点",
  "ↄ": "ɔ",
  "ᴐ": "ɔ",
  "ͻ": "ɔ",
  "𐑋": "ɔ",
  "Ↄ": "Ɔ",
  "Ͻ": "Ɔ",
  "ꓛ": "Ɔ",
  "𐐣": "Ɔ",
  "ꬿ": "ɔ̸",
  "ꭢ": "ɔe",
  "𐐿": "ɷ",
  "⍴": "p",
  "ｐ": "p",
  "𝐩": "p",
  "𝑝": "p",
  "𝒑": "p",
  "𝓅": "p",
  "𝓹": "p",
  "𝔭": "p",
  "𝕡": "p",
  "𝖕": "p",
  "𝗉": "p",
  "𝗽": "p",
  "𝘱": "p",
  "𝙥": "p",
  "𝚙": "p",
  "ρ": "p",
  "ϱ": "p",
  "𝛒": "p",
  "𝛠": "p",
  "𝜌": "p",
  "𝜚": "p",
  "𝝆": "p",
  "𝝔": "p",
  "𝞀": "p",
  "𝞎": "p",
  "𝞺": "p",
  "𝟈": "p",
  "ⲣ": "p",
  "р": "p",
  "Ｐ": "P",
  "ℙ": "P",
  "𝐏": "P",
  "𝑃": "P",
  "𝑷": "P",
  "𝒫": "P",
  "𝓟": "P",
  "𝔓": "P",
  "𝕻": "P",
  "𝖯": "P",
  "𝗣": "P",
  "𝘗": "P",
  "𝙋": "P",
  "𝙿": "P",
  "Ρ": "P",
  "𝚸": "P",
  "𝛲": "P",
  "𝜬": "P",
  "𝝦": "P",
  "𝞠": "P",
  "Ⲣ": "P",
  "Р": "P",
  "Ꮲ": "P",
  "ᑭ": "P",
  "ꓑ": "P",
  "𐊕": "P",
  "ƥ": "p̔",
  "ᵽ": "p̵",
  "ᑷ": "p·",
  "ᒆ": "P'",
  "ᴩ": "ᴘ",
  "ꮲ": "ᴘ",
  "φ": "ɸ",
  "ϕ": "ɸ",
  "𝛗": "ɸ",
  "𝛟": "ɸ",
  "𝜑": "ɸ",
  "𝜙": "ɸ",
  "𝝋": "ɸ",
  "𝝓": "ɸ",
  "𝞅": "ɸ",
  "𝞍": "ɸ",
  "𝞿": "ɸ",
  "𝟇": "ɸ",
  "ⲫ": "ɸ",
  "ф": "ɸ",
  "𝐪": "q",
  "𝑞": "q",
  "𝒒": "q",
  "𝓆": "q",
  "𝓺": "q",
  "𝔮": "q",
  "𝕢": "q",
  "𝖖": "q",
  "𝗊": "q",
  "𝗾": "q",
  "𝘲": "q",
  "𝙦": "q",
  "𝚚": "q",
  "ԛ": "q",
  "գ": "q",
  "զ": "q",
  "ℚ": "Q",
  "𝐐": "Q",
  "𝑄": "Q",
  "𝑸": "Q",
  "𝒬": "Q",
  "𝓠": "Q",
  "𝔔": "Q",
  "𝕼": "Q",
  "𝖰": "Q",
  "𝗤": "Q",
  "𝘘": "Q",
  "𝙌": "Q",
  "𝚀": "Q",
  "ⵕ": "Q",
  "ʠ": "q̔",
  "🜀": "QE",
  "ᶐ": "ɋ",
  "ᴋ": "ĸ",
  "κ": "ĸ",
  "ϰ": "ĸ",
  "𝛋": "ĸ",
  "𝛞": "ĸ",
  "𝜅": "ĸ",
  "𝜘": "ĸ",
  "𝜿": "ĸ",
  "𝝒": "ĸ",
  "𝝹": "ĸ",
  "𝞌": "ĸ",
  "𝞳": "ĸ",
  "𝟆": "ĸ",
  "ⲕ": "ĸ",
  "к": "ĸ",
  "ꮶ": "ĸ",
  "қ": "ĸ̩",
  "ҟ": "ĸ̵",
  "𝐫": "r",
  "𝑟": "r",
  "𝒓": "r",
  "𝓇": "r",
  "𝓻": "r",
  "𝔯": "r",
  "𝕣": "r",
  "𝖗": "r",
  "𝗋": "r",
  "𝗿": "r",
  "𝘳": "r",
  "𝙧": "r",
  "𝚛": "r",
  "ꭇ": "r",
  "ꭈ": "r",
  "ᴦ": "r",
  "ⲅ": "r",
  "г": "r",
  "ꮁ": "r",
  "𝈖": "R",
  "ℛ": "R",
  "ℜ": "R",
  "ℝ": "R",
  "𝐑": "R",
  "𝑅": "R",
  "𝑹": "R",
  "𝓡": "R",
  "𝕽": "R",
  "𝖱": "R",
  "𝗥": "R",
  "𝘙": "R",
  "𝙍": "R",
  "𝚁": "R",
  "Ʀ": "R",
  "Ꭱ": "R",
  "Ꮢ": "R",
  "𐒴": "R",
  "ᖇ": "R",
  "ꓣ": "R",
  "𖼵": "R",
  "ɽ": "r̨",
  "ɼ": "r̩",
  "ɍ": "r̵",
  "ғ": "r̵",
  "ᵲ": "r̴",
  "ґ": "r'",
  "𑣣": "rn",
  "m": "rn",
  "ⅿ": "rn",
  "𝐦": "rn",
  "𝑚": "rn",
  "𝒎": "rn",
  "𝓂": "rn",
  "𝓶": "rn",
  "𝔪": "rn",
  "𝕞": "rn",
  "𝖒": "rn",
  "𝗆": "rn",
  "𝗺": "rn",
  "𝘮": "rn",
  "𝙢": "rn",
  "𝚖": "rn",
  "𑜀": "rn",
  "₥": "rn̸",
  "ɱ": "rn̦",
  "ᵯ": "rn̴",
  "₨": "Rs",
  "ꭱ": "ʀ",
  "ꮢ": "ʀ",
  "я": "ᴙ",
  "ᵳ": "ɾ̴",
  "℩": "ɿ",
  "ｓ": "s",
  "𝐬": "s",
  "𝑠": "s",
  "𝒔": "s",
  "𝓈": "s",
  "𝓼": "s",
  "𝔰": "s",
  "𝕤": "s",
  "𝖘": "s",
  "𝗌": "s",
  "𝘀": "s",
  "𝘴": "s",
  "𝙨": "s",
  "𝚜": "s",
  "ꜱ": "s",
  "ƽ": "s",
  "ѕ": "s",
  "ꮪ": "s",
  "𑣁": "s",
  "𐑈": "s",
  "Ｓ": "S",
  "𝐒": "S",
  "𝑆": "S",
  "𝑺": "S",
  "𝒮": "S",
  "𝓢": "S",
  "𝔖": "S",
  "𝕊": "S",
  "𝕾": "S",
  "𝖲": "S",
  "𝗦": "S",
  "𝘚": "S",
  "𝙎": "S",
  "𝚂": "S",
  "Ѕ": "S",
  "Տ": "S",
  "Ꮥ": "S",
  "Ꮪ": "S",
  "ꓢ": "S",
  "𖼺": "S",
  "𐊖": "S",
  "𐐠": "S",
  "ʂ": "s̨",
  "ᵴ": "s̴",
  "ꞵ": "ß",
  "β": "ß",
  "ϐ": "ß",
  "𝛃": "ß",
  "𝛽": "ß",
  "𝜷": "ß",
  "𝝱": "ß",
  "𝞫": "ß",
  "Ᏸ": "ß",
  "🝜": "sss",
  "ﬆ": "st",
  "∫": "ʃ",
  "ꭍ": "ʃ",
  "∑": "Ʃ",
  "⅀": "Ʃ",
  "Σ": "Ʃ",
  "𝚺": "Ʃ",
  "𝛴": "Ʃ",
  "𝜮": "Ʃ",
  "𝝨": "Ʃ",
  "𝞢": "Ʃ",
  "ⵉ": "Ʃ",
  "∬": "ʃʃ",
  "∭": "ʃʃʃ",
  "⨌": "ʃʃʃʃ",
  "𝐭": "t",
  "𝑡": "t",
  "𝒕": "t",
  "𝓉": "t",
  "𝓽": "t",
  "𝔱": "t",
  "𝕥": "t",
  "𝖙": "t",
  "𝗍": "t",
  "𝘁": "t",
  "𝘵": "t",
  "𝙩": "t",
  "𝚝": "t",
  "⊤": "T",
  "⟙": "T",
  "🝨": "T",
  "Ｔ": "T",
  "𝐓": "T",
  "𝑇": "T",
  "𝑻": "T",
  "𝒯": "T",
  "𝓣": "T",
  "𝔗": "T",
  "𝕋": "T",
  "𝕿": "T",
  "𝖳": "T",
  "𝗧": "T",
  "𝘛": "T",
  "𝙏": "T",
  "𝚃": "T",
  "Τ": "T",
  "𝚻": "T",
  "𝛵": "T",
  "𝜯": "T",
  "𝝩": "T",
  "𝞣": "T",
  "Ⲧ": "T",
  "Т": "T",
  "Ꭲ": "T",
  "ꓔ": "T",
  "𖼊": "T",
  "𑢼": "T",
  "𐊗": "T",
  "𐊱": "T",
  "𐌕": "T",
  "ƭ": "t̔",
  "⍡": "T̈",
  "Ⱦ": "T̸",
  "Ț": "Ţ",
  "Ʈ": "T̨",
  "Ҭ": "T̩",
  "₮": "T⃫",
  "ŧ": "t̵",
  "Ŧ": "T̵",
  "ᵵ": "t̴",
  "Ⴀ": "Ꞇ",
  "Ꜩ": "T3",
  "ʨ": "tɕ",
  "℡": "TEL",
  "ꝷ": "tf",
  "ʦ": "ts",
  "ʧ": "tʃ",
  "ꜩ": "tȝ",
  "τ": "ᴛ",
  "𝛕": "ᴛ",
  "𝜏": "ᴛ",
  "𝝉": "ᴛ",
  "𝞃": "ᴛ",
  "𝞽": "ᴛ",
  "т": "ᴛ",
  "ꭲ": "ᴛ",
  "ҭ": "ᴛ̩",
  "ţ": "ƫ",
  "ț": "ƫ",
  "Ꮏ": "ƫ",
  "𝐮": "u",
  "𝑢": "u",
  "𝒖": "u",
  "𝓊": "u",
  "𝓾": "u",
  "𝔲": "u",
  "𝕦": "u",
  "𝖚": "u",
  "𝗎": "u",
  "𝘂": "u",
  "𝘶": "u",
  "𝙪": "u",
  "𝚞": "u",
  "ꞟ": "u",
  "ᴜ": "u",
  "ꭎ": "u",
  "ꭒ": "u",
  "ʋ": "u",
  "υ": "u",
  "𝛖": "u",
  "𝜐": "u",
  "𝝊": "u",
  "𝞄": "u",
  "𝞾": "u",
  "ս": "u",
  "𐓶": "u",
  "𑣘": "u",
  "∪": "U",
  "⋃": "U",
  "𝐔": "U",
  "𝑈": "U",
  "𝑼": "U",
  "𝒰": "U",
  "𝓤": "U",
  "𝔘": "U",
  "𝕌": "U",
  "𝖀": "U",
  "𝖴": "U",
  "𝗨": "U",
  "𝘜": "U",
  "𝙐": "U",
  "𝚄": "U",
  "Ս": "U",
  "ሀ": "U",
  "𐓎": "U",
  "ᑌ": "U",
  "ꓴ": "U",
  "𖽂": "U",
  "𑢸": "U",
  "ǔ": "ŭ",
  "Ǔ": "Ŭ",
  "ᵾ": "u̵",
  "ꮜ": "u̵",
  "Ʉ": "U̵",
  "Ꮜ": "U̵",
  "ᑘ": "U·",
  "ᑧ": "U'",
  "ᵫ": "ue",
  "ꭣ": "uo",
  "ṃ": "ꭑ",
  "պ": "ɰ",
  "ሣ": "ɰ",
  "℧": "Ʊ",
  "ᘮ": "Ʊ",
  "ᘴ": "Ʊ",
  "ᵿ": "ʊ̵",
  "∨": "v",
  "⋁": "v",
  "ｖ": "v",
  "ⅴ": "v",
  "𝐯": "v",
  "𝑣": "v",
  "𝒗": "v",
  "𝓋": "v",
  "𝓿": "v",
  "𝔳": "v",
  "𝕧": "v",
  "𝖛": "v",
  "𝗏": "v",
  "𝘃": "v",
  "𝘷": "v",
  "𝙫": "v",
  "𝚟": "v",
  "ᴠ": "v",
  "ν": "v",
  "𝛎": "v",
  "𝜈": "v",
  "𝝂": "v",
  "𝝼": "v",
  "𝞶": "v",
  "ѵ": "v",
  "ט": "v",
  "𑜆": "v",
  "ꮩ": "v",
  "𑣀": "v",
  "𝈍": "V",
  "٧": "V",
  "۷": "V",
  "Ⅴ": "V",
  "𝐕": "V",
  "𝑉": "V",
  "𝑽": "V",
  "𝒱": "V",
  "𝓥": "V",
  "𝔙": "V",
  "𝕍": "V",
  "𝖁": "V",
  "𝖵": "V",
  "𝗩": "V",
  "𝘝": "V",
  "𝙑": "V",
  "𝚅": "V",
  "Ѵ": "V",
  "ⴸ": "V",
  "Ꮩ": "V",
  "ᐯ": "V",
  "ꛟ": "V",
  "ꓦ": "V",
  "𖼈": "V",
  "𑢠": "V",
  "𐔝": "V",
  "𐆗": "V̵",
  "ᐻ": "V·",
  "🝬": "VB",
  "ⅵ": "vi",
  "ⅶ": "vii",
  "ⅷ": "viii",
  "Ⅵ": "Vl",
  "Ⅶ": "Vll",
  "Ⅷ": "Vlll",
  "🜈": "Vᷤ",
  "ᴧ": "ʌ",
  "𐓘": "ʌ",
  "٨": "Ʌ",
  "۸": "Ʌ",
  "Λ": "Ʌ",
  "𝚲": "Ʌ",
  "𝛬": "Ʌ",
  "𝜦": "Ʌ",
  "𝝠": "Ʌ",
  "𝞚": "Ʌ",
  "Л": "Ʌ",
  "ⴷ": "Ʌ",
  "𐒰": "Ʌ",
  "ᐱ": "Ʌ",
  "ꛎ": "Ʌ",
  "ꓥ": "Ʌ",
  "𖼽": "Ʌ",
  "𐊍": "Ʌ",
  "Ӆ": "Ʌ̦",
  "ᐽ": "Ʌ·",
  "ɯ": "w",
  "𝐰": "w",
  "𝑤": "w",
  "𝒘": "w",
  "𝓌": "w",
  "𝔀": "w",
  "𝔴": "w",
  "𝕨": "w",
  "𝖜": "w",
  "𝗐": "w",
  "𝘄": "w",
  "𝘸": "w",
  "𝙬": "w",
  "𝚠": "w",
  "ᴡ": "w",
  "ѡ": "w",
  "ԝ": "w",
  "ա": "w",
  "𑜊": "w",
  "𑜎": "w",
  "𑜏": "w",
  "ꮃ": "w",
  "𑣯": "W",
  "𑣦": "W",
  "𝐖": "W",
  "𝑊": "W",
  "𝑾": "W",
  "𝒲": "W",
  "𝓦": "W",
  "𝔚": "W",
  "𝕎": "W",
  "𝖂": "W",
  "𝖶": "W",
  "𝗪": "W",
  "𝘞": "W",
  "𝙒": "W",
  "𝚆": "W",
  "Ԝ": "W",
  "Ꮃ": "W",
  "Ꮤ": "W",
  "ꓪ": "W",
  "ѽ": "w҆҇",
  "𑓅": "ẇ",
  "₩": "W̵",
  "ꝡ": "w̦",
  "ᴍ": "ʍ",
  "м": "ʍ",
  "ꮇ": "ʍ",
  "ӎ": "ʍ̦",
  "᙮": "x",
  "×": "x",
  "⤫": "x",
  "⤬": "x",
  "⨯": "x",
  "ｘ": "x",
  "ⅹ": "x",
  "𝐱": "x",
  "𝑥": "x",
  "𝒙": "x",
  "𝓍": "x",
  "𝔁": "x",
  "𝔵": "x",
  "𝕩": "x",
  "𝖝": "x",
  "𝗑": "x",
  "𝘅": "x",
  "𝘹": "x",
  "𝙭": "x",
  "𝚡": "x",
  "х": "x",
  "ᕁ": "x",
  "ᕽ": "x",
  "ⷯ": "ͯ",
  "᙭": "X",
  "╳": "X",
  "𐌢": "X",
  "𑣬": "X",
  "Ｘ": "X",
  "Ⅹ": "X",
  "𝐗": "X",
  "𝑋": "X",
  "𝑿": "X",
  "𝒳": "X",
  "𝓧": "X",
  "𝔛": "X",
  "𝕏": "X",
  "𝖃": "X",
  "𝖷": "X",
  "𝗫": "X",
  "𝘟": "X",
  "𝙓": "X",
  "𝚇": "X",
  "Ꭓ": "X",
  "Χ": "X",
  "𝚾": "X",
  "𝛸": "X",
  "𝜲": "X",
  "𝝬": "X",
  "𝞦": "X",
  "Ⲭ": "X",
  "Х": "X",
  "ⵝ": "X",
  "ᚷ": "X",
  "ꓫ": "X",
  "𐊐": "X",
  "𐊴": "X",
  "𐌗": "X",
  "𐔧": "X",
  "⨰": "ẋ",
  "Ҳ": "X̩",
  "𐆖": "X̵",
  "ⅺ": "xi",
  "ⅻ": "xii",
  "Ⅺ": "Xl",
  "Ⅻ": "Xll",
  "ɣ": "y",
  "ᶌ": "y",
  "ｙ": "y",
  "𝐲": "y",
  "𝑦": "y",
  "𝒚": "y",
  "𝓎": "y",
  "𝔂": "y",
  "𝔶": "y",
  "𝕪": "y",
  "𝖞": "y",
  "𝗒": "y",
  "𝘆": "y",
  "𝘺": "y",
  "𝙮": "y",
  "𝚢": "y",
  "ʏ": "y",
  "ỿ": "y",
  "ꭚ": "y",
  "γ": "y",
  "ℽ": "y",
  "𝛄": "y",
  "𝛾": "y",
  "𝜸": "y",
  "𝝲": "y",
  "𝞬": "y",
  "у": "y",
  "ү": "y",
  "ყ": "y",
  "𑣜": "y",
  "Ｙ": "Y",
  "𝐘": "Y",
  "𝑌": "Y",
  "𝒀": "Y",
  "𝒴": "Y",
  "𝓨": "Y",
  "𝔜": "Y",
  "𝕐": "Y",
  "𝖄": "Y",
  "𝖸": "Y",
  "𝗬": "Y",
  "𝘠": "Y",
  "𝙔": "Y",
  "𝚈": "Y",
  "Υ": "Y",
  "ϒ": "Y",
  "𝚼": "Y",
  "𝛶": "Y",
  "𝜰": "Y",
  "𝝪": "Y",
  "𝞤": "Y",
  "Ⲩ": "Y",
  "У": "Y",
  "Ү": "Y",
  "Ꭹ": "Y",
  "Ꮍ": "Y",
  "ꓬ": "Y",
  "𖽃": "Y",
  "𑢤": "Y",
  "𐊲": "Y",
  "ƴ": "y̔",
  "ɏ": "y̵",
  "ұ": "y̵",
  "¥": "Y̵",
  "Ɏ": "Y̵",
  "Ұ": "Y̵",
  "ʒ": "ȝ",
  "ꝫ": "ȝ",
  "ⳍ": "ȝ",
  "ӡ": "ȝ",
  "ჳ": "ȝ",
  "𝐳": "z",
  "𝑧": "z",
  "𝒛": "z",
  "𝓏": "z",
  "𝔃": "z",
  "𝔷": "z",
  "𝕫": "z",
  "𝖟": "z",
  "𝗓": "z",
  "𝘇": "z",
  "𝘻": "z",
  "𝙯": "z",
  "𝚣": "z",
  "ᴢ": "z",
  "ꮓ": "z",
  "𑣄": "z",
  "𐋵": "Z",
  "𑣥": "Z",
  "Ｚ": "Z",
  "ℤ": "Z",
  "ℨ": "Z",
  "𝐙": "Z",
  "𝑍": "Z",
  "𝒁": "Z",
  "𝒵": "Z",
  "𝓩": "Z",
  "𝖅": "Z",
  "𝖹": "Z",
  "𝗭": "Z",
  "𝘡": "Z",
  "𝙕": "Z",
  "𝚉": "Z",
  "Ζ": "Z",
  "𝚭": "Z",
  "𝛧": "Z",
  "𝜡": "Z",
  "𝝛": "Z",
  "𝞕": "Z",
  "Ꮓ": "Z",
  "ꓜ": "Z",
  "𑢩": "Z",
  "ʐ": "z̨",
  "ƶ": "z̵",
  "Ƶ": "Z̵",
  "ȥ": "z̦",
  "Ȥ": "Z̦",
  "ᵶ": "z̴",
  "ƿ": "þ",
  "ϸ": "þ",
  "Ϸ": "Þ",
  "𐓄": "Þ",
  "⁹": "ꝰ",
  "ᴤ": "ƨ",
  "ϩ": "ƨ",
  "ꙅ": "ƨ",
  "ь": "ƅ",
  "ꮟ": "ƅ",
  "ы": "ƅi",
  "ꭾ": "ɂ",
  "ˤ": "ˁ",
  "ꛍ": "ʡ",
  "⊙": "ʘ",
  "☉": "ʘ",
  "⨀": "ʘ",
  "Ꙩ": "ʘ",
  "ⵙ": "ʘ",
  "𐓃": "ʘ",
  "ℾ": "Γ",
  "𝚪": "Γ",
  "𝛤": "Γ",
  "𝜞": "Γ",
  "𝝘": "Γ",
  "𝞒": "Γ",
  "Ⲅ": "Γ",
  "Г": "Γ",
  "Ꮁ": "Γ",
  "ᒥ": "Γ",
  "𖼇": "Γ",
  "Ғ": "Γ̵",
  "ᒯ": "Γ·",
  "Ґ": "Γ'",
  "∆": "Δ",
  "△": "Δ",
  "🜂": "Δ",
  "𝚫": "Δ",
  "𝛥": "Δ",
  "𝜟": "Δ",
  "𝝙": "Δ",
  "𝞓": "Δ",
  "Ⲇ": "Δ",
  "ⵠ": "Δ",
  "ᐃ": "Δ",
  "𖼚": "Δ",
  "𐊅": "Δ",
  "𐊣": "Δ",
  "⍙": "Δ̲",
  "ᐏ": "Δ·",
  "ᐬ": "Δᐠ",
  "𝟋": "ϝ",
  "𝛇": "ζ",
  "𝜁": "ζ",
  "𝜻": "ζ",
  "𝝵": "ζ",
  "𝞯": "ζ",
  "ⳤ": "ϗ",
  "𝛌": "λ",
  "𝜆": "λ",
  "𝝀": "λ",
  "𝝺": "λ",
  "𝞴": "λ",
  "Ⲗ": "λ",
  "𐓛": "λ",
  "µ": "μ",
  "𝛍": "μ",
  "𝜇": "μ",
  "𝝁": "μ",
  "𝝻": "μ",
  "𝞵": "μ",
  "𝛏": "ξ",
  "𝜉": "ξ",
  "𝝃": "ξ",
  "𝝽": "ξ",
  "𝞷": "ξ",
  "𝚵": "Ξ",
  "𝛯": "Ξ",
  "𝜩": "Ξ",
  "𝝣": "Ξ",
  "𝞝": "Ξ",
  "ϖ": "π",
  "ℼ": "π",
  "𝛑": "π",
  "𝛡": "π",
  "𝜋": "π",
  "𝜛": "π",
  "𝝅": "π",
  "𝝕": "π",
  "𝝿": "π",
  "𝞏": "π",
  "𝞹": "π",
  "𝟉": "π",
  "ᴨ": "π",
  "п": "π",
  "∏": "Π",
  "ℿ": "Π",
  "𝚷": "Π",
  "𝛱": "Π",
  "𝜫": "Π",
  "𝝥": "Π",
  "𝞟": "Π",
  "Ⲡ": "Π",
  "П": "Π",
  "ꛛ": "Π",
  "𐊭": "Ϙ",
  "𐌒": "Ϙ",
  "ϛ": "ς",
  "𝛓": "ς",
  "𝜍": "ς",
  "𝝇": "ς",
  "𝞁": "ς",
  "𝞻": "ς",
  "𝚽": "Φ",
  "𝛷": "Φ",
  "𝜱": "Φ",
  "𝝫": "Φ",
  "𝞥": "Φ",
  "Ⲫ": "Φ",
  "Ф": "Φ",
  "Փ": "Φ",
  "ቀ": "Φ",
  "ᛰ": "Φ",
  "𐊳": "Φ",
  "ꭓ": "χ",
  "ꭕ": "χ",
  "𝛘": "χ",
  "𝜒": "χ",
  "𝝌": "χ",
  "𝞆": "χ",
  "𝟀": "χ",
  "ⲭ": "χ",
  "𝛙": "ψ",
  "𝜓": "ψ",
  "𝝍": "ψ",
  "𝞇": "ψ",
  "𝟁": "ψ",
  "ѱ": "ψ",
  "𐓹": "ψ",
  "𝚿": "Ψ",
  "𝛹": "Ψ",
  "𝜳": "Ψ",
  "𝝭": "Ψ",
  "𝞧": "Ψ",
  "Ⲯ": "Ψ",
  "Ѱ": "Ψ",
  "𐓑": "Ψ",
  "ᛘ": "Ψ",
  "𐊵": "Ψ",
  "⍵": "ω",
  "ꞷ": "ω",
  "𝛚": "ω",
  "𝜔": "ω",
  "𝝎": "ω",
  "𝞈": "ω",
  "𝟂": "ω",
  "ⲱ": "ω",
  "ꙍ": "ω",
  "Ω": "Ω",
  "𝛀": "Ω",
  "𝛺": "Ω",
  "𝜴": "Ω",
  "𝝮": "Ω",
  "𝞨": "Ω",
  "ᘯ": "Ω",
  "ᘵ": "Ω",
  "𐊶": "Ω",
  "⍹": "ω̲",
  "ώ": "ῴ",
  "☰": "Ⲷ",
  "Ⳝ": "Ϭ",
  "җ": "ж̩",
  "Җ": "Ж̩",
  "𝈋": "И",
  "Ͷ": "И",
  "ꚡ": "И",
  "𐐥": "И",
  "Й": "Ѝ",
  "Ҋ": "Ѝ̦",
  "ѝ": "й",
  "ҋ": "й̦",
  "𐒼": "Ӄ",
  "ᴫ": "л",
  "ӆ": "л̦",
  "ꭠ": "љ",
  "𐓫": "ꙩ",
  "ᷮ": "ⷬ",
  "𐓍": "Ћ",
  "𝈂": "Ӿ",
  "𝈢": "Ѡ",
  "Ꮗ": "Ѡ",
  "ᗯ": "Ѡ",
  "Ѽ": "Ѡ҆҇",
  "ᣭ": "Ѡ·",
  "Ꞷ": "Ꙍ",
  "ӌ": "ҷ",
  "Ӌ": "Ҷ",
  "Ҿ": "Ҽ̨",
  "ⲽ": "ш",
  "Ⲽ": "Ш",
  "Ꙑ": "Ъl",
  "℈": "Э",
  "🜁": "Ꙙ",
  "𖼜": "Ꙙ",
  "ꦒ": "ⰿ",
  "և": "եւ",
  "ኔ": "ձ",
  "ﬔ": "մե",
  "ﬕ": "մի",
  "ﬗ": "մխ",
  "ﬓ": "մն",
  "∩": "Ո",
  "⋂": "Ո",
  "𝉅": "Ո",
  "በ": "Ո",
  "ᑎ": "Ո",
  "ꓵ": "Ո",
  "ᑚ": "Ո·",
  "ᑨ": "Ո'",
  "ﬖ": "վն",
  "₽": "Ք",
  "˓": "ՙ",
  "ʿ": "ՙ",
  "ℵ": "א",
  "ﬡ": "א",
  "אָ": "אַ",
  "אּ": "אַ",
  "ﭏ": "אל",
  "ℶ": "ב",
  "ℷ": "ג",
  "ℸ": "ד",
  "ﬢ": "ד",
  "ﬣ": "ה",
  "יּ": "יִ",
  "ﬤ": "כ",
  "ﬥ": "ל",
  "ﬦ": "ם",
  "ﬠ": "ע",
  "ﬧ": "ר",
  "שׂ": "שׁ",
  "שּ": "שׁ",
  "שּׂ": "שּׁ",
  "ﬨ": "ת",
  "ﺀ": "ء",
  "۽": "ء͈",
  "ﺂ": "آ",
  "ﺁ": "آ",
  "ﭑ": "ٱ",
  "ﭐ": "ٱ",
  "𞸁": "ب",
  "𞸡": "ب",
  "𞹡": "ب",
  "𞺁": "ب",
  "𞺡": "ب",
  "ﺑ": "ب",
  "ﺒ": "ب",
  "ﺐ": "ب",
  "ﺏ": "ب",
  "ݑ": "بۛ",
  "ࢶ": "بۢ",
  "ࢡ": "بٔ",
  "ﲠ": "بo",
  "ﳢ": "بo",
  "ﲜ": "بج",
  "ﰅ": "بج",
  "ﲝ": "بح",
  "ﰆ": "بح",
  "ﷂ": "بحى",
  "ﲞ": "بخ",
  "ﰇ": "بخ",
  "ﳒ": "بخ",
  "ﱋ": "بخ",
  "ﶞ": "بخى",
  "ﱪ": "بر",
  "ﱫ": "بز",
  "ﲟ": "بم",
  "ﳡ": "بم",
  "ﱬ": "بم",
  "ﰈ": "بم",
  "ﱭ": "بن",
  "ﱮ": "بى",
  "ﰉ": "بى",
  "ﱯ": "بى",
  "ﰊ": "بى",
  "ﭔ": "ٻ",
  "ﭕ": "ٻ",
  "ﭓ": "ٻ",
  "ﭒ": "ٻ",
  "ې": "ٻ",
  "ﯦ": "ٻ",
  "ﯧ": "ٻ",
  "ﯥ": "ٻ",
  "ﯤ": "ٻ",
  "ﭜ": "ڀ",
  "ﭝ": "ڀ",
  "ﭛ": "ڀ",
  "ﭚ": "ڀ",
  "ࢩ": "ݔ",
  "ݧ": "ݔ",
  "⍥": "ة",
  "ö": "ة",
  "ﺔ": "ة",
  "ﺓ": "ة",
  "ۃ": "ة",
  "𞸕": "ت",
  "𞸵": "ت",
  "𞹵": "ت",
  "𞺕": "ت",
  "𞺵": "ت",
  "ﺗ": "ت",
  "ﺘ": "ت",
  "ﺖ": "ت",
  "ﺕ": "ت",
  "ﲥ": "تo",
  "ﳤ": "تo",
  "ﲡ": "تج",
  "ﰋ": "تج",
  "ﵐ": "تجم",
  "ﶠ": "تجى",
  "ﶟ": "تجى",
  "ﲢ": "تح",
  "ﰌ": "تح",
  "ﵒ": "تحج",
  "ﵑ": "تحج",
  "ﵓ": "تحم",
  "ﲣ": "تخ",
  "ﰍ": "تخ",
  "ﵔ": "تخم",
  "ﶢ": "تخى",
  "ﶡ": "تخى",
  "ﱰ": "تر",
  "ﱱ": "تز",
  "ﲤ": "تم",
  "ﳣ": "تم",
  "ﱲ": "تم",
  "ﰎ": "تم",
  "ﵕ": "تمج",
  "ﵖ": "تمح",
  "ﵗ": "تمخ",
  "ﶤ": "تمى",
  "ﶣ": "تمى",
  "ﱳ": "تن",
  "ﱴ": "تى",
  "ﰏ": "تى",
  "ﱵ": "تى",
  "ﰐ": "تى",
  "ﭠ": "ٺ",
  "ﭡ": "ٺ",
  "ﭟ": "ٺ",
  "ﭞ": "ٺ",
  "ﭤ": "ٿ",
  "ﭥ": "ٿ",
  "ﭣ": "ٿ",
  "ﭢ": "ٿ",
  "𞸂": "ج",
  "𞸢": "ج",
  "𞹂": "ج",
  "𞹢": "ج",
  "𞺂": "ج",
  "𞺢": "ج",
  "ﺟ": "ج",
  "ﺠ": "ج",
  "ﺞ": "ج",
  "ﺝ": "ج",
  "ﲧ": "جح",
  "ﰕ": "جح",
  "ﶦ": "جحى",
  "ﶾ": "جحى",
  "ﷻ": "جل جلlلo",
  "ﲨ": "جم",
  "ﰖ": "جم",
  "ﵙ": "جمح",
  "ﵘ": "جمح",
  "ﶧ": "جمى",
  "ﶥ": "جمى",
  "ﴝ": "جى",
  "ﴁ": "جى",
  "ﴞ": "جى",
  "ﴂ": "جى",
  "ﭸ": "ڃ",
  "ﭹ": "ڃ",
  "ﭷ": "ڃ",
  "ﭶ": "ڃ",
  "ﭴ": "ڄ",
  "ﭵ": "ڄ",
  "ﭳ": "ڄ",
  "ﭲ": "ڄ",
  "ﭼ": "چ",
  "ﭽ": "چ",
  "ﭻ": "چ",
  "ﭺ": "چ",
  "ﮀ": "ڇ",
  "ﮁ": "ڇ",
  "ﭿ": "ڇ",
  "ﭾ": "ڇ",
  "𞸇": "ح",
  "𞸧": "ح",
  "𞹇": "ح",
  "𞹧": "ح",
  "𞺇": "ح",
  "𞺧": "ح",
  "ﺣ": "ح",
  "ﺤ": "ح",
  "ﺢ": "ح",
  "ﺡ": "ح",
  "څ": "حۛ",
  "ځ": "حٔ",
  "ݲ": "حٔ",
  "ﲩ": "حج",
  "ﰗ": "حج",
  "ﶿ": "حجى",
  "ﲪ": "حم",
  "ﰘ": "حم",
  "ﵛ": "حمى",
  "ﵚ": "حمى",
  "ﴛ": "حى",
  "ﳿ": "حى",
  "ﴜ": "حى",
  "ﴀ": "حى",
  "𞸗": "خ",
  "𞸷": "خ",
  "𞹗": "خ",
  "𞹷": "خ",
  "𞺗": "خ",
  "𞺷": "خ",
  "ﺧ": "خ",
  "ﺨ": "خ",
  "ﺦ": "خ",
  "ﺥ": "خ",
  "ﲫ": "خج",
  "ﰙ": "خج",
  "ﰚ": "خح",
  "ﲬ": "خم",
  "ﰛ": "خم",
  "ﴟ": "خى",
  "ﴃ": "خى",
  "ﴠ": "خى",
  "ﴄ": "خى",
  "𐋡": "د",
  "𞸃": "د",
  "𞺃": "د",
  "𞺣": "د",
  "ﺪ": "د",
  "ﺩ": "د",
  "ڈ": "دؕ",
  "ﮉ": "دؕ",
  "ﮈ": "دؕ",
  "ڎ": "دۛ",
  "ﮇ": "دۛ",
  "ﮆ": "دۛ",
  "ۮ": "د̂",
  "ࢮ": "د̤̣",
  "𞸘": "ذ",
  "𞺘": "ذ",
  "𞺸": "ذ",
  "ﺬ": "ذ",
  "ﺫ": "ذ",
  "ﱛ": "ذٰ",
  "ڋ": "ڊؕ",
  "ﮅ": "ڌ",
  "ﮄ": "ڌ",
  "ﮃ": "ڍ",
  "ﮂ": "ڍ",
  "𞸓": "ر",
  "𞺓": "ر",
  "𞺳": "ر",
  "ﺮ": "ر",
  "ﺭ": "ر",
  "ڑ": "رؕ",
  "ﮍ": "رؕ",
  "ﮌ": "رؕ",
  "ژ": "رۛ",
  "ﮋ": "رۛ",
  "ﮊ": "رۛ",
  "ڒ": "ر̆",
  "ࢹ": "ر̆̇",
  "ۯ": "ر̂",
  "ݬ": "رٔ",
  "ﱜ": "رٰ",
  "ﷶ": "رسول",
  "﷼": "رىlل",
  "𞸆": "ز",
  "𞺆": "ز",
  "𞺦": "ز",
  "ﺰ": "ز",
  "ﺯ": "ز",
  "ࢲ": "ز̂",
  "ݱ": "ڗؕ",
  "𞸎": "س",
  "𞸮": "س",
  "𞹎": "س",
  "𞹮": "س",
  "𞺎": "س",
  "𞺮": "س",
  "ﺳ": "س",
  "ﺴ": "س",
  "ﺲ": "س",
  "ﺱ": "س",
  "ش": "سۛ",
  "𞸔": "سۛ",
  "𞸴": "سۛ",
  "𞹔": "سۛ",
  "𞹴": "سۛ",
  "𞺔": "سۛ",
  "𞺴": "سۛ",
  "ﺷ": "سۛ",
  "ﺸ": "سۛ",
  "ﺶ": "سۛ",
  "ﺵ": "سۛ",
  "ݾ": "س̂",
  "ﴱ": "سo",
  "ﳨ": "سo",
  "ﴲ": "سۛo",
  "ﳪ": "سۛo",
  "ﲭ": "سج",
  "ﴴ": "سج",
  "ﰜ": "سج",
  "ﴭ": "سۛج",
  "ﴷ": "سۛج",
  "ﴥ": "سۛج",
  "ﴉ": "سۛج",
  "ﵝ": "سجح",
  "ﵞ": "سجى",
  "ﵩ": "سۛجى",
  "ﲮ": "سح",
  "ﴵ": "سح",
  "ﰝ": "سح",
  "ﴮ": "سۛح",
  "ﴸ": "سۛح",
  "ﴦ": "سۛح",
  "ﴊ": "سۛح",
  "ﵜ": "سحج",
  "ﵨ": "سۛحم",
  "ﵧ": "سۛحم",
  "ﶪ": "سۛحى",
  "ﲯ": "سخ",
  "ﴶ": "سخ",
  "ﰞ": "سخ",
  "ﴯ": "سۛخ",
  "ﴹ": "سۛخ",
  "ﴧ": "سۛخ",
  "ﴋ": "سۛخ",
  "ﶨ": "سخى",
  "ﷆ": "سخى",
  "ﴪ": "سر",
  "ﴎ": "سر",
  "ﴩ": "سۛر",
  "ﴍ": "سۛر",
  "ﲰ": "سم",
  "ﳧ": "سم",
  "ﰟ": "سم",
  "ﴰ": "سۛم",
  "ﳩ": "سۛم",
  "ﴨ": "سۛم",
  "ﴌ": "سۛم",
  "ﵡ": "سمج",
  "ﵠ": "سمح",
  "ﵟ": "سمح",
  "ﵫ": "سۛمخ",
  "ﵪ": "سۛمخ",
  "ﵣ": "سمم",
  "ﵢ": "سمم",
  "ﵭ": "سۛمم",
  "ﵬ": "سۛمم",
  "ﴗ": "سى",
  "ﳻ": "سى",
  "ﴘ": "سى",
  "ﳼ": "سى",
  "ﴙ": "سۛى",
  "ﳽ": "سۛى",
  "ﴚ": "سۛى",
  "ﳾ": "سۛى",
  "𐋲": "ص",
  "𞸑": "ص",
  "𞸱": "ص",
  "𞹑": "ص",
  "𞹱": "ص",
  "𞺑": "ص",
  "𞺱": "ص",
  "ﺻ": "ص",
  "ﺼ": "ص",
  "ﺺ": "ص",
  "ﺹ": "ص",
  "ڞ": "صۛ",
  "ࢯ": "ص̤̣",
  "ﲱ": "صح",
  "ﰠ": "صح",
  "ﵥ": "صحح",
  "ﵤ": "صحح",
  "ﶩ": "صحى",
  "ﲲ": "صخ",
  "ﴫ": "صر",
  "ﴏ": "صر",
  "ﷵ": "صلعم",
  "ﷹ": "صلى",
  "ﷰ": "صلى",
  "ﷺ": "صلى lللo علىo وسلم",
  "ﲳ": "صم",
  "ﰡ": "صم",
  "ﷅ": "صمم",
  "ﵦ": "صمم",
  "ﴡ": "صى",
  "ﴅ": "صى",
  "ﴢ": "صى",
  "ﴆ": "صى",
  "𞸙": "ض",
  "𞸹": "ض",
  "𞹙": "ض",
  "𞹹": "ض",
  "𞺙": "ض",
  "𞺹": "ض",
  "ﺿ": "ض",
  "ﻀ": "ض",
  "ﺾ": "ض",
  "ﺽ": "ض",
  "ﲴ": "ضج",
  "ﰢ": "ضج",
  "ﲵ": "ضح",
  "ﰣ": "ضح",
  "ﵮ": "ضحى",
  "ﶫ": "ضحى",
  "ﲶ": "ضخ",
  "ﰤ": "ضخ",
  "ﵰ": "ضخم",
  "ﵯ": "ضخم",
  "ﴬ": "ضر",
  "ﴐ": "ضر",
  "ﲷ": "ضم",
  "ﰥ": "ضم",
  "ﴣ": "ضى",
  "ﴇ": "ضى",
  "ﴤ": "ضى",
  "ﴈ": "ضى",
  "𐋨": "ط",
  "𞸈": "ط",
  "𞹨": "ط",
  "𞺈": "ط",
  "𞺨": "ط",
  "ﻃ": "ط",
  "ﻄ": "ط",
  "ﻂ": "ط",
  "ﻁ": "ط",
  "ڟ": "طۛ",
  "ﲸ": "طح",
  "ﰦ": "طح",
  "ﴳ": "طم",
  "ﴺ": "طم",
  "ﰧ": "طم",
  "ﵲ": "طمح",
  "ﵱ": "طمح",
  "ﵳ": "طمم",
  "ﵴ": "طمى",
  "ﴑ": "طى",
  "ﳵ": "طى",
  "ﴒ": "طى",
  "ﳶ": "طى",
  "𞸚": "ظ",
  "𞹺": "ظ",
  "𞺚": "ظ",
  "𞺺": "ظ",
  "ﻇ": "ظ",
  "ﻈ": "ظ",
  "ﻆ": "ظ",
  "ﻅ": "ظ",
  "ﲹ": "ظم",
  "ﴻ": "ظم",
  "ﰨ": "ظم",
  "؏": "ع",
  "𞸏": "ع",
  "𞸯": "ع",
  "𞹏": "ع",
  "𞹯": "ع",
  "𞺏": "ع",
  "𞺯": "ع",
  "ﻋ": "ع",
  "ﻌ": "ع",
  "ﻊ": "ع",
  "ﻉ": "ع",
  "ﲺ": "عج",
  "ﰩ": "عج",
  "ﷄ": "عجم",
  "ﵵ": "عجم",
  "ﷷ": "علىo",
  "ﲻ": "عم",
  "ﰪ": "عم",
  "ﵷ": "عمم",
  "ﵶ": "عمم",
  "ﵸ": "عمى",
  "ﶶ": "عمى",
  "ﴓ": "عى",
  "ﳷ": "عى",
  "ﴔ": "عى",
  "ﳸ": "عى",
  "𞸛": "غ",
  "𞸻": "غ",
  "𞹛": "غ",
  "𞹻": "غ",
  "𞺛": "غ",
  "𞺻": "غ",
  "ﻏ": "غ",
  "ﻐ": "غ",
  "ﻎ": "غ",
  "ﻍ": "غ",
  "ﲼ": "غج",
  "ﰫ": "غج",
  "ﲽ": "غم",
  "ﰬ": "غم",
  "ﵹ": "غمم",
  "ﵻ": "غمى",
  "ﵺ": "غمى",
  "ﴕ": "غى",
  "ﳹ": "غى",
  "ﴖ": "غى",
  "ﳺ": "غى",
  "𞸐": "ف",
  "𞸰": "ف",
  "𞹰": "ف",
  "𞺐": "ف",
  "𞺰": "ف",
  "ﻓ": "ف",
  "ﻔ": "ف",
  "ﻒ": "ف",
  "ﻑ": "ف",
  "ڧ": "ف",
  "ﲾ": "فج",
  "ﰭ": "فج",
  "ﲿ": "فح",
  "ﰮ": "فح",
  "ﳀ": "فخ",
  "ﰯ": "فخ",
  "ﵽ": "فخم",
  "ﵼ": "فخم",
  "ﳁ": "فم",
  "ﰰ": "فم",
  "ﷁ": "فمى",
  "ﱼ": "فى",
  "ﰱ": "فى",
  "ﱽ": "فى",
  "ﰲ": "فى",
  "𞸞": "ڡ",
  "𞹾": "ڡ",
  "ࢻ": "ڡ",
  "ٯ": "ڡ",
  "𞸟": "ڡ",
  "𞹟": "ڡ",
  "ࢼ": "ڡ",
  "ڤ": "ڡۛ",
  "ﭬ": "ڡۛ",
  "ﭭ": "ڡۛ",
  "ﭫ": "ڡۛ",
  "ﭪ": "ڡۛ",
  "ڨ": "ڡۛ",
  "ࢤ": "ڢۛ",
  "ﭰ": "ڦ",
  "ﭱ": "ڦ",
  "ﭯ": "ڦ",
  "ﭮ": "ڦ",
  "𞸒": "ق",
  "𞸲": "ق",
  "𞹒": "ق",
  "𞹲": "ق",
  "𞺒": "ق",
  "𞺲": "ق",
  "ﻗ": "ق",
  "ﻘ": "ق",
  "ﻖ": "ق",
  "ﻕ": "ق",
  "ﳂ": "قح",
  "ﰳ": "قح",
  "ﷱ": "قلى",
  "ﳃ": "قم",
  "ﰴ": "قم",
  "ﶴ": "قمح",
  "ﵾ": "قمح",
  "ﵿ": "قمم",
  "ﶲ": "قمى",
  "ﱾ": "قى",
  "ﰵ": "قى",
  "ﱿ": "قى",
  "ﰶ": "قى",
  "𞸊": "ك",
  "𞸪": "ك",
  "𞹪": "ك",
  "ﻛ": "ك",
  "ﻜ": "ك",
  "ﻚ": "ك",
  "ﻙ": "ك",
  "ک": "ك",
  "ﮐ": "ك",
  "ﮑ": "ك",
  "ﮏ": "ك",
  "ﮎ": "ك",
  "ڪ": "ك",
  "ڭ": "كۛ",
  "ﯕ": "كۛ",
  "ﯖ": "كۛ",
  "ﯔ": "كۛ",
  "ﯓ": "كۛ",
  "ݣ": "كۛ",
  "ﲀ": "كl",
  "ﰷ": "كl",
  "ﳄ": "كج",
  "ﰸ": "كج",
  "ﳅ": "كح",
  "ﰹ": "كح",
  "ﳆ": "كخ",
  "ﰺ": "كخ",
  "ﳇ": "كل",
  "ﳫ": "كل",
  "ﲁ": "كل",
  "ﰻ": "كل",
  "ﳈ": "كم",
  "ﳬ": "كم",
  "ﲂ": "كم",
  "ﰼ": "كم",
  "ﷃ": "كمم",
  "ﶻ": "كمم",
  "ﶷ": "كمى",
  "ﲃ": "كى",
  "ﰽ": "كى",
  "ﲄ": "كى",
  "ﰾ": "كى",
  "ݢ": "ڬ",
  "ﮔ": "گ",
  "ﮕ": "گ",
  "ﮓ": "گ",
  "ﮒ": "گ",
  "ࢰ": "گ",
  "ڴ": "گۛ",
  "ﮜ": "ڱ",
  "ﮝ": "ڱ",
  "ﮛ": "ڱ",
  "ﮚ": "ڱ",
  "ﮘ": "ڳ",
  "ﮙ": "ڳ",
  "ﮗ": "ڳ",
  "ﮖ": "ڳ",
  "𞸋": "ل",
  "𞸫": "ل",
  "𞹋": "ل",
  "𞺋": "ل",
  "𞺫": "ل",
  "ﻟ": "ل",
  "ﻠ": "ل",
  "ﻞ": "ل",
  "ﻝ": "ل",
  "ڷ": "لۛ",
  "ڵ": "ل̆",
  "ﻼ": "لl",
  "ﻻ": "لl",
  "ﻺ": "لlٕ",
  "ﻹ": "لlٕ",
  "ﻸ": "لlٴ",
  "ﻷ": "لlٴ",
  "ﳍ": "لo",
  "ﻶ": "لآ",
  "ﻵ": "لآ",
  "ﳉ": "لج",
  "ﰿ": "لج",
  "ﶃ": "لجج",
  "ﶄ": "لجج",
  "ﶺ": "لجم",
  "ﶼ": "لجم",
  "ﶬ": "لجى",
  "ﳊ": "لح",
  "ﱀ": "لح",
  "ﶵ": "لحم",
  "ﶀ": "لحم",
  "ﶂ": "لحى",
  "ﶁ": "لحى",
  "ﳋ": "لخ",
  "ﱁ": "لخ",
  "ﶆ": "لخم",
  "ﶅ": "لخم",
  "ﳌ": "لم",
  "ﳭ": "لم",
  "ﲅ": "لم",
  "ﱂ": "لم",
  "ﶈ": "لمح",
  "ﶇ": "لمح",
  "ﶭ": "لمى",
  "ﲆ": "لى",
  "ﱃ": "لى",
  "ﲇ": "لى",
  "ﱄ": "لى",
  "𞸌": "م",
  "𞸬": "م",
  "𞹬": "م",
  "𞺌": "م",
  "𞺬": "م",
  "ﻣ": "م",
  "ﻤ": "م",
  "ﻢ": "م",
  "ﻡ": "م",
  "ࢧ": "مۛ",
  "۾": "م͈",
  "ﲈ": "مl",
  "ﳎ": "مج",
  "ﱅ": "مج",
  "ﶌ": "مجح",
  "ﶒ": "مجخ",
  "ﶍ": "مجم",
  "ﷀ": "مجى",
  "ﳏ": "مح",
  "ﱆ": "مح",
  "ﶉ": "محج",
  "ﶊ": "محم",
  "ﷴ": "محمد",
  "ﶋ": "محى",
  "ﳐ": "مخ",
  "ﱇ": "مخ",
  "ﶎ": "مخج",
  "ﶏ": "مخم",
  "ﶹ": "مخى",
  "ﳑ": "مم",
  "ﲉ": "مم",
  "ﱈ": "مم",
  "ﶱ": "ممى",
  "ﱉ": "مى",
  "ﱊ": "مى",
  "𞸍": "ن",
  "𞸭": "ن",
  "𞹍": "ن",
  "𞹭": "ن",
  "𞺍": "ن",
  "𞺭": "ن",
  "ﻧ": "ن",
  "ﻨ": "ن",
  "ﻦ": "ن",
  "ﻥ": "ن",
  "ݨ": "نؕ",
  "ݩ": "ن̆",
  "ﳖ": "نo",
  "ﳯ": "نo",
  "ﶸ": "نجح",
  "ﶽ": "نجح",
  "ﶘ": "نجم",
  "ﶗ": "نجم",
  "ﶙ": "نجى",
  "ﷇ": "نجى",
  "ﳓ": "نح",
  "ﱌ": "نح",
  "ﶕ": "نحم",
  "ﶖ": "نحى",
  "ﶳ": "نحى",
  "ﳔ": "نخ",
  "ﱍ": "نخ",
  "ﲊ": "نر",
  "ﲋ": "نز",
  "ﳕ": "نم",
  "ﳮ": "نم",
  "ﲌ": "نم",
  "ﱎ": "نم",
  "ﶛ": "نمى",
  "ﶚ": "نمى",
  "ﲍ": "نن",
  "ﲎ": "نى",
  "ﱏ": "نى",
  "ﲏ": "نى",
  "ﱐ": "نى",
  "ۂ": "ۀ",
  "ﮥ": "ۀ",
  "ﮤ": "ۀ",
  "𐋤": "و",
  "𞸅": "و",
  "𞺅": "و",
  "𞺥": "و",
  "ﻮ": "و",
  "ﻭ": "و",
  "ࢱ": "و",
  "ۋ": "وۛ",
  "ﯟ": "وۛ",
  "ﯞ": "وۛ",
  "ۇ": "و̓",
  "ﯘ": "و̓",
  "ﯗ": "و̓",
  "ۆ": "و̆",
  "ﯚ": "و̆",
  "ﯙ": "و̆",
  "ۉ": "و̂",
  "ﯣ": "و̂",
  "ﯢ": "و̂",
  "ۈ": "وٰ",
  "ﯜ": "وٰ",
  "ﯛ": "وٰ",
  "ؤ": "وٴ",
  "ﺆ": "وٴ",
  "ﺅ": "وٴ",
  "ٶ": "وٴ",
  "ٷ": "و̓ٴ",
  "ﯝ": "و̓ٴ",
  "ﷸ": "وسلم",
  "ﯡ": "ۅ",
  "ﯠ": "ۅ",
  "ٮ": "ى",
  "𞸜": "ى",
  "𞹼": "ى",
  "ں": "ى",
  "𞸝": "ى",
  "𞹝": "ى",
  "ﮟ": "ى",
  "ﮞ": "ى",
  "ࢽ": "ى",
  "ﯨ": "ى",
  "ﯩ": "ى",
  "ﻰ": "ى",
  "ﻯ": "ى",
  "ي": "ى",
  "𞸉": "ى",
  "𞸩": "ى",
  "𞹉": "ى",
  "𞹩": "ى",
  "𞺉": "ى",
  "𞺩": "ى",
  "ﻳ": "ى",
  "ﻴ": "ى",
  "ﻲ": "ى",
  "ﻱ": "ى",
  "ی": "ى",
  "ﯾ": "ى",
  "ﯿ": "ى",
  "ﯽ": "ى",
  "ﯼ": "ى",
  "ے": "ى",
  "ﮯ": "ى",
  "ﮮ": "ى",
  "ٹ": "ىؕ",
  "ﭨ": "ىؕ",
  "ﭩ": "ىؕ",
  "ﭧ": "ىؕ",
  "ﭦ": "ىؕ",
  "ڻ": "ىؕ",
  "ﮢ": "ىؕ",
  "ﮣ": "ىؕ",
  "ﮡ": "ىؕ",
  "ﮠ": "ىؕ",
  "پ": "ىۛ",
  "ﭘ": "ىۛ",
  "ﭙ": "ىۛ",
  "ﭗ": "ىۛ",
  "ﭖ": "ىۛ",
  "ث": "ىۛ",
  "𞸖": "ىۛ",
  "𞸶": "ىۛ",
  "𞹶": "ىۛ",
  "𞺖": "ىۛ",
  "𞺶": "ىۛ",
  "ﺛ": "ىۛ",
  "ﺜ": "ىۛ",
  "ﺚ": "ىۛ",
  "ﺙ": "ىۛ",
  "ڽ": "ىۛ",
  "ۑ": "ىۛ",
  "ؿ": "ىۛ",
  "ࢷ": "ىۛۢ",
  "ݖ": "ى̆",
  "ێ": "ى̆",
  "ࢺ": "ى̆̇",
  "ؽ": "ى̂",
  "ࢨ": "ىٔ",
  "ﲐ": "ىٰ",
  "ﱝ": "ىٰ",
  "ﳞ": "ىo",
  "ﳱ": "ىo",
  "ﳦ": "ىۛo",
  "ئ": "ىٴ",
  "ﺋ": "ىٴ",
  "ﺌ": "ىٴ",
  "ﺊ": "ىٴ",
  "ﺉ": "ىٴ",
  "ٸ": "ىٴ",
  "ﯫ": "ىٴl",
  "ﯪ": "ىٴl",
  "ﲛ": "ىٴo",
  "ﳠ": "ىٴo",
  "ﯭ": "ىٴo",
  "ﯬ": "ىٴo",
  "ﯸ": "ىٴٻ",
  "ﯷ": "ىٴٻ",
  "ﯶ": "ىٴٻ",
  "ﲗ": "ىٴج",
  "ﰀ": "ىٴج",
  "ﲘ": "ىٴح",
  "ﰁ": "ىٴح",
  "ﲙ": "ىٴخ",
  "ﱤ": "ىٴر",
  "ﱥ": "ىٴز",
  "ﲚ": "ىٴم",
  "ﳟ": "ىٴم",
  "ﱦ": "ىٴم",
  "ﰂ": "ىٴم",
  "ﱧ": "ىٴن",
  "ﯯ": "ىٴو",
  "ﯮ": "ىٴو",
  "ﯱ": "ىٴو̓",
  "ﯰ": "ىٴو̓",
  "ﯳ": "ىٴو̆",
  "ﯲ": "ىٴو̆",
  "ﯵ": "ىٴوٰ",
  "ﯴ": "ىٴوٰ",
  "ﯻ": "ىٴى",
  "ﯺ": "ىٴى",
  "ﱨ": "ىٴى",
  "ﯹ": "ىٴى",
  "ﰃ": "ىٴى",
  "ﱩ": "ىٴى",
  "ﰄ": "ىٴى",
  "ﳚ": "ىج",
  "ﱕ": "ىج",
  "ﰑ": "ىۛج",
  "ﶯ": "ىجى",
  "ﳛ": "ىح",
  "ﱖ": "ىح",
  "ﶮ": "ىحى",
  "ﳜ": "ىخ",
  "ﱗ": "ىخ",
  "ﲑ": "ىر",
  "ﱶ": "ىۛر",
  "ﲒ": "ىز",
  "ﱷ": "ىۛز",
  "ﳝ": "ىم",
  "ﳰ": "ىم",
  "ﲓ": "ىم",
  "ﱘ": "ىم",
  "ﲦ": "ىۛم",
  "ﳥ": "ىۛم",
  "ﱸ": "ىۛم",
  "ﰒ": "ىۛم",
  "ﶝ": "ىمم",
  "ﶜ": "ىمم",
  "ﶰ": "ىمى",
  "ﲔ": "ىن",
  "ﱹ": "ىۛن",
  "ﲕ": "ىى",
  "ﱙ": "ىى",
  "ﲖ": "ىى",
  "ﱚ": "ىى",
  "ﱺ": "ىۛى",
  "ﰓ": "ىۛى",
  "ﱻ": "ىۛى",
  "ﰔ": "ىۛى",
  "ﮱ": "ۓ",
  "ﮰ": "ۓ",
  "𐊸": "ⵀ",
  "⁞": "ⵂ",
  "⸽": "ⵂ",
  "⦙": "ⵂ",
  "︙": "ⵗ",
  "⁝": "ⵗ",
  "⋮": "ⵗ",
  "Մ": "ሆ",
  "Ռ": "ቡ",
  "Ի": "ኮ",
  "Պ": "ጣ",
  "आ": "अा",
  "ऒ": "अाॆ",
  "ओ": "अाे",
  "औ": "अाै",
  "ऄ": "अॆ",
  "ऑ": "अॉ",
  "ऍ": "एॅ",
  "ऎ": "एॆ",
  "ऐ": "एे",
  "ई": "र्इ",
  "ઽ": "ऽ",
  "𑇜": "ꣻ",
  "𑇋": "ऺ",
  "ુ": "ु",
  "ૂ": "ू",
  "ੋ": "ॆ",
  "੍": "्",
  "્": "्",
  "আ": "অা",
  "ৠ": "ঋৃ",
  "ৡ": "ঋৃ",
  "𑒒": "ঘ",
  "𑒔": "চ",
  "𑒖": "জ",
  "𑒘": "ঞ",
  "𑒙": "ট",
  "𑒛": "ড",
  "𑒪": "ণ",
  "𑒞": "ত",
  "𑒟": "থ",
  "𑒠": "দ",
  "𑒡": "ধ",
  "𑒢": "ন",
  "𑒣": "প",
  "𑒩": "ব",
  "𑒧": "ম",
  "𑒨": "য",
  "𑒫": "র",
  "𑒝": "ল",
  "𑒭": "ষ",
  "𑒮": "স",
  "𑓄": "ঽ",
  "𑒰": "া",
  "𑒱": "ি",
  "𑒹": "ে",
  "𑒼": "ো",
  "𑒾": "ৌ",
  "𑓂": "্",
  "𑒽": "ৗ",
  "ਉ": "ੳੁ",
  "ਊ": "ੳੂ",
  "ਆ": "ਅਾ",
  "ਐ": "ਅੈ",
  "ਔ": "ਅੌ",
  "ਇ": "ੲਿ",
  "ਈ": "ੲੀ",
  "ਏ": "ੲੇ",
  "આ": "અા",
  "ઑ": "અાૅ",
  "ઓ": "અાે",
  "ઔ": "અાૈ",
  "ઍ": "અૅ",
  "એ": "અે",
  "ઐ": "અૈ",
  "ଆ": "ଅା",
  "௮": "அ",
  "ர": "ஈ",
  "ா": "ஈ",
  "௫": "ஈு",
  "௨": "உ",
  "ഉ": "உ",
  "ஊ": "உள",
  "ഊ": "உൗ",
  "௭": "எ",
  "௷": "எவ",
  "ஜ": "ஐ",
  "ജ": "ஐ",
  "௧": "க",
  "௪": "ச",
  "௬": "சு",
  "௲": "சூ",
  "ഺ": "டி",
  "ണ": "ண",
  "௺": "நீ",
  "௴": "மீ",
  "௰": "ய",
  "ഴ": "ழ",
  "ௗ": "ள",
  "ை": "ன",
  "ശ": "ஶ",
  "௸": "ஷ",
  "ി": "ி",
  "ീ": "ி",
  "ொ": "ெஈ",
  "ௌ": "ெள",
  "ோ": "ேஈ",
  "ಅ": "అ",
  "ಆ": "ఆ",
  "ಇ": "ఇ",
  "ౠ": "ఋా",
  "ౡ": "ఌా",
  "ಒ": "ఒ",
  "ఔ": "ఒౌ",
  "ಔ": "ఒౌ",
  "ఓ": "ఒౕ",
  "ಓ": "ఒౕ",
  "ಜ": "జ",
  "ಞ": "ఞ",
  "ఢ": "డ̣",
  "ಣ": "ణ",
  "థ": "ధּ",
  "భ": "బ̣",
  "ಯ": "య",
  "ఠ": "రּ",
  "ಱ": "ఱ",
  "ಲ": "ల",
  "ష": "వ̣",
  "హ": "వా",
  "మ": "వు",
  "ూ": "ుా",
  "ౄ": "ృా",
  "ೡ": "ಌಾ",
  "ഈ": "ഇൗ",
  "ഐ": "എെ",
  "ഓ": "ഒാ",
  "ഔ": "ഒൗ",
  "ൡ": "ഞ",
  "൫": "ദ്ര",
  "൹": "നു",
  "ഌ": "നു",
  "ങ": "നു",
  "൯": "ന്",
  "ൻ": "ന്",
  "൬": "ന്ന",
  "൚": "ന്മ",
  "റ": "ര",
  "൪": "ര്",
  "ർ": "ര്",
  "൮": "വ്ര",
  "൶": "ഹ്മ",
  "ൂ": "ു",
  "ൃ": "ു",
  "ൈ": "െെ",
  "෪": "ජ",
  "෫": "ද",
  "𑐓": "𑐴𑑂𑐒",
  "𑐙": "𑐴𑑂𑐘",
  "𑐤": "𑐴𑑂𑐣",
  "𑐪": "𑐴𑑂𑐩",
  "𑐭": "𑐴𑑂𑐬",
  "𑐯": "𑐴𑑂𑐮",
  "𑗘": "𑖂",
  "𑗙": "𑖂",
  "𑗚": "𑖃",
  "𑗛": "𑖄",
  "𑗜": "𑖲",
  "𑗝": "𑖳",
  "ฃ": "ข",
  "ด": "ค",
  "ต": "ค",
  "ม": "ฆ",
  "ຈ": "จ",
  "ซ": "ช",
  "ฏ": "ฎ",
  "ท": "ฑ",
  "ບ": "บ",
  "ປ": "ป",
  "ຝ": "ฝ",
  "ພ": "พ",
  "ຟ": "ฟ",
  "ฦ": "ภ",
  "ຍ": "ย",
  "។": "ฯ",
  "ๅ": "า",
  "ำ": "̊า",
  "ិ": "ิ",
  "ី": "ี",
  "ឹ": "ึ",
  "ឺ": "ื",
  "ຸ": "ุ",
  "ູ": "ู",
  "แ": "เเ",
  "ໜ": "ຫນ",
  "ໝ": "ຫມ",
  "ຳ": "̊າ",
  "༂": "འུྂཿ",
  "༃": "འུྂ༔",
  "ཪ": "ར",
  "ༀ": "ཨོཾ",
  "ཷ": "ྲཱྀ",
  "ཹ": "ླཱྀ",
  "𑲲": "𑲪",
  "ႁ": "ဂှ",
  "က": "ဂာ",
  "ၰ": "ဃှ",
  "ၦ": "ပှ",
  "ဟ": "ပာ",
  "ၯ": "ပာှ",
  "ၾ": "ၽှ",
  "ဩ": "သြ",
  "ဪ": "သြော်",
  "႞": "ႃ̊",
  "ឣ": "អ",
  "᧐": "ᦞ",
  "᧑": "ᦱ",
  "᪀": "ᩅ",
  "᪐": "ᩅ",
  "꩓": "ꨁ",
  "꩖": "ꨣ",
  "᭒": "ᬍ",
  "᭓": "ᬑ",
  "᭘": "ᬨ",
  "ꦣ": "ꦝ",
  "ᢖ": "ᡜ",
  "ᡕ": "ᠵ",
  "ῶ": "Ꮿ",
  "ᐍ": "ᐁ·",
  "ᐫ": "ᐁᐠ",
  "ᐑ": "ᐄ·",
  "ᐓ": "ᐅ·",
  "ᐭ": "ᐅᐠ",
  "ᐕ": "ᐆ·",
  "ᐘ": "ᐊ·",
  "ᐮ": "ᐊᐠ",
  "ᐚ": "ᐋ·",
  "ᣝ": "ᐞᣟ",
  "ᓑ": "ᐡ",
  "ᕀ": "ᐩ",
  "ᐿ": "ᐲ·",
  "ᑃ": "ᐴ·",
  "⍩": "ᐵ",
  "ᑇ": "ᐹ·",
  "ᑜ": "ᑏ·",
  "⸧": "ᑐ",
  "⊃": "ᑐ",
  "ᑞ": "ᑐ·",
  "ᑩ": "ᑐ'",
  "⟉": "ᑐ/",
  "⫗": "ᑐᑕ",
  "ᑠ": "ᑑ·",
  "⸦": "ᑕ",
  "⊂": "ᑕ",
  "ᑢ": "ᑕ·",
  "ᑪ": "ᑕ'",
  "ᑤ": "ᑖ·",
  "ᑵ": "ᑫ·",
  "ᒅ": "ᑫ'",
  "ᑹ": "ᑮ·",
  "ᑽ": "ᑰ·",
  "ᘃ": "ᒉ",
  "ᒓ": "ᒉ·",
  "ᒕ": "ᒋ·",
  "ᒗ": "ᒌ·",
  "ᒛ": "ᒎ·",
  "ᘂ": "ᒐ",
  "ᒝ": "ᒐ·",
  "ᒟ": "ᒑ·",
  "ᒭ": "ᒣ·",
  "ᒱ": "ᒦ·",
  "ᒳ": "ᒧ·",
  "ᒵ": "ᒨ·",
  "ᒹ": "ᒫ·",
  "ᓊ": "ᓀ·",
  "ᣇ": "ᓂ·",
  "ᣉ": "ᓃ·",
  "ᣋ": "ᓄ·",
  "ᣍ": "ᓅ·",
  "ᓌ": "ᓇ·",
  "ᓎ": "ᓈ·",
  "ᘄ": "ᓓ",
  "ᓝ": "ᓓ·",
  "ᓟ": "ᓕ·",
  "ᓡ": "ᓖ·",
  "ᓣ": "ᓗ·",
  "ᓥ": "ᓘ·",
  "ᘇ": "ᓚ",
  "ᓧ": "ᓚ·",
  "ᓩ": "ᓛ·",
  "ᓷ": "ᓭ·",
  "ᓹ": "ᓯ·",
  "ᓻ": "ᓰ·",
  "ᓽ": "ᓱ·",
  "ᓿ": "ᓲ·",
  "ᔁ": "ᓴ·",
  "ᔃ": "ᓵ·",
  "ᔌ": "ᔋ<",
  "ᔎ": "ᔋb",
  "ᔍ": "ᔋᑕ",
  "ᔏ": "ᔋᒐ",
  "ᔘ": "ᔐ·",
  "ᔚ": "ᔑ·",
  "ᔜ": "ᔒ·",
  "ᔞ": "ᔓ·",
  "ᔠ": "ᔔ·",
  "ᔢ": "ᔕ·",
  "ᔤ": "ᔖ·",
  "ᔲ": "ᔨ·",
  "ᔴ": "ᔩ·",
  "ᔶ": "ᔪ·",
  "ᔸ": "ᔫ·",
  "ᔺ": "ᔭ·",
  "ᔼ": "ᔮ·",
  "ᘢ": "ᕃ",
  "ᣠ": "ᕃ·",
  "ᘣ": "ᕆ",
  "ᘤ": "ᕊ",
  "ᕏ": "ᕌ·",
  "ᖃ": "ᕐb",
  "ᖄ": "ᕐḃ",
  "ᖁ": "ᕐd",
  "ᕿ": "ᕐP",
  "ᙯ": "ᕐᑫ",
  "ᕾ": "ᕐᑬ",
  "ᖀ": "ᕐᑮ",
  "ᖂ": "ᕐᑰ",
  "ᖅ": "ᕐᒃ",
  "ᕜ": "ᕚ·",
  "ᣣ": "ᕞ·",
  "ᣤ": "ᕦ·",
  "ᕩ": "ᕧ·",
  "ᣥ": "ᕫ·",
  "ᣨ": "ᖆ·",
  "ᖑ": "ᖕJ",
  "ᙰ": "ᖕᒉ",
  "ᖎ": "ᖕᒊ",
  "ᖏ": "ᖕᒋ",
  "ᖐ": "ᖕᒌ",
  "ᖒ": "ᖕᒎ",
  "ᖓ": "ᖕᒐ",
  "ᖔ": "ᖕᒑ",
  "ᙳ": "ᖖJ",
  "ᙱ": "ᖖᒋ",
  "ᙲ": "ᖖᒌ",
  "ᙴ": "ᖖᒎ",
  "ᙵ": "ᖖᒐ",
  "ᙶ": "ᖖᒑ",
  "ᣪ": "ᖗ·",
  "ᙷ": "ᖧ·",
  "ᙸ": "ᖨ·",
  "ᙹ": "ᖩ·",
  "ᙺ": "ᖪ·",
  "ᙻ": "ᖫ·",
  "ᙼ": "ᖬ·",
  "ᙽ": "ᖭ·",
  "⪫": "ᗒ",
  "⪪": "ᗕ",
  "ꓷ": "ᗡ",
  "ᣰ": "ᗴ·",
  "ᣲ": "ᘛ·",
  "ᶻ": "ᙆ",
  "ꓭ": "ᙠ",
  "ᶺ": "ᣔ",
  "ᴾ": "ᣖ",
  "ᣜ": "ᣟᐞ",
  "ˡ": "ᣳ",
  "ʳ": "ᣴ",
  "ˢ": "ᣵ",
  "ᣛ": "ᣵ",
  "ꚰ": "ᚹ",
  "ᛡ": "ᚼ",
  "⍿": "ᚽ",
  "ᛂ": "ᚽ",
  "𝈿": "ᛋ",
  "↑": "ᛏ",
  "↿": "ᛐ",
  "⥮": "ᛐ⇂",
  "⥣": "ᛐᛚ",
  "ⵣ": "ᛯ",
  "↾": "ᛚ",
  "⨡": "ᛚ",
  "⋄": "ᛜ",
  "◇": "ᛜ",
  "◊": "ᛜ",
  "♢": "ᛜ",
  "🝔": "ᛜ",
  "𑢷": "ᛜ",
  "𐊔": "ᛜ",
  "⍚": "ᛜ̲",
  "⋈": "ᛞ",
  "⨝": "ᛞ",
  "𐓐": "ᛦ",
  "↕": "ᛨ",
  "𐳼": "𐲂",
  "𐳺": "𐲥",
  "ㄱ": "ᄀ",
  "ᆨ": "ᄀ",
  "ᄁ": "ᄀᄀ",
  "ㄲ": "ᄀᄀ",
  "ᆩ": "ᄀᄀ",
  "ᇺ": "ᄀᄂ",
  "ᅚ": "ᄀᄃ",
  "ᇃ": "ᄀᄅ",
  "ᇻ": "ᄀᄇ",
  "ᆪ": "ᄀᄉ",
  "ㄳ": "ᄀᄉ",
  "ᇄ": "ᄀᄉᄀ",
  "ᇼ": "ᄀᄎ",
  "ᇽ": "ᄀᄏ",
  "ᇾ": "ᄀᄒ",
  "ㄴ": "ᄂ",
  "ᆫ": "ᄂ",
  "ᄓ": "ᄂᄀ",
  "ᇅ": "ᄂᄀ",
  "ᄔ": "ᄂᄂ",
  "ㅥ": "ᄂᄂ",
  "ᇿ": "ᄂᄂ",
  "ᄕ": "ᄂᄃ",
  "ㅦ": "ᄂᄃ",
  "ᇆ": "ᄂᄃ",
  "ퟋ": "ᄂᄅ",
  "ᄖ": "ᄂᄇ",
  "ᅛ": "ᄂᄉ",
  "ᇇ": "ᄂᄉ",
  "ㅧ": "ᄂᄉ",
  "ᅜ": "ᄂᄌ",
  "ᆬ": "ᄂᄌ",
  "ㄵ": "ᄂᄌ",
  "ퟌ": "ᄂᄎ",
  "ᇉ": "ᄂᄐ",
  "ᅝ": "ᄂᄒ",
  "ᆭ": "ᄂᄒ",
  "ㄶ": "ᄂᄒ",
  "ᇈ": "ᄂᅀ",
  "ㅨ": "ᄂᅀ",
  "ㄷ": "ᄃ",
  "ᆮ": "ᄃ",
  "ᄗ": "ᄃᄀ",
  "ᇊ": "ᄃᄀ",
  "ᄄ": "ᄃᄃ",
  "ㄸ": "ᄃᄃ",
  "ퟍ": "ᄃᄃ",
  "ퟎ": "ᄃᄃᄇ",
  "ᅞ": "ᄃᄅ",
  "ᇋ": "ᄃᄅ",
  "ꥠ": "ᄃᄆ",
  "ꥡ": "ᄃᄇ",
  "ퟏ": "ᄃᄇ",
  "ꥢ": "ᄃᄉ",
  "ퟐ": "ᄃᄉ",
  "ퟑ": "ᄃᄉᄀ",
  "ꥣ": "ᄃᄌ",
  "ퟒ": "ᄃᄌ",
  "ퟓ": "ᄃᄎ",
  "ퟔ": "ᄃᄐ",
  "ㄹ": "ᄅ",
  "ᆯ": "ᄅ",
  "ꥤ": "ᄅᄀ",
  "ᆰ": "ᄅᄀ",
  "ㄺ": "ᄅᄀ",
  "ꥥ": "ᄅᄀᄀ",
  "ퟕ": "ᄅᄀᄀ",
  "ᇌ": "ᄅᄀᄉ",
  "ㅩ": "ᄅᄀᄉ",
  "ퟖ": "ᄅᄀᄒ",
  "ᄘ": "ᄅᄂ",
  "ᇍ": "ᄅᄂ",
  "ꥦ": "ᄅᄃ",
  "ᇎ": "ᄅᄃ",
  "ㅪ": "ᄅᄃ",
  "ꥧ": "ᄅᄃᄃ",
  "ᇏ": "ᄅᄃᄒ",
  "ᄙ": "ᄅᄅ",
  "ᇐ": "ᄅᄅ",
  "ퟗ": "ᄅᄅᄏ",
  "ꥨ": "ᄅᄆ",
  "ᆱ": "ᄅᄆ",
  "ㄻ": "ᄅᄆ",
  "ᇑ": "ᄅᄆᄀ",
  "ᇒ": "ᄅᄆᄉ",
  "ퟘ": "ᄅᄆᄒ",
  "ꥩ": "ᄅᄇ",
  "ᆲ": "ᄅᄇ",
  "ㄼ": "ᄅᄇ",
  "ퟙ": "ᄅᄇᄃ",
  "ꥪ": "ᄅᄇᄇ",
  "ᇓ": "ᄅᄇᄉ",
  "ㅫ": "ᄅᄇᄉ",
  "ꥫ": "ᄅᄇᄋ",
  "ᇕ": "ᄅᄇᄋ",
  "ퟚ": "ᄅᄇᄑ",
  "ᇔ": "ᄅᄇᄒ",
  "ꥬ": "ᄅᄉ",
  "ᆳ": "ᄅᄉ",
  "ㄽ": "ᄅᄉ",
  "ᇖ": "ᄅᄉᄉ",
  "ᄛ": "ᄅᄋ",
  "ퟝ": "ᄅᄋ",
  "ꥭ": "ᄅᄌ",
  "ꥮ": "ᄅᄏ",
  "ᇘ": "ᄅᄏ",
  "ᆴ": "ᄅᄐ",
  "ㄾ": "ᄅᄐ",
  "ᆵ": "ᄅᄑ",
  "ㄿ": "ᄅᄑ",
  "ᄚ": "ᄅᄒ",
  "ㅀ": "ᄅᄒ",
  "ᄻ": "ᄅᄒ",
  "ᆶ": "ᄅᄒ",
  "ퟲ": "ᄅᄒ",
  "ᇗ": "ᄅᅀ",
  "ㅬ": "ᄅᅀ",
  "ퟛ": "ᄅᅌ",
  "ᇙ": "ᄅᅙ",
  "ㅭ": "ᄅᅙ",
  "ퟜ": "ᄅᅙᄒ",
  "ㅁ": "ᄆ",
  "ᆷ": "ᄆ",
  "ꥯ": "ᄆᄀ",
  "ᇚ": "ᄆᄀ",
  "ퟞ": "ᄆᄂ",
  "ퟟ": "ᄆᄂᄂ",
  "ꥰ": "ᄆᄃ",
  "ᇛ": "ᄆᄅ",
  "ퟠ": "ᄆᄆ",
  "ᄜ": "ᄆᄇ",
  "ㅮ": "ᄆᄇ",
  "ᇜ": "ᄆᄇ",
  "ퟡ": "ᄆᄇᄉ",
  "ꥱ": "ᄆᄉ",
  "ᇝ": "ᄆᄉ",
  "ㅯ": "ᄆᄉ",
  "ᇞ": "ᄆᄉᄉ",
  "ᄝ": "ᄆᄋ",
  "ㅱ": "ᄆᄋ",
  "ᇢ": "ᄆᄋ",
  "ퟢ": "ᄆᄌ",
  "ᇠ": "ᄆᄎ",
  "ᇡ": "ᄆᄒ",
  "ᇟ": "ᄆᅀ",
  "ㅰ": "ᄆᅀ",
  "ㅂ": "ᄇ",
  "ᆸ": "ᄇ",
  "ᄞ": "ᄇᄀ",
  "ㅲ": "ᄇᄀ",
  "ᄟ": "ᄇᄂ",
  "ᄠ": "ᄇᄃ",
  "ㅳ": "ᄇᄃ",
  "ퟣ": "ᄇᄃ",
  "ᇣ": "ᄇᄅ",
  "ퟤ": "ᄇᄅᄑ",
  "ퟥ": "ᄇᄆ",
  "ᄈ": "ᄇᄇ",
  "ㅃ": "ᄇᄇ",
  "ퟦ": "ᄇᄇ",
  "ᄬ": "ᄇᄇᄋ",
  "ㅹ": "ᄇᄇᄋ",
  "ᄡ": "ᄇᄉ",
  "ㅄ": "ᄇᄉ",
  "ᆹ": "ᄇᄉ",
  "ᄢ": "ᄇᄉᄀ",
  "ㅴ": "ᄇᄉᄀ",
  "ᄣ": "ᄇᄉᄃ",
  "ㅵ": "ᄇᄉᄃ",
  "ퟧ": "ᄇᄉᄃ",
  "ᄤ": "ᄇᄉᄇ",
  "ᄥ": "ᄇᄉᄉ",
  "ᄦ": "ᄇᄉᄌ",
  "ꥲ": "ᄇᄉᄐ",
  "ᄫ": "ᄇᄋ",
  "ㅸ": "ᄇᄋ",
  "ᇦ": "ᄇᄋ",
  "ᄧ": "ᄇᄌ",
  "ㅶ": "ᄇᄌ",
  "ퟨ": "ᄇᄌ",
  "ᄨ": "ᄇᄎ",
  "ퟩ": "ᄇᄎ",
  "ꥳ": "ᄇᄏ",
  "ᄩ": "ᄇᄐ",
  "ㅷ": "ᄇᄐ",
  "ᄪ": "ᄇᄑ",
  "ᇤ": "ᄇᄑ",
  "ꥴ": "ᄇᄒ",
  "ᇥ": "ᄇᄒ",
  "ㅅ": "ᄉ",
  "ᆺ": "ᄉ",
  "ᄭ": "ᄉᄀ",
  "ㅺ": "ᄉᄀ",
  "ᇧ": "ᄉᄀ",
  "ᄮ": "ᄉᄂ",
  "ㅻ": "ᄉᄂ",
  "ᄯ": "ᄉᄃ",
  "ㅼ": "ᄉᄃ",
  "ᇨ": "ᄉᄃ",
  "ᄰ": "ᄉᄅ",
  "ᇩ": "ᄉᄅ",
  "ᄱ": "ᄉᄆ",
  "ퟪ": "ᄉᄆ",
  "ᄲ": "ᄉᄇ",
  "ㅽ": "ᄉᄇ",
  "ᇪ": "ᄉᄇ",
  "ᄳ": "ᄉᄇᄀ",
  "ퟫ": "ᄉᄇᄋ",
  "ᄊ": "ᄉᄉ",
  "ㅆ": "ᄉᄉ",
  "ᆻ": "ᄉᄉ",
  "ퟬ": "ᄉᄉᄀ",
  "ퟭ": "ᄉᄉᄃ",
  "ꥵ": "ᄉᄉᄇ",
  "ᄴ": "ᄉᄉᄉ",
  "ᄵ": "ᄉᄋ",
  "ᄶ": "ᄉᄌ",
  "ㅾ": "ᄉᄌ",
  "ퟯ": "ᄉᄌ",
  "ᄷ": "ᄉᄎ",
  "ퟰ": "ᄉᄎ",
  "ᄸ": "ᄉᄏ",
  "ᄹ": "ᄉᄐ",
  "ퟱ": "ᄉᄐ",
  "ᄺ": "ᄉᄑ",
  "ퟮ": "ᄉᅀ",
  "ㅇ": "ᄋ",
  "ᆼ": "ᄋ",
  "ᅁ": "ᄋᄀ",
  "ᇬ": "ᄋᄀ",
  "ᇭ": "ᄋᄀᄀ",
  "ᅂ": "ᄋᄃ",
  "ꥶ": "ᄋᄅ",
  "ᅃ": "ᄋᄆ",
  "ᅄ": "ᄋᄇ",
  "ᅅ": "ᄋᄉ",
  "ᇱ": "ᄋᄉ",
  "ㆂ": "ᄋᄉ",
  "ᅇ": "ᄋᄋ",
  "ㆀ": "ᄋᄋ",
  "ᇮ": "ᄋᄋ",
  "ᅈ": "ᄋᄌ",
  "ᅉ": "ᄋᄎ",
  "ᇯ": "ᄋᄏ",
  "ᅊ": "ᄋᄐ",
  "ᅋ": "ᄋᄑ",
  "ꥷ": "ᄋᄒ",
  "ᅆ": "ᄋᅀ",
  "ᇲ": "ᄋᅀ",
  "ㆃ": "ᄋᅀ",
  "ㅈ": "ᄌ",
  "ᆽ": "ᄌ",
  "ퟷ": "ᄌᄇ",
  "ퟸ": "ᄌᄇᄇ",
  "ᅍ": "ᄌᄋ",
  "ᄍ": "ᄌᄌ",
  "ㅉ": "ᄌᄌ",
  "ퟹ": "ᄌᄌ",
  "ꥸ": "ᄌᄌᄒ",
  "ㅊ": "ᄎ",
  "ᆾ": "ᄎ",
  "ᅒ": "ᄎᄏ",
  "ᅓ": "ᄎᄒ",
  "ㅋ": "ᄏ",
  "ᆿ": "ᄏ",
  "ㅌ": "ᄐ",
  "ᇀ": "ᄐ",
  "ꥹ": "ᄐᄐ",
  "ㅍ": "ᄑ",
  "ᇁ": "ᄑ",
  "ᅖ": "ᄑᄇ",
  "ᇳ": "ᄑᄇ",
  "ퟺ": "ᄑᄉ",
  "ᅗ": "ᄑᄋ",
  "ㆄ": "ᄑᄋ",
  "ᇴ": "ᄑᄋ",
  "ퟻ": "ᄑᄐ",
  "ꥺ": "ᄑᄒ",
  "ㅎ": "ᄒ",
  "ᇂ": "ᄒ",
  "ᇵ": "ᄒᄂ",
  "ᇶ": "ᄒᄅ",
  "ᇷ": "ᄒᄆ",
  "ᇸ": "ᄒᄇ",
  "ꥻ": "ᄒᄉ",
  "ᅘ": "ᄒᄒ",
  "ㆅ": "ᄒᄒ",
  "ᄽ": "ᄼᄼ",
  "ᄿ": "ᄾᄾ",
  "ㅿ": "ᅀ",
  "ᇫ": "ᅀ",
  "ퟳ": "ᅀᄇ",
  "ퟴ": "ᅀᄇᄋ",
  "ㆁ": "ᅌ",
  "ᇰ": "ᅌ",
  "ퟵ": "ᅌᄆ",
  "ퟶ": "ᅌᄒ",
  "ᅏ": "ᅎᅎ",
  "ᅑ": "ᅐᅐ",
  "ㆆ": "ᅙ",
  "ᇹ": "ᅙ",
  "ꥼ": "ᅙᅙ",
  "ㅤ": "ᅠ",
  "ㅏ": "ᅡ",
  "ᆣ": "ᅡー",
  "ᅶ": "ᅡᅩ",
  "ᅷ": "ᅡᅮ",
  "ᅢ": "ᅡ丨",
  "ㅐ": "ᅡ丨",
  "ㅑ": "ᅣ",
  "ᅸ": "ᅣᅩ",
  "ᅹ": "ᅣᅭ",
  "ᆤ": "ᅣᅮ",
  "ᅤ": "ᅣ丨",
  "ㅒ": "ᅣ丨",
  "ㅓ": "ᅥ",
  "ᅼ": "ᅥー",
  "ᅺ": "ᅥᅩ",
  "ᅻ": "ᅥᅮ",
  "ᅦ": "ᅥ丨",
  "ㅔ": "ᅥ丨",
  "ㅕ": "ᅧ",
  "ᆥ": "ᅧᅣ",
  "ᅽ": "ᅧᅩ",
  "ᅾ": "ᅧᅮ",
  "ᅨ": "ᅧ丨",
  "ㅖ": "ᅧ丨",
  "ㅗ": "ᅩ",
  "ᅪ": "ᅩᅡ",
  "ㅘ": "ᅩᅡ",
  "ᅫ": "ᅩᅡ丨",
  "ㅙ": "ᅩᅡ丨",
  "ᆦ": "ᅩᅣ",
  "ᆧ": "ᅩᅣ丨",
  "ᅿ": "ᅩᅥ",
  "ᆀ": "ᅩᅥ丨",
  "ힰ": "ᅩᅧ",
  "ᆁ": "ᅩᅧ丨",
  "ᆂ": "ᅩᅩ",
  "ힱ": "ᅩᅩ丨",
  "ᆃ": "ᅩᅮ",
  "ᅬ": "ᅩ丨",
  "ㅚ": "ᅩ丨",
  "ㅛ": "ᅭ",
  "ힲ": "ᅭᅡ",
  "ힳ": "ᅭᅡ丨",
  "ᆄ": "ᅭᅣ",
  "ㆇ": "ᅭᅣ",
  "ᆆ": "ᅭᅣ",
  "ᆅ": "ᅭᅣ丨",
  "ㆈ": "ᅭᅣ丨",
  "ힴ": "ᅭᅥ",
  "ᆇ": "ᅭᅩ",
  "ᆈ": "ᅭ丨",
  "ㆉ": "ᅭ丨",
  "ㅜ": "ᅮ",
  "ᆉ": "ᅮᅡ",
  "ᆊ": "ᅮᅡ丨",
  "ᅯ": "ᅮᅥ",
  "ㅝ": "ᅮᅥ",
  "ᆋ": "ᅮᅥー",
  "ᅰ": "ᅮᅥ丨",
  "ㅞ": "ᅮᅥ丨",
  "ힵ": "ᅮᅧ",
  "ᆌ": "ᅮᅧ丨",
  "ᆍ": "ᅮᅮ",
  "ᅱ": "ᅮ丨",
  "ㅟ": "ᅮ丨",
  "ힶ": "ᅮ丨丨",
  "ㅠ": "ᅲ",
  "ᆎ": "ᅲᅡ",
  "ힷ": "ᅲᅡ丨",
  "ᆏ": "ᅲᅥ",
  "ᆐ": "ᅲᅥ丨",
  "ᆑ": "ᅲᅧ",
  "ㆊ": "ᅲᅧ",
  "ᆒ": "ᅲᅧ丨",
  "ㆋ": "ᅲᅧ丨",
  "ힸ": "ᅲᅩ",
  "ᆓ": "ᅲᅮ",
  "ᆔ": "ᅲ丨",
  "ㆌ": "ᅲ丨",
  "ㆍ": "ᆞ",
  "ퟅ": "ᆞᅡ",
  "ᆟ": "ᆞᅥ",
  "ퟆ": "ᆞᅥ丨",
  "ᆠ": "ᆞᅮ",
  "ᆢ": "ᆞᆞ",
  "ᆡ": "ᆞ丨",
  "ㆎ": "ᆞ丨",
  "ヘ": "へ",
  "⍁": "〼",
  "⧄": "〼",
  "꒞": "ꁊ",
  "꒬": "ꁐ",
  "꒜": "ꃀ",
  "꒨": "ꄲ",
  "꒿": "ꉙ",
  "꒾": "ꊱ",
  "꒔": "ꋍ",
  "꓀": "ꎫ",
  "꓂": "ꎵ",
  "꒺": "ꎿ",
  "꒰": "ꏂ",
  "꒧": "ꑘ",
  "⊥": "ꓕ",
  "⟂": "ꓕ",
  "𝈜": "ꓕ",
  "Ʇ": "ꓕ",
  "Ꞟ": "ꓤ",
  "⅁": "ꓨ",
  "⅂": "ꓶ",
  "𝈕": "ꓶ",
  "𝈫": "ꓶ",
  "𖼦": "ꓶ",
  "𐐑": "ꓶ",
  "⅃": "𖼀",
  "𑫦": "𑫥𑫯",
  "𑫨": "𑫥𑫥",
  "𑫩": "𑫥𑫥𑫯",
  "𑫪": "𑫥𑫥𑫰",
  "𑫧": "𑫥𑫰",
  "𑫴": "𑫳𑫯",
  "𑫶": "𑫳𑫳",
  "𑫷": "𑫳𑫳𑫯",
  "𑫸": "𑫳𑫳𑫰",
  "𑫵": "𑫳𑫰",
  "𑫬": "𑫫𑫯",
  "𑫭": "𑫫𑫫",
  "𑫮": "𑫫𑫫𑫯",
  "⊕": "𐊨",
  "⨁": "𐊨",
  "🜨": "𐊨",
  "Ꚛ": "𐊨",
  "▽": "𐊼",
  "𝈔": "𐊼",
  "🜄": "𐊼",
  "⧖": "𐋀",
  "ꞛ": "𐐺",
  "Ꞛ": "𐐒",
  "𐒠": "𐒆",
  "𐏑": "𐎂",
  "𐏓": "𐎓",
  "𒀸": "𐎚",
  "☥": "𐦞",
  "𓋹": "𐦞",
  "〹": "卄",
  "不": "不",
  "丽": "丽",
  "並": "並",
  "⎜": "丨",
  "⎟": "丨",
  "⎢": "丨",
  "⎥": "丨",
  "⎪": "丨",
  "⎮": "丨",
  "㇑": "丨",
  "ᅵ": "丨",
  "ㅣ": "丨",
  "⼁": "丨",
  "ᆜ": "丨ー",
  "ᆘ": "丨ᅡ",
  "ᆙ": "丨ᅣ",
  "ힽ": "丨ᅣᅩ",
  "ힾ": "丨ᅣ丨",
  "ힿ": "丨ᅧ",
  "ퟀ": "丨ᅧ丨",
  "ᆚ": "丨ᅩ",
  "ퟁ": "丨ᅩ丨",
  "ퟂ": "丨ᅭ",
  "ᆛ": "丨ᅮ",
  "ퟃ": "丨ᅲ",
  "ᆝ": "丨ᆞ",
  "ퟄ": "丨丨",
  "串": "串",
  "丸": "丸",
  "丹": "丹",
  "乁": "乁",
  "㇠": "乙",
  "⼄": "乙",
  "㇟": "乚",
  "⺃": "乚",
  "㇖": "乛",
  "⺂": "乛",
  "⻲": "亀",
  "亂": "亂",
  "㇚": "亅",
  "⼅": "亅",
  "了": "了",
  "ニ": "二",
  "⼆": "二",
  "𠄢": "𠄢",
  "⼇": "亠",
  "亮": "亮",
  "⼈": "人",
  "イ": "亻",
  "⺅": "亻",
  "什": "什",
  "仌": "仌",
  "令": "令",
  "你": "你",
  "倂": "併",
  "倂": "併",
  "侀": "侀",
  "來": "來",
  "例": "例",
  "侮": "侮",
  "侮": "侮",
  "侻": "侻",
  "便": "便",
  "值": "値",
  "倫": "倫",
  "偺": "偺",
  "備": "備",
  "像": "像",
  "僚": "僚",
  "僧": "僧",
  "僧": "僧",
  "㒞": "㒞",
  "⼉": "儿",
  "兀": "兀",
  "⺎": "兀",
  "充": "充",
  "免": "免",
  "免": "免",
  "兔": "兔",
  "兤": "兤",
  "⼊": "入",
  "內": "內",
  "全": "全",
  "兩": "兩",
  "ハ": "八",
  "⼋": "八",
  "六": "六",
  "具": "具",
  "𠔜": "𠔜",
  "𠔥": "𠔥",
  "冀": "冀",
  "㒹": "㒹",
  "⼌": "冂",
  "再": "再",
  "𠕋": "𠕋",
  "冒": "冒",
  "冕": "冕",
  "㒻": "㒻",
  "最": "最",
  "⼍": "冖",
  "冗": "冗",
  "冤": "冤",
  "⼎": "冫",
  "冬": "冬",
  "况": "况",
  "况": "况",
  "冷": "冷",
  "凉": "凉",
  "凌": "凌",
  "凜": "凜",
  "凞": "凞",
  "⼏": "几",
  "𠘺": "𠘺",
  "凵": "凵",
  "⼐": "凵",
  "⼑": "刀",
  "⺉": "刂",
  "刃": "刃",
  "切": "切",
  "切": "切",
  "列": "列",
  "利": "利",
  "㓟": "㓟",
  "刺": "刺",
  "刻": "刻",
  "剆": "剆",
  "割": "割",
  "剷": "剷",
  "劉": "劉",
  "𠠄": "𠠄",
  "カ": "力",
  "力": "力",
  "⼒": "力",
  "劣": "劣",
  "㔕": "㔕",
  "劳": "劳",
  "勇": "勇",
  "勇": "勇",
  "勉": "勉",
  "勉": "勉",
  "勒": "勒",
  "勞": "勞",
  "勤": "勤",
  "勤": "勤",
  "勵": "勵",
  "⼓": "勹",
  "勺": "勺",
  "勺": "勺",
  "包": "包",
  "匆": "匆",
  "𠣞": "𠣞",
  "⼔": "匕",
  "北": "北",
  "北": "北",
  "⼕": "匚",
  "⼖": "匸",
  "匿": "匿",
  "⼗": "十",
  "〸": "十",
  "〺": "卅",
  "卉": "卉",
  "࿖": "卍",
  "࿕": "卐",
  "卑": "卑",
  "卑": "卑",
  "博": "博",
  "ト": "卜",
  "⼘": "卜",
  "⼙": "卩",
  "⺋": "㔾",
  "即": "即",
  "卵": "卵",
  "卽": "卽",
  "卿": "卿",
  "卿": "卿",
  "卿": "卿",
  "⼚": "厂",
  "𠨬": "𠨬",
  "⼛": "厶",
  "參": "參",
  "⼜": "又",
  "及": "及",
  "叟": "叟",
  "𠭣": "𠭣",
  "ロ": "口",
  "⼝": "口",
  "囗": "口",
  "⼞": "口",
  "句": "句",
  "叫": "叫",
  "叱": "叱",
  "吆": "吆",
  "吏": "吏",
  "吝": "吝",
  "吸": "吸",
  "呂": "呂",
  "呈": "呈",
  "周": "周",
  "咞": "咞",
  "咢": "咢",
  "咽": "咽",
  "䎛": "㖈",
  "哶": "哶",
  "唐": "唐",
  "啓": "啓",
  "啟": "啓",
  "啕": "啕",
  "啣": "啣",
  "善": "善",
  "善": "善",
  "喇": "喇",
  "喙": "喙",
  "喙": "喙",
  "喝": "喝",
  "喝": "喝",
  "喫": "喫",
  "喳": "喳",
  "嗀": "嗀",
  "嗂": "嗂",
  "嗢": "嗢",
  "嘆": "嘆",
  "嘆": "嘆",
  "噑": "噑",
  "噴": "噴",
  "器": "器",
  "囹": "囹",
  "圖": "圖",
  "圗": "圗",
  "⼟": "土",
  "士": "土",
  "⼠": "土",
  "型": "型",
  "城": "城",
  "㦳": "㘽",
  "埴": "埴",
  "堍": "堍",
  "報": "報",
  "堲": "堲",
  "塀": "塀",
  "塚": "塚",
  "塚": "塚",
  "塞": "塞",
  "填": "塡",
  "壿": "墫",
  "墬": "墬",
  "墳": "墳",
  "壘": "壘",
  "壟": "壟",
  "𡓤": "𡓤",
  "壮": "壮",
  "売": "売",
  "壷": "壷",
  "⼡": "夂",
  "夆": "夆",
  "⼢": "夊",
  "タ": "夕",
  "⼣": "夕",
  "多": "多",
  "夢": "夢",
  "⼤": "大",
  "奄": "奄",
  "奈": "奈",
  "契": "契",
  "奔": "奔",
  "奢": "奢",
  "女": "女",
  "⼥": "女",
  "𡚨": "𡚨",
  "𡛪": "𡛪",
  "姘": "姘",
  "姬": "姬",
  "娛": "娛",
  "娧": "娧",
  "婢": "婢",
  "婦": "婦",
  "嬀": "媯",
  "㛮": "㛮",
  "㛼": "㛼",
  "媵": "媵",
  "嬈": "嬈",
  "嬨": "嬨",
  "嬾": "嬾",
  "嬾": "嬾",
  "⼦": "子",
  "⼧": "宀",
  "宅": "宅",
  "𡧈": "𡧈",
  "寃": "寃",
  "寘": "寘",
  "寧": "寧",
  "寧": "寧",
  "寧": "寧",
  "寮": "寮",
  "寳": "寳",
  "𡬘": "𡬘",
  "⼨": "寸",
  "寿": "寿",
  "将": "将",
  "⼩": "小",
  "尢": "尢",
  "⺐": "尢",
  "⼪": "尢",
  "⺏": "尣",
  "㞁": "㞁",
  "⼫": "尸",
  "尿": "尿",
  "屠": "屠",
  "屢": "屢",
  "層": "層",
  "履": "履",
  "屮": "屮",
  "屮": "屮",
  "⼬": "屮",
  "𡴋": "𡴋",
  "⼭": "山",
  "峀": "峀",
  "岍": "岍",
  "𡷤": "𡷤",
  "𡷦": "𡷦",
  "崙": "崙",
  "嵃": "嵃",
  "嵐": "嵐",
  "嵫": "嵫",
  "嵮": "嵮",
  "嵼": "嵼",
  "嶲": "嶲",
  "嶺": "嶺",
  "⼮": "巛",
  "巢": "巢",
  "エ": "工",
  "⼯": "工",
  "⼰": "己",
  "⺒": "巳",
  "㠯": "㠯",
  "巽": "巽",
  "⼱": "巾",
  "帲": "帡",
  "帨": "帨",
  "帽": "帽",
  "幩": "幩",
  "㡢": "㡢",
  "𢆃": "𢆃",
  "⼲": "干",
  "年": "年",
  "𢆟": "𢆟",
  "⺓": "幺",
  "⼳": "幺",
  "⼴": "广",
  "度": "度",
  "㡼": "㡼",
  "庰": "庰",
  "庳": "庳",
  "庶": "庶",
  "廊": "廊",
  "廊": "廊",
  "廉": "廉",
  "廒": "廒",
  "廓": "廓",
  "廙": "廙",
  "廬": "廬",
  "⼵": "廴",
  "廾": "廾",
  "⼶": "廾",
  "𢌱": "𢌱",
  "𢌱": "𢌱",
  "弄": "弄",
  "⼷": "弋",
  "⼸": "弓",
  "弢": "弢",
  "弢": "弢",
  "⼹": "彐",
  "⺔": "彑",
  "当": "当",
  "㣇": "㣇",
  "⼺": "彡",
  "形": "形",
  "彩": "彩",
  "彫": "彫",
  "⼻": "彳",
  "律": "律",
  "㣣": "㣣",
  "徚": "徚",
  "復": "復",
  "徭": "徭",
  "⼼": "心",
  "⺖": "忄",
  "⺗": "㣺",
  "忍": "忍",
  "志": "志",
  "念": "念",
  "忹": "忹",
  "怒": "怒",
  "怜": "怜",
  "恵": "恵",
  "㤜": "㤜",
  "㤺": "㤺",
  "悁": "悁",
  "悔": "悔",
  "悔": "悔",
  "惇": "惇",
  "惘": "惘",
  "惡": "惡",
  "𢛔": "𢛔",
  "愈": "愈",
  "慨": "慨",
  "慄": "慄",
  "慈": "慈",
  "慌": "慌",
  "慌": "慌",
  "慎": "慎",
  "慎": "慎",
  "慠": "慠",
  "慺": "慺",
  "憎": "憎",
  "憎": "憎",
  "憎": "憎",
  "憐": "憐",
  "憤": "憤",
  "憯": "憯",
  "憲": "憲",
  "𢡄": "𢡄",
  "𢡊": "𢡊",
  "懞": "懞",
  "懲": "懲",
  "懲": "懲",
  "懲": "懲",
  "懶": "懶",
  "懶": "懶",
  "戀": "戀",
  "⼽": "戈",
  "成": "成",
  "戛": "戛",
  "戮": "戮",
  "戴": "戴",
  "⼾": "戶",
  "戸": "戶",
  "⼿": "手",
  "⺘": "扌",
  "扝": "扝",
  "抱": "抱",
  "拉": "拉",
  "拏": "拏",
  "拓": "拓",
  "拔": "拔",
  "拼": "拼",
  "拾": "拾",
  "𢬌": "𢬌",
  "挽": "挽",
  "捐": "捐",
  "捨": "捨",
  "捻": "捻",
  "掃": "掃",
  "掠": "掠",
  "掩": "掩",
  "揄": "揄",
  "揤": "揤",
  "摒": "摒",
  "𢯱": "𢯱",
  "搜": "搜",
  "搢": "搢",
  "揅": "揅",
  "摩": "摩",
  "摷": "摷",
  "摾": "摾",
  "㨮": "㨮",
  "搉": "㩁",
  "撚": "撚",
  "撝": "撝",
  "擄": "擄",
  "㩬": "㩬",
  "⽀": "支",
  "⽁": "攴",
  "⺙": "攵",
  "敏": "敏",
  "敏": "敏",
  "敖": "敖",
  "敬": "敬",
  "數": "數",
  "𣀊": "𣀊",
  "⽂": "文",
  "⻫": "斉",
  "⽃": "斗",
  "料": "料",
  "⽄": "斤",
  "⽅": "方",
  "旅": "旅",
  "⽆": "无",
  "⺛": "旡",
  "既": "既",
  "旣": "旣",
  "⽇": "日",
  "易": "易",
  "曶": "㫚",
  "㫤": "㫤",
  "晉": "晉",
  "晩": "晚",
  "晴": "晴",
  "晴": "晴",
  "暑": "暑",
  "暑": "暑",
  "暈": "暈",
  "㬈": "㬈",
  "暜": "暜",
  "暴": "暴",
  "曆": "曆",
  "㬙": "㬙",
  "𣊸": "𣊸",
  "⽈": "曰",
  "更": "更",
  "書": "書",
  "⽉": "月",
  "𣍟": "𣍟",
  "肦": "朌",
  "胐": "朏",
  "胊": "朐",
  "脁": "朓",
  "胶": "㬵",
  "朗": "朗",
  "朗": "朗",
  "朗": "朗",
  "脧": "朘",
  "望": "望",
  "望": "望",
  "幐": "㬺",
  "䐠": "㬻",
  "𣎓": "𣎓",
  "膧": "朣",
  "𣎜": "𣎜",
  "⽊": "木",
  "李": "李",
  "杓": "杓",
  "杖": "杖",
  "杞": "杞",
  "𣏃": "𣏃",
  "柿": "杮",
  "杻": "杻",
  "枅": "枅",
  "林": "林",
  "㭉": "㭉",
  "𣏕": "𣏕",
  "柳": "柳",
  "柺": "柺",
  "栗": "栗",
  "栟": "栟",
  "桒": "桒",
  "𣑭": "𣑭",
  "梁": "梁",
  "梅": "梅",
  "梅": "梅",
  "梎": "梎",
  "梨": "梨",
  "椔": "椔",
  "楂": "楂",
  "㮝": "㮝",
  "㮝": "㮝",
  "槩": "㮣",
  "樧": "榝",
  "榣": "榣",
  "槪": "槪",
  "樂": "樂",
  "樂": "樂",
  "樂": "樂",
  "樓": "樓",
  "𣚣": "𣚣",
  "檨": "檨",
  "櫓": "櫓",
  "櫛": "櫛",
  "欄": "欄",
  "㰘": "㰘",
  "⽋": "欠",
  "次": "次",
  "𣢧": "𣢧",
  "歔": "歔",
  "㱎": "㱎",
  "⽌": "止",
  "⻭": "歯",
  "歲": "歲",
  "歷": "歷",
  "歹": "歹",
  "⽍": "歹",
  "⺞": "歺",
  "殟": "殟",
  "殮": "殮",
  "⽎": "殳",
  "殺": "殺",
  "殺": "殺",
  "殺": "殺",
  "殻": "殻",
  "𣪍": "𣪍",
  "⽏": "毋",
  "⺟": "母",
  "𣫺": "𣫺",
  "⽐": "比",
  "⽑": "毛",
  "⽒": "氏",
  "⺠": "民",
  "⽓": "气",
  "⽔": "水",
  "⺡": "氵",
  "⺢": "氺",
  "汎": "汎",
  "汧": "汧",
  "沈": "沈",
  "沿": "沿",
  "泌": "泌",
  "泍": "泍",
  "泥": "泥",
  "𣲼": "𣲼",
  "洛": "洛",
  "洞": "洞",
  "洴": "洴",
  "派": "派",
  "流": "流",
  "流": "流",
  "流": "流",
  "洖": "洖",
  "浩": "浩",
  "浪": "浪",
  "海": "海",
  "海": "海",
  "浸": "浸",
  "涅": "涅",
  "𣴞": "𣴞",
  "淋": "淋",
  "淚": "淚",
  "淪": "淪",
  "淹": "淹",
  "渚": "渚",
  "港": "港",
  "湮": "湮",
  "潙": "溈",
  "滋": "滋",
  "滋": "滋",
  "溜": "溜",
  "溺": "溺",
  "滇": "滇",
  "滑": "滑",
  "滛": "滛",
  "㴳": "㴳",
  "漏": "漏",
  "漢": "漢",
  "漢": "漢",
  "漣": "漣",
  "𣻑": "𣻑",
  "潮": "潮",
  "𣽞": "𣽞",
  "𣾎": "𣾎",
  "濆": "濆",
  "濫": "濫",
  "濾": "濾",
  "瀛": "瀛",
  "瀞": "瀞",
  "瀞": "瀞",
  "瀹": "瀹",
  "灊": "灊",
  "㶖": "㶖",
  "⽕": "火",
  "⺣": "灬",
  "灰": "灰",
  "灷": "灷",
  "災": "災",
  "炙": "炙",
  "炭": "炭",
  "烈": "烈",
  "烙": "烙",
  "煮": "煮",
  "煮": "煮",
  "𤉣": "𤉣",
  "煅": "煅",
  "煉": "煉",
  "𤋮": "𤋮",
  "熜": "熜",
  "燎": "燎",
  "燐": "燐",
  "𤎫": "𤎫",
  "爐": "爐",
  "爛": "爛",
  "爨": "爨",
  "⽖": "爪",
  "爫": "爫",
  "⺤": "爫",
  "爵": "爵",
  "爵": "爵",
  "⽗": "父",
  "⽘": "爻",
  "⺦": "丬",
  "⽙": "爿",
  "⽚": "片",
  "牐": "牐",
  "⽛": "牙",
  "𤘈": "𤘈",
  "⽜": "牛",
  "牢": "牢",
  "犀": "犀",
  "犕": "犕",
  "⽝": "犬",
  "⺨": "犭",
  "犯": "犯",
  "狀": "狀",
  "𤜵": "𤜵",
  "狼": "狼",
  "猪": "猪",
  "猪": "猪",
  "𤠔": "𤠔",
  "獵": "獵",
  "獺": "獺",
  "⽞": "玄",
  "率": "率",
  "率": "率",
  "⽟": "玉",
  "王": "王",
  "㺬": "㺬",
  "玥": "玥",
  "玲": "玲",
  "㺸": "㺸",
  "㺸": "㺸",
  "珞": "珞",
  "琉": "琉",
  "理": "理",
  "琢": "琢",
  "瑇": "瑇",
  "瑜": "瑜",
  "瑩": "瑩",
  "瑱": "瑱",
  "瑱": "瑱",
  "璅": "璅",
  "璉": "璉",
  "璘": "璘",
  "瓊": "瓊",
  "⽠": "瓜",
  "⽡": "瓦",
  "㼛": "㼛",
  "甆": "甆",
  "⽢": "甘",
  "⽣": "生",
  "甤": "甤",
  "⽤": "用",
  "⽥": "田",
  "画": "画",
  "甾": "甾",
  "𤰶": "𤰶",
  "留": "留",
  "略": "略",
  "異": "異",
  "異": "異",
  "𤲒": "𤲒",
  "⽦": "疋",
  "⽧": "疒",
  "痢": "痢",
  "瘐": "瘐",
  "瘟": "瘟",
  "瘝": "瘝",
  "療": "療",
  "癩": "癩",
  "⽨": "癶",
  "⽩": "白",
  "𤾡": "𤾡",
  "𤾸": "𤾸",
  "⽪": "皮",
  "⽫": "皿",
  "𥁄": "𥁄",
  "㿼": "㿼",
  "益": "益",
  "益": "益",
  "盛": "盛",
  "盧": "盧",
  "䀈": "䀈",
  "⽬": "目",
  "直": "直",
  "直": "直",
  "𥃲": "𥃲",
  "𥃳": "𥃳",
  "省": "省",
  "䀘": "䀘",
  "𥄙": "𥄙",
  "眞": "眞",
  "真": "真",
  "真": "真",
  "𥄳": "𥄳",
  "着": "着",
  "睊": "睊",
  "睊": "睊",
  "鿃": "䀹",
  "䀹": "䀹",
  "䀹": "䀹",
  "晣": "䀿",
  "䁆": "䁆",
  "瞋": "瞋",
  "𥉉": "𥉉",
  "瞧": "瞧",
  "⽭": "矛",
  "⽮": "矢",
  "⽯": "石",
  "䂖": "䂖",
  "𥐝": "𥐝",
  "硏": "研",
  "硎": "硎",
  "硫": "硫",
  "碌": "碌",
  "碌": "碌",
  "碑": "碑",
  "磊": "磊",
  "磌": "磌",
  "磌": "磌",
  "磻": "磻",
  "䃣": "䃣",
  "礪": "礪",
  "⽰": "示",
  "⺭": "礻",
  "礼": "礼",
  "社": "社",
  "祈": "祈",
  "祉": "祉",
  "𥘦": "𥘦",
  "祐": "祐",
  "祖": "祖",
  "祖": "祖",
  "祝": "祝",
  "神": "神",
  "祥": "祥",
  "視": "視",
  "視": "視",
  "祿": "祿",
  "𥚚": "𥚚",
  "禍": "禍",
  "禎": "禎",
  "福": "福",
  "福": "福",
  "𥛅": "𥛅",
  "禮": "禮",
  "⽱": "禸",
  "⽲": "禾",
  "秊": "秊",
  "䄯": "䄯",
  "秫": "秫",
  "稜": "稜",
  "穊": "穊",
  "穀": "穀",
  "穀": "穀",
  "穏": "穏",
  "⽳": "穴",
  "突": "突",
  "𥥼": "𥥼",
  "窱": "窱",
  "立": "立",
  "⽴": "立",
  "⻯": "竜",
  "𥪧": "𥪧",
  "𥪧": "𥪧",
  "竮": "竮",
  "⽵": "竹",
  "笠": "笠",
  "節": "節",
  "節": "節",
  "䈂": "䈂",
  "𥮫": "𥮫",
  "篆": "篆",
  "䈧": "䈧",
  "築": "築",
  "𥲀": "𥲀",
  "𥳐": "𥳐",
  "簾": "簾",
  "籠": "籠",
  "⽶": "米",
  "类": "类",
  "粒": "粒",
  "精": "精",
  "糒": "糒",
  "糖": "糖",
  "糨": "糨",
  "䊠": "䊠",
  "糣": "糣",
  "糧": "糧",
  "⽷": "糸",
  "⺯": "糹",
  "𥾆": "𥾆",
  "紀": "紀",
  "紐": "紐",
  "索": "索",
  "累": "累",
  "絶": "絕",
  "絣": "絣",
  "絛": "絛",
  "綠": "綠",
  "綾": "綾",
  "緇": "緇",
  "練": "練",
  "練": "練",
  "練": "練",
  "縂": "縂",
  "䌁": "䌁",
  "縉": "縉",
  "縷": "縷",
  "繁": "繁",
  "繅": "繅",
  "𦇚": "𦇚",
  "䌴": "䌴",
  "⽸": "缶",
  "𦈨": "𦈨",
  "缾": "缾",
  "𦉇": "𦉇",
  "⽹": "网",
  "⺫": "罒",
  "⺲": "罒",
  "⺱": "罓",
  "䍙": "䍙",
  "署": "署",
  "𦋙": "𦋙",
  "罹": "罹",
  "罺": "罺",
  "羅": "羅",
  "𦌾": "𦌾",
  "⽺": "羊",
  "羕": "羕",
  "羚": "羚",
  "羽": "羽",
  "⽻": "羽",
  "翺": "翺",
  "老": "老",
  "⽼": "老",
  "⺹": "耂",
  "者": "者",
  "者": "者",
  "者": "者",
  "⽽": "而",
  "𦓚": "𦓚",
  "⽾": "耒",
  "𦔣": "𦔣",
  "⽿": "耳",
  "聆": "聆",
  "聠": "聠",
  "𦖨": "𦖨",
  "聯": "聯",
  "聰": "聰",
  "聾": "聾",
  "⾀": "聿",
  "⺺": "肀",
  "⾁": "肉",
  "肋": "肋",
  "肭": "肭",
  "育": "育",
  "䏕": "䏕",
  "䏙": "䏙",
  "腁": "胼",
  "脃": "脃",
  "脾": "脾",
  "䐋": "䐋",
  "朡": "朡",
  "𦞧": "𦞧",
  "𦞵": "𦞵",
  "朦": "䑃",
  "臘": "臘",
  "⾂": "臣",
  "臨": "臨",
  "⾃": "自",
  "臭": "臭",
  "⾄": "至",
  "⾅": "臼",
  "舁": "舁",
  "舁": "舁",
  "舄": "舄",
  "⾆": "舌",
  "舘": "舘",
  "⾇": "舛",
  "⾈": "舟",
  "䑫": "䑫",
  "⾉": "艮",
  "良": "良",
  "⾊": "色",
  "⾋": "艸",
  "艹": "艹",
  "艹": "艹",
  "⺾": "艹",
  "⺿": "艹",
  "⻀": "艹",
  "芋": "芋",
  "芑": "芑",
  "芝": "芝",
  "花": "花",
  "芳": "芳",
  "芽": "芽",
  "若": "若",
  "若": "若",
  "苦": "苦",
  "𦬼": "𦬼",
  "茶": "茶",
  "荒": "荒",
  "荣": "荣",
  "茝": "茝",
  "茣": "茣",
  "莽": "莽",
  "荓": "荓",
  "菉": "菉",
  "菊": "菊",
  "菌": "菌",
  "菜": "菜",
  "菧": "菧",
  "華": "華",
  "菱": "菱",
  "著": "著",
  "著": "著",
  "𦰶": "𦰶",
  "莭": "莭",
  "落": "落",
  "葉": "葉",
  "蔿": "蒍",
  "𦳕": "𦳕",
  "𦵫": "𦵫",
  "蓮": "蓮",
  "蓱": "蓱",
  "蓳": "蓳",
  "蓼": "蓼",
  "蔖": "蔖",
  "䔫": "䔫",
  "蕤": "蕤",
  "𦼬": "𦼬",
  "藍": "藍",
  "䕝": "䕝",
  "𦾱": "𦾱",
  "䕡": "䕡",
  "藺": "藺",
  "蘆": "蘆",
  "䕫": "䕫",
  "蘒": "蘒",
  "蘭": "蘭",
  "𧃒": "𧃒",
  "虁": "蘷",
  "蘿": "蘿",
  "⾌": "虍",
  "⻁": "虎",
  "虐": "虐",
  "虜": "虜",
  "虜": "虜",
  "虧": "虧",
  "虩": "虩",
  "⾍": "虫",
  "蚩": "蚩",
  "蚈": "蚈",
  "蛢": "蛢",
  "蜎": "蜎",
  "蜨": "蜨",
  "蝫": "蝫",
  "蟡": "蟡",
  "蝹": "蝹",
  "蝹": "蝹",
  "螆": "螆",
  "䗗": "䗗",
  "𧏊": "𧏊",
  "螺": "螺",
  "蠁": "蠁",
  "䗹": "䗹",
  "蠟": "蠟",
  "⾎": "血",
  "行": "行",
  "⾏": "行",
  "衠": "衠",
  "衣": "衣",
  "⾐": "衣",
  "⻂": "衤",
  "裂": "裂",
  "𧙧": "𧙧",
  "裏": "裏",
  "裗": "裗",
  "裞": "裞",
  "裡": "裡",
  "裸": "裸",
  "裺": "裺",
  "䘵": "䘵",
  "褐": "褐",
  "襁": "襁",
  "襤": "襤",
  "⾑": "襾",
  "⻄": "西",
  "⻃": "覀",
  "覆": "覆",
  "見": "見",
  "⾒": "見",
  "𧢮": "𧢮",
  "⻅": "见",
  "⾓": "角",
  "⾔": "言",
  "𧥦": "𧥦",
  "詽": "訮",
  "訞": "䚶",
  "䚾": "䚾",
  "䛇": "䛇",
  "誠": "誠",
  "說": "說",
  "說": "說",
  "調": "調",
  "請": "請",
  "諒": "諒",
  "論": "論",
  "諭": "諭",
  "諭": "諭",
  "諸": "諸",
  "諸": "諸",
  "諾": "諾",
  "諾": "諾",
  "謁": "謁",
  "謁": "謁",
  "謹": "謹",
  "謹": "謹",
  "識": "識",
  "讀": "讀",
  "讏": "讆",
  "變": "變",
  "變": "變",
  "⻈": "讠",
  "⾕": "谷",
  "⾖": "豆",
  "豈": "豈",
  "豕": "豕",
  "⾗": "豕",
  "豣": "豜",
  "⾘": "豸",
  "𧲨": "𧲨",
  "⾙": "貝",
  "貫": "貫",
  "賁": "賁",
  "賂": "賂",
  "賈": "賈",
  "賓": "賓",
  "贈": "贈",
  "贈": "贈",
  "贛": "贛",
  "⻉": "贝",
  "⾚": "赤",
  "⾛": "走",
  "起": "起",
  "趆": "赿",
  "𧻓": "𧻓",
  "𧼯": "𧼯",
  "⾜": "足",
  "跋": "跋",
  "趼": "趼",
  "跺": "跥",
  "路": "路",
  "跰": "跰",
  "躛": "躗",
  "⾝": "身",
  "車": "車",
  "⾞": "車",
  "軔": "軔",
  "輧": "軿",
  "輦": "輦",
  "輪": "輪",
  "輸": "輸",
  "輸": "輸",
  "輻": "輻",
  "轢": "轢",
  "⻋": "车",
  "⾟": "辛",
  "辞": "辞",
  "辰": "辰",
  "⾠": "辰",
  "⾡": "辵",
  "辶": "辶",
  "⻌": "辶",
  "⻍": "辶",
  "巡": "巡",
  "連": "連",
  "逸": "逸",
  "逸": "逸",
  "遲": "遲",
  "遼": "遼",
  "𨗒": "𨗒",
  "𨗭": "𨗭",
  "邏": "邏",
  "⾢": "邑",
  "邔": "邔",
  "郎": "郎",
  "郞": "郎",
  "郞": "郎",
  "郱": "郱",
  "都": "都",
  "𨜮": "𨜮",
  "鄑": "鄑",
  "鄛": "鄛",
  "⾣": "酉",
  "酪": "酪",
  "醙": "醙",
  "醴": "醴",
  "⾤": "釆",
  "里": "里",
  "⾥": "里",
  "量": "量",
  "金": "金",
  "⾦": "金",
  "鈴": "鈴",
  "鈸": "鈸",
  "鉶": "鉶",
  "鋗": "鋗",
  "鋘": "鋘",
  "鉼": "鉼",
  "錄": "錄",
  "鍊": "鍊",
  "鎮": "鎭",
  "鏹": "鏹",
  "鐕": "鐕",
  "𨯺": "𨯺",
  "⻐": "钅",
  "⻑": "長",
  "⾧": "長",
  "⻒": "镸",
  "⻓": "长",
  "⾨": "門",
  "開": "開",
  "䦕": "䦕",
  "閭": "閭",
  "閷": "閷",
  "𨵷": "𨵷",
  "⻔": "门",
  "⾩": "阜",
  "⻏": "阝",
  "⻖": "阝",
  "阮": "阮",
  "陋": "陋",
  "降": "降",
  "陵": "陵",
  "陸": "陸",
  "陼": "陼",
  "隆": "隆",
  "隣": "隣",
  "䧦": "䧦",
  "⾪": "隶",
  "隷": "隷",
  "隸": "隷",
  "隸": "隷",
  "⾫": "隹",
  "雃": "雃",
  "離": "離",
  "難": "難",
  "難": "難",
  "⾬": "雨",
  "零": "零",
  "雷": "雷",
  "霣": "霣",
  "𩅅": "𩅅",
  "露": "露",
  "靈": "靈",
  "⾭": "靑",
  "⻘": "青",
  "靖": "靖",
  "靖": "靖",
  "𩇟": "𩇟",
  "⾮": "非",
  "⾯": "面",
  "𩈚": "𩈚",
  "⾰": "革",
  "䩮": "䩮",
  "䩶": "䩶",
  "⾱": "韋",
  "韛": "韛",
  "韠": "韠",
  "⻙": "韦",
  "⾲": "韭",
  "𩐊": "𩐊",
  "⾳": "音",
  "響": "響",
  "響": "響",
  "⾴": "頁",
  "䪲": "䪲",
  "頋": "頋",
  "頋": "頋",
  "頋": "頋",
  "領": "領",
  "頩": "頩",
  "𩒖": "𩒖",
  "頻": "頻",
  "頻": "頻",
  "類": "類",
  "⻚": "页",
  "⾵": "風",
  "𩖶": "𩖶",
  "⻛": "风",
  "⾶": "飛",
  "⻜": "飞",
  "⻝": "食",
  "⾷": "食",
  "⻟": "飠",
  "飢": "飢",
  "飯": "飯",
  "飼": "飼",
  "䬳": "䬳",
  "館": "館",
  "餩": "餩",
  "⻠": "饣",
  "⾸": "首",
  "⾹": "香",
  "馧": "馧",
  "⾺": "馬",
  "駂": "駂",
  "駱": "駱",
  "駾": "駾",
  "驪": "驪",
  "⻢": "马",
  "⾻": "骨",
  "䯎": "䯎",
  "⾼": "高",
  "⾽": "髟",
  "𩬰": "𩬰",
  "鬒": "鬒",
  "鬒": "鬒",
  "⾾": "鬥",
  "⾿": "鬯",
  "⿀": "鬲",
  "⿁": "鬼",
  "⻤": "鬼",
  "⿂": "魚",
  "魯": "魯",
  "鱀": "鱀",
  "鱗": "鱗",
  "⻥": "鱼",
  "⿃": "鳥",
  "鳽": "鳽",
  "䳎": "䳎",
  "鵧": "鵧",
  "䳭": "䳭",
  "𪃎": "𪃎",
  "鶴": "鶴",
  "𪄅": "𪄅",
  "䳸": "䳸",
  "鷺": "鷺",
  "𪈎": "𪈎",
  "鸞": "鸞",
  "鹃": "鹂",
  "⿄": "鹵",
  "鹿": "鹿",
  "⿅": "鹿",
  "𪊑": "𪊑",
  "麗": "麗",
  "麟": "麟",
  "⿆": "麥",
  "⻨": "麦",
  "麻": "麻",
  "⿇": "麻",
  "𪎒": "𪎒",
  "⿈": "黃",
  "⻩": "黄",
  "⿉": "黍",
  "黎": "黎",
  "䵖": "䵖",
  "⿊": "黑",
  "黒": "黑",
  "墨": "墨",
  "黹": "黹",
  "⿋": "黹",
  "⿌": "黽",
  "鼅": "鼅",
  "黾": "黾",
  "⿍": "鼎",
  "鼏": "鼏",
  "⿎": "鼓",
  "鼖": "鼖",
  "⿏": "鼠",
  "鼻": "鼻",
  "⿐": "鼻",
  "齃": "齃",
  "⿑": "齊",
  "⻬": "齐",
  "⿒": "齒",
  "𪘀": "𪘀",
  "⻮": "齿",
  "龍": "龍",
  "⿓": "龍",
  "龎": "龎",
  "⻰": "龙",
  "龜": "龜",
  "龜": "龜",
  "龜": "龜",
  "⿔": "龜",
  "⻳": "龟",
  "⿕": "龠"
}
},{}],55:[function(require,module,exports){
'use strict';


var data = require('./data.json');

function escapeRegexp(str) {
  return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}

var REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');

function replace_fn(match) {
  return data[match];
}

function unhomoglyph(str) {
  return str.replace(REPLACE_RE, replace_fn);
}

module.exports = unhomoglyph;

},{"./data.json":54}],56:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

var punycode = require('punycode');
var util = require('./util');

exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;

exports.Url = Url;

function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}

// Reference: RFC 3986, RFC 1808, RFC 2396

// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
    portPattern = /:[0-9]*$/,

    // Special case for a simple path URL
    simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,

    // RFC 2396: characters reserved for delimiting URLs.
    // We actually just auto-escape these.
    delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],

    // RFC 2396: characters not allowed for various reasons.
    unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),

    // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
    autoEscape = ['\''].concat(unwise),
    // Characters that are never ever allowed in a hostname.
    // Note that any invalid chars are also handled, but these
    // are the ones that are *expected* to be seen, so we fast-path
    // them.
    nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
    hostEndingChars = ['/', '?', '#'],
    hostnameMaxLen = 255,
    hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
    hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
    // protocols that can allow "unsafe" and "unwise" chars.
    unsafeProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that never have a hostname.
    hostlessProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that always contain a // bit.
    slashedProtocol = {
      'http': true,
      'https': true,
      'ftp': true,
      'gopher': true,
      'file': true,
      'http:': true,
      'https:': true,
      'ftp:': true,
      'gopher:': true,
      'file:': true
    },
    querystring = require('querystring');

function urlParse(url, parseQueryString, slashesDenoteHost) {
  if (url && util.isObject(url) && url instanceof Url) return url;

  var u = new Url;
  u.parse(url, parseQueryString, slashesDenoteHost);
  return u;
}

Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  if (!util.isString(url)) {
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  }

  // Copy chrome, IE, opera backslash-handling behavior.
  // Back slashes before the query string get converted to forward slashes
  // See: https://code.google.com/p/chromium/issues/detail?id=25916
  var queryIndex = url.indexOf('?'),
      splitter =
          (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
      uSplit = url.split(splitter),
      slashRegex = /\\/g;
  uSplit[0] = uSplit[0].replace(slashRegex, '/');
  url = uSplit.join(splitter);

  var rest = url;

  // trim before proceeding.
  // This is to support parse stuff like "  http://foo.com  \n"
  rest = rest.trim();

  if (!slashesDenoteHost && url.split('#').length === 1) {
    // Try fast path regexp
    var simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      this.path = rest;
      this.href = rest;
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
        if (parseQueryString) {
          this.query = querystring.parse(this.search.substr(1));
        } else {
          this.query = this.search.substr(1);
        }
      } else if (parseQueryString) {
        this.search = '';
        this.query = {};
      }
      return this;
    }
  }

  var proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    var lowerProto = proto.toLowerCase();
    this.protocol = lowerProto;
    rest = rest.substr(proto.length);
  }

  // figure out if it's got a host
  // user@server is *always* interpreted as a hostname, and url
  // resolution will treat //foo/bar as host=foo,path=bar because that's
  // how the browser resolves relative URLs.
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    var slashes = rest.substr(0, 2) === '//';
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }

  if (!hostlessProtocol[proto] &&
      (slashes || (proto && !slashedProtocol[proto]))) {

    // there's a hostname.
    // the first instance of /, ?, ;, or # ends the host.
    //
    // If there is an @ in the hostname, then non-host chars *are* allowed
    // to the left of the last @ sign, unless some host-ending character
    // comes *before* the @-sign.
    // URLs are obnoxious.
    //
    // ex:
    // http://a@b@c/ => user:a@b host:c
    // http://a@b?@c => user:a host:c path:/?@c

    // v0.12 TODO(isaacs): This is not quite how Chrome does things.
    // Review our test case against browsers more comprehensively.

    // find the first instance of any hostEndingChars
    var hostEnd = -1;
    for (var i = 0; i < hostEndingChars.length; i++) {
      var hec = rest.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }

    // at this point, either we have an explicit point where the
    // auth portion cannot go past, or the last @ char is the decider.
    var auth, atSign;
    if (hostEnd === -1) {
      // atSign can be anywhere.
      atSign = rest.lastIndexOf('@');
    } else {
      // atSign must be in auth portion.
      // http://a@b/c@d => host:b auth:a path:/c@d
      atSign = rest.lastIndexOf('@', hostEnd);
    }

    // Now we have a portion which is definitely the auth.
    // Pull that off.
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = decodeURIComponent(auth);
    }

    // the host is the remaining to the left of the first non-host char
    hostEnd = -1;
    for (var i = 0; i < nonHostChars.length; i++) {
      var hec = rest.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    // if we still have not hit it, then the entire thing is a host.
    if (hostEnd === -1)
      hostEnd = rest.length;

    this.host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);

    // pull out port.
    this.parseHost();

    // we've indicated that there is a hostname,
    // so even if it's empty, it has to be present.
    this.hostname = this.hostname || '';

    // if hostname begins with [ and ends with ]
    // assume that it's an IPv6 address.
    var ipv6Hostname = this.hostname[0] === '[' &&
        this.hostname[this.hostname.length - 1] === ']';

    // validate a little.
    if (!ipv6Hostname) {
      var hostparts = this.hostname.split(/\./);
      for (var i = 0, l = hostparts.length; i < l; i++) {
        var part = hostparts[i];
        if (!part) continue;
        if (!part.match(hostnamePartPattern)) {
          var newpart = '';
          for (var j = 0, k = part.length; j < k; j++) {
            if (part.charCodeAt(j) > 127) {
              // we replace non-ASCII char with a temporary placeholder
              // we need this to make sure size of hostname is not
              // broken by replacing non-ASCII by nothing
              newpart += 'x';
            } else {
              newpart += part[j];
            }
          }
          // we test again with ASCII char only
          if (!newpart.match(hostnamePartPattern)) {
            var validParts = hostparts.slice(0, i);
            var notHost = hostparts.slice(i + 1);
            var bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = '/' + notHost.join('.') + rest;
            }
            this.hostname = validParts.join('.');
            break;
          }
        }
      }
    }

    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = '';
    } else {
      // hostnames are always lower case.
      this.hostname = this.hostname.toLowerCase();
    }

    if (!ipv6Hostname) {
      // IDNA Support: Returns a punycoded representation of "domain".
      // It only converts parts of the domain name that
      // have non-ASCII characters, i.e. it doesn't matter if
      // you call it with a domain that already is ASCII-only.
      this.hostname = punycode.toASCII(this.hostname);
    }

    var p = this.port ? ':' + this.port : '';
    var h = this.hostname || '';
    this.host = h + p;
    this.href += this.host;

    // strip [ and ] from the hostname
    // the host field still retains them, though
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
      if (rest[0] !== '/') {
        rest = '/' + rest;
      }
    }
  }

  // now rest is set to the post-host stuff.
  // chop off any delim chars.
  if (!unsafeProtocol[lowerProto]) {

    // First, make 100% sure that any "autoEscape" chars get
    // escaped, even if encodeURIComponent doesn't think they
    // need to be.
    for (var i = 0, l = autoEscape.length; i < l; i++) {
      var ae = autoEscape[i];
      if (rest.indexOf(ae) === -1)
        continue;
      var esc = encodeURIComponent(ae);
      if (esc === ae) {
        esc = escape(ae);
      }
      rest = rest.split(ae).join(esc);
    }
  }


  // chop off from the tail first.
  var hash = rest.indexOf('#');
  if (hash !== -1) {
    // got a fragment string.
    this.hash = rest.substr(hash);
    rest = rest.slice(0, hash);
  }
  var qm = rest.indexOf('?');
  if (qm !== -1) {
    this.search = rest.substr(qm);
    this.query = rest.substr(qm + 1);
    if (parseQueryString) {
      this.query = querystring.parse(this.query);
    }
    rest = rest.slice(0, qm);
  } else if (parseQueryString) {
    // no query string, but parseQueryString still requested
    this.search = '';
    this.query = {};
  }
  if (rest) this.pathname = rest;
  if (slashedProtocol[lowerProto] &&
      this.hostname && !this.pathname) {
    this.pathname = '/';
  }

  //to support http.request
  if (this.pathname || this.search) {
    var p = this.pathname || '';
    var s = this.search || '';
    this.path = p + s;
  }

  // finally, reconstruct the href based on what has been validated.
  this.href = this.format();
  return this;
};

// format a parsed object into a url string
function urlFormat(obj) {
  // ensure it's an object, and not a string url.
  // If it's an obj, this is a no-op.
  // this way, you can call url_format() on strings
  // to clean up potentially wonky urls.
  if (util.isString(obj)) obj = urlParse(obj);
  if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  return obj.format();
}

Url.prototype.format = function() {
  var auth = this.auth || '';
  if (auth) {
    auth = encodeURIComponent(auth);
    auth = auth.replace(/%3A/i, ':');
    auth += '@';
  }

  var protocol = this.protocol || '',
      pathname = this.pathname || '',
      hash = this.hash || '',
      host = false,
      query = '';

  if (this.host) {
    host = auth + this.host;
  } else if (this.hostname) {
    host = auth + (this.hostname.indexOf(':') === -1 ?
        this.hostname :
        '[' + this.hostname + ']');
    if (this.port) {
      host += ':' + this.port;
    }
  }

  if (this.query &&
      util.isObject(this.query) &&
      Object.keys(this.query).length) {
    query = querystring.stringify(this.query);
  }

  var search = this.search || (query && ('?' + query)) || '';

  if (protocol && protocol.substr(-1) !== ':') protocol += ':';

  // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
  // unless they had them to begin with.
  if (this.slashes ||
      (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = '//' + (host || '');
    if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  } else if (!host) {
    host = '';
  }

  if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  if (search && search.charAt(0) !== '?') search = '?' + search;

  pathname = pathname.replace(/[?#]/g, function(match) {
    return encodeURIComponent(match);
  });
  search = search.replace('#', '%23');

  return protocol + host + pathname + search + hash;
};

function urlResolve(source, relative) {
  return urlParse(source, false, true).resolve(relative);
}

Url.prototype.resolve = function(relative) {
  return this.resolveObject(urlParse(relative, false, true)).format();
};

function urlResolveObject(source, relative) {
  if (!source) return relative;
  return urlParse(source, false, true).resolveObject(relative);
}

Url.prototype.resolveObject = function(relative) {
  if (util.isString(relative)) {
    var rel = new Url();
    rel.parse(relative, false, true);
    relative = rel;
  }

  var result = new Url();
  var tkeys = Object.keys(this);
  for (var tk = 0; tk < tkeys.length; tk++) {
    var tkey = tkeys[tk];
    result[tkey] = this[tkey];
  }

  // hash is always overridden, no matter what.
  // even href="" will remove it.
  result.hash = relative.hash;

  // if the relative url is empty, then there's nothing left to do here.
  if (relative.href === '') {
    result.href = result.format();
    return result;
  }

  // hrefs like //foo/bar always cut to the protocol.
  if (relative.slashes && !relative.protocol) {
    // take everything except the protocol from relative
    var rkeys = Object.keys(relative);
    for (var rk = 0; rk < rkeys.length; rk++) {
      var rkey = rkeys[rk];
      if (rkey !== 'protocol')
        result[rkey] = relative[rkey];
    }

    //urlParse appends trailing / to urls like http://www.example.com
    if (slashedProtocol[result.protocol] &&
        result.hostname && !result.pathname) {
      result.path = result.pathname = '/';
    }

    result.href = result.format();
    return result;
  }

  if (relative.protocol && relative.protocol !== result.protocol) {
    // if it's a known url protocol, then changing
    // the protocol does weird things
    // first, if it's not file:, then we MUST have a host,
    // and if there was a path
    // to begin with, then we MUST have a path.
    // if it is file:, then the host is dropped,
    // because that's known to be hostless.
    // anything else is assumed to be absolute.
    if (!slashedProtocol[relative.protocol]) {
      var keys = Object.keys(relative);
      for (var v = 0; v < keys.length; v++) {
        var k = keys[v];
        result[k] = relative[k];
      }
      result.href = result.format();
      return result;
    }

    result.protocol = relative.protocol;
    if (!relative.host && !hostlessProtocol[relative.protocol]) {
      var relPath = (relative.pathname || '').split('/');
      while (relPath.length && !(relative.host = relPath.shift()));
      if (!relative.host) relative.host = '';
      if (!relative.hostname) relative.hostname = '';
      if (relPath[0] !== '') relPath.unshift('');
      if (relPath.length < 2) relPath.unshift('');
      result.pathname = relPath.join('/');
    } else {
      result.pathname = relative.pathname;
    }
    result.search = relative.search;
    result.query = relative.query;
    result.host = relative.host || '';
    result.auth = relative.auth;
    result.hostname = relative.hostname || relative.host;
    result.port = relative.port;
    // to support http.request
    if (result.pathname || result.search) {
      var p = result.pathname || '';
      var s = result.search || '';
      result.path = p + s;
    }
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
  }

  var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
      isRelAbs = (
          relative.host ||
          relative.pathname && relative.pathname.charAt(0) === '/'
      ),
      mustEndAbs = (isRelAbs || isSourceAbs ||
                    (result.host && relative.pathname)),
      removeAllDots = mustEndAbs,
      srcPath = result.pathname && result.pathname.split('/') || [],
      relPath = relative.pathname && relative.pathname.split('/') || [],
      psychotic = result.protocol && !slashedProtocol[result.protocol];

  // if the url is a non-slashed url, then relative
  // links like ../.. should be able
  // to crawl up to the hostname, as well.  This is strange.
  // result.protocol has already been set by now.
  // Later on, put the first path part into the host field.
  if (psychotic) {
    result.hostname = '';
    result.port = null;
    if (result.host) {
      if (srcPath[0] === '') srcPath[0] = result.host;
      else srcPath.unshift(result.host);
    }
    result.host = '';
    if (relative.protocol) {
      relative.hostname = null;
      relative.port = null;
      if (relative.host) {
        if (relPath[0] === '') relPath[0] = relative.host;
        else relPath.unshift(relative.host);
      }
      relative.host = null;
    }
    mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  }

  if (isRelAbs) {
    // it's absolute.
    result.host = (relative.host || relative.host === '') ?
                  relative.host : result.host;
    result.hostname = (relative.hostname || relative.hostname === '') ?
                      relative.hostname : result.hostname;
    result.search = relative.search;
    result.query = relative.query;
    srcPath = relPath;
    // fall through to the dot-handling below.
  } else if (relPath.length) {
    // it's relative
    // throw away the existing file, and take the new path instead.
    if (!srcPath) srcPath = [];
    srcPath.pop();
    srcPath = srcPath.concat(relPath);
    result.search = relative.search;
    result.query = relative.query;
  } else if (!util.isNullOrUndefined(relative.search)) {
    // just pull out the search.
    // like href='?foo'.
    // Put this after the other two cases because it simplifies the booleans
    if (psychotic) {
      result.hostname = result.host = srcPath.shift();
      //occationaly the auth can get stuck only in host
      //this especially happens in cases like
      //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
      var authInHost = result.host && result.host.indexOf('@') > 0 ?
                       result.host.split('@') : false;
      if (authInHost) {
        result.auth = authInHost.shift();
        result.host = result.hostname = authInHost.shift();
      }
    }
    result.search = relative.search;
    result.query = relative.query;
    //to support http.request
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
      result.path = (result.pathname ? result.pathname : '') +
                    (result.search ? result.search : '');
    }
    result.href = result.format();
    return result;
  }

  if (!srcPath.length) {
    // no path at all.  easy.
    // we've already handled the other stuff above.
    result.pathname = null;
    //to support http.request
    if (result.search) {
      result.path = '/' + result.search;
    } else {
      result.path = null;
    }
    result.href = result.format();
    return result;
  }

  // if a url ENDs in . or .., then it must get a trailing slash.
  // however, if it ends in anything else non-slashy,
  // then it must NOT get a trailing slash.
  var last = srcPath.slice(-1)[0];
  var hasTrailingSlash = (
      (result.host || relative.host || srcPath.length > 1) &&
      (last === '.' || last === '..') || last === '');

  // strip single dots, resolve double dots to parent dir
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = srcPath.length; i >= 0; i--) {
    last = srcPath[i];
    if (last === '.') {
      srcPath.splice(i, 1);
    } else if (last === '..') {
      srcPath.splice(i, 1);
      up++;
    } else if (up) {
      srcPath.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (!mustEndAbs && !removeAllDots) {
    for (; up--; up) {
      srcPath.unshift('..');
    }
  }

  if (mustEndAbs && srcPath[0] !== '' &&
      (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
    srcPath.unshift('');
  }

  if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
    srcPath.push('');
  }

  var isAbsolute = srcPath[0] === '' ||
      (srcPath[0] && srcPath[0].charAt(0) === '/');

  // put the host back
  if (psychotic) {
    result.hostname = result.host = isAbsolute ? '' :
                                    srcPath.length ? srcPath.shift() : '';
    //occationaly the auth can get stuck only in host
    //this especially happens in cases like
    //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
    var authInHost = result.host && result.host.indexOf('@') > 0 ?
                     result.host.split('@') : false;
    if (authInHost) {
      result.auth = authInHost.shift();
      result.host = result.hostname = authInHost.shift();
    }
  }

  mustEndAbs = mustEndAbs || (result.host && srcPath.length);

  if (mustEndAbs && !isAbsolute) {
    srcPath.unshift('');
  }

  if (!srcPath.length) {
    result.pathname = null;
    result.path = null;
  } else {
    result.pathname = srcPath.join('/');
  }

  //to support request.http
  if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
    result.path = (result.pathname ? result.pathname : '') +
                  (result.search ? result.search : '');
  }
  result.auth = relative.auth || result.auth;
  result.slashes = result.slashes || relative.slashes;
  result.href = result.format();
  return result;
};

Url.prototype.parseHost = function() {
  var host = this.host;
  var port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ':') {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) this.hostname = host;
};

},{"./util":57,"punycode":32,"querystring":48}],57:[function(require,module,exports){
'use strict';

module.exports = {
  isString: function(arg) {
    return typeof(arg) === 'string';
  },
  isObject: function(arg) {
    return typeof(arg) === 'object' && arg !== null;
  },
  isNull: function(arg) {
    return arg === null;
  },
  isNullOrUndefined: function(arg) {
    return arg == null;
  }
};

},{}],58:[function(require,module,exports){
"use strict";
/*
Copyright 2020 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.UNSTABLE_MSC3089_BRANCH = exports.UNSTABLE_MSC3089_LEAF = exports.UNSTABLE_MSC3089_TREE_SUBTYPE = exports.UNSTABLE_MSC3088_ENABLED = exports.UNSTABLE_MSC3088_PURPOSE = exports.RoomType = exports.RoomCreateTypeField = exports.MsgType = exports.RelationType = exports.EventType = void 0;
const NamespacedValue_1 = require("../NamespacedValue");
var EventType;
(function (EventType) {
    // Room state events
    EventType["RoomCanonicalAlias"] = "m.room.canonical_alias";
    EventType["RoomCreate"] = "m.room.create";
    EventType["RoomJoinRules"] = "m.room.join_rules";
    EventType["RoomMember"] = "m.room.member";
    EventType["RoomThirdPartyInvite"] = "m.room.third_party_invite";
    EventType["RoomPowerLevels"] = "m.room.power_levels";
    EventType["RoomName"] = "m.room.name";
    EventType["RoomTopic"] = "m.room.topic";
    EventType["RoomAvatar"] = "m.room.avatar";
    EventType["RoomPinnedEvents"] = "m.room.pinned_events";
    EventType["RoomEncryption"] = "m.room.encryption";
    EventType["RoomHistoryVisibility"] = "m.room.history_visibility";
    EventType["RoomGuestAccess"] = "m.room.guest_access";
    EventType["RoomServerAcl"] = "m.room.server_acl";
    EventType["RoomTombstone"] = "m.room.tombstone";
    /**
     * @deprecated Should not be used.
     */
    EventType["RoomAliases"] = "m.room.aliases";
    EventType["SpaceChild"] = "m.space.child";
    EventType["SpaceParent"] = "m.space.parent";
    // Room timeline events
    EventType["RoomRedaction"] = "m.room.redaction";
    EventType["RoomMessage"] = "m.room.message";
    EventType["RoomMessageEncrypted"] = "m.room.encrypted";
    EventType["Sticker"] = "m.sticker";
    EventType["CallInvite"] = "m.call.invite";
    EventType["CallCandidates"] = "m.call.candidates";
    EventType["CallAnswer"] = "m.call.answer";
    EventType["CallHangup"] = "m.call.hangup";
    EventType["CallReject"] = "m.call.reject";
    EventType["CallSelectAnswer"] = "m.call.select_answer";
    EventType["CallNegotiate"] = "m.call.negotiate";
    EventType["CallReplaces"] = "m.call.replaces";
    EventType["CallAssertedIdentity"] = "m.call.asserted_identity";
    EventType["CallAssertedIdentityPrefix"] = "org.matrix.call.asserted_identity";
    EventType["KeyVerificationRequest"] = "m.key.verification.request";
    EventType["KeyVerificationStart"] = "m.key.verification.start";
    EventType["KeyVerificationCancel"] = "m.key.verification.cancel";
    EventType["KeyVerificationMac"] = "m.key.verification.mac";
    EventType["KeyVerificationDone"] = "m.key.verification.done";
    // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback
    EventType["RoomMessageFeedback"] = "m.room.message.feedback";
    EventType["Reaction"] = "m.reaction";
    // Room ephemeral events
    EventType["Typing"] = "m.typing";
    EventType["Receipt"] = "m.receipt";
    EventType["Presence"] = "m.presence";
    // Room account_data events
    EventType["FullyRead"] = "m.fully_read";
    EventType["Tag"] = "m.tag";
    EventType["SpaceOrder"] = "org.matrix.msc3230.space_order";
    // User account_data events
    EventType["PushRules"] = "m.push_rules";
    EventType["Direct"] = "m.direct";
    EventType["IgnoredUserList"] = "m.ignored_user_list";
    // to_device events
    EventType["RoomKey"] = "m.room_key";
    EventType["RoomKeyRequest"] = "m.room_key_request";
    EventType["ForwardedRoomKey"] = "m.forwarded_room_key";
    EventType["Dummy"] = "m.dummy";
})(EventType = exports.EventType || (exports.EventType = {}));
var RelationType;
(function (RelationType) {
    RelationType["Annotation"] = "m.annotation";
    RelationType["Replace"] = "m.replace";
})(RelationType = exports.RelationType || (exports.RelationType = {}));
var MsgType;
(function (MsgType) {
    MsgType["Text"] = "m.text";
    MsgType["Emote"] = "m.emote";
    MsgType["Notice"] = "m.notice";
    MsgType["Image"] = "m.image";
    MsgType["File"] = "m.file";
    MsgType["Audio"] = "m.audio";
    MsgType["Location"] = "m.location";
    MsgType["Video"] = "m.video";
})(MsgType = exports.MsgType || (exports.MsgType = {}));
exports.RoomCreateTypeField = "type";
var RoomType;
(function (RoomType) {
    RoomType["Space"] = "m.space";
})(RoomType = exports.RoomType || (exports.RoomType = {}));
/**
 * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)
 * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,
 * including its eventual removal.
 */
exports.UNSTABLE_MSC3088_PURPOSE = new NamespacedValue_1.UnstableValue("m.room.purpose", "org.matrix.msc3088.purpose");
/**
 * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)
 * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,
 * including its eventual removal.
 */
exports.UNSTABLE_MSC3088_ENABLED = new NamespacedValue_1.UnstableValue("m.enabled", "org.matrix.msc3088.enabled");
/**
 * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.
 * Note that this reference is UNSTABLE and subject to breaking changes, including its
 * eventual removal.
 */
exports.UNSTABLE_MSC3089_TREE_SUBTYPE = new NamespacedValue_1.UnstableValue("m.data_tree", "org.matrix.msc3089.data_tree");
/**
 * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.
 * Note that this reference is UNSTABLE and subject to breaking changes, including its
 * eventual removal.
 */
exports.UNSTABLE_MSC3089_LEAF = new NamespacedValue_1.UnstableValue("m.leaf", "org.matrix.msc3089.leaf");
/**
 * Branch (Leaf Reference) type for the index approach in a
 * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is
 * UNSTABLE and subject to breaking changes, including its eventual removal.
 */
exports.UNSTABLE_MSC3089_BRANCH = new NamespacedValue_1.UnstableValue("m.branch", "org.matrix.msc3089.branch");

},{"../NamespacedValue":60}],59:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Preset = exports.Visibility = void 0;
var Visibility;
(function (Visibility) {
    Visibility["Public"] = "public";
    Visibility["Private"] = "private";
})(Visibility = exports.Visibility || (exports.Visibility = {}));
var Preset;
(function (Preset) {
    Preset["PrivateChat"] = "private_chat";
    Preset["TrustedPrivateChat"] = "trusted_private_chat";
    Preset["PublicChat"] = "public_chat";
})(Preset = exports.Preset || (exports.Preset = {}));

},{}],60:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnstableValue = exports.NamespacedValue = void 0;
/**
 * Represents a simple Matrix namespaced value. This will assume that if a stable prefix
 * is provided that the stable prefix should be used when representing the identifier.
 */
class NamespacedValue {
    // Stable is optional, but one of the two parameters is required, hence the weird-looking types.
    // Goal is to to have developers explicitly say there is no stable value (if applicable).
    constructor(stable, unstable) {
        this.stable = stable;
        this.unstable = unstable;
        if (!this.unstable && !this.stable) {
            throw new Error("One of stable or unstable values must be supplied");
        }
    }
    get name() {
        if (this.stable) {
            return this.stable;
        }
        return this.unstable;
    }
    get altName() {
        if (!this.stable) {
            return null;
        }
        return this.unstable;
    }
    matches(val) {
        return this.name === val || this.altName === val;
    }
    // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class
    // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.
    findIn(obj) {
        let val;
        if (this.name) {
            val = obj === null || obj === void 0 ? void 0 : obj[this.name];
        }
        if (!val && this.altName) {
            val = obj === null || obj === void 0 ? void 0 : obj[this.altName];
        }
        return val;
    }
    includedIn(arr) {
        let included = false;
        if (this.name) {
            included = arr.includes(this.name);
        }
        if (!included && this.altName) {
            included = arr.includes(this.altName);
        }
        return included;
    }
}
exports.NamespacedValue = NamespacedValue;
/**
 * Represents a namespaced value which prioritizes the unstable value over the stable
 * value.
 */
class UnstableValue extends NamespacedValue {
    // Note: Constructor difference is that `unstable` is *required*.
    constructor(stable, unstable) {
        super(stable, unstable);
        if (!this.unstable) {
            throw new Error("Unstable value must be supplied");
        }
    }
    get name() {
        return this.unstable;
    }
    get altName() {
        return this.stable;
    }
}
exports.UnstableValue = UnstableValue;

},{}],61:[function(require,module,exports){
"use strict";
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReEmitter = void 0;
class ReEmitter {
    constructor(target) {
        this.target = target;
    }
    reEmit(source, eventNames) {
        for (const eventName of eventNames) {
            // We include the source as the last argument for event handlers which may need it,
            // such as read receipt listeners on the client class which won't have the context
            // of the room.
            const forSource = (...args) => {
                // EventEmitter special cases 'error' to make the emit function throw if no
                // handler is attached, which sort of makes sense for making sure that something
                // handles an error, but for re-emitting, there could be a listener on the original
                // source object so the test doesn't really work. We *could* try to replicate the
                // same logic and throw if there is no listener on either the source or the target,
                // but this behaviour is fairly undesireable for us anyway: the main place we throw
                // 'error' events is for calls, where error events are usually emitted some time
                // later by a different part of the code where 'emit' throwing because the app hasn't
                // added an error handler isn't terribly helpful. (A better fix in retrospect may
                // have been to just avoid using the event name 'error', but backwards compat...)
                if (eventName === 'error' && this.target.listenerCount('error') === 0)
                    return;
                this.target.emit(eventName, ...args, source);
            };
            source.on(eventName, forSource);
        }
    }
}
exports.ReEmitter = ReEmitter;

},{}],62:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AutoDiscovery = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _logger = require("./logger");

var _url = require("url");

/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/** @module auto-discovery */
// Dev note: Auto discovery is part of the spec.
// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery

/**
 * Description for what an automatically discovered client configuration
 * would look like. Although this is a class, it is recommended that it
 * be treated as an interface definition rather than as a class.
 *
 * Additional properties than those defined here may be present, and
 * should follow the Java package naming convention.
 */
var DiscoveredClientConfig = // eslint-disable-line no-unused-vars
// Dev note: this is basically a copy/paste of the .well-known response
// object as defined in the spec. It does have additional information,
// however. Overall, this exists to serve as a place for documentation
// and not functionality.
// See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client
function DiscoveredClientConfig() {
  (0, _classCallCheck2["default"])(this, DiscoveredClientConfig);

  /**
   * The homeserver configuration the client should use. This will
   * always be present on the object.
   * @type {{state: string, base_url: string}} The configuration.
   */
  this["m.homeserver"] = {
    /**
     * The lookup result state. If this is anything other than
     * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally,
     * if this is not AutoDiscovery.SUCCESS then the client should
     * assume the other properties in the client config (such as
     * the identity server configuration) are not valid.
     */
    state: AutoDiscovery.PROMPT,

    /**
     * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT
     * then this will contain a human-readable (English) message
     * for what went wrong. If the state is none of those previously
     * mentioned, this will be falsey.
     */
    error: "Something went wrong",

    /**
     * The base URL clients should use to talk to the homeserver,
     * particularly for the login process. May be falsey if the
     * state is not AutoDiscovery.SUCCESS.
     */
    base_url: "https://matrix.org"
  };
  /**
   * The identity server configuration the client should use. This
   * will always be present on teh object.
   * @type {{state: string, base_url: string}} The configuration.
   */

  this["m.identity_server"] = {
    /**
     * The lookup result state. If this is anything other than
     * AutoDiscovery.SUCCESS then base_url may be falsey.
     */
    state: AutoDiscovery.PROMPT,

    /**
     * The base URL clients should use for interacting with the
     * identity server. May be falsey if the state is not
     * AutoDiscovery.SUCCESS.
     */
    base_url: "https://vector.im"
  };
};
/**
 * Utilities for automatically discovery resources, such as homeservers
 * for users to log in to.
 */


var AutoDiscovery = /*#__PURE__*/function () {
  function AutoDiscovery() {
    (0, _classCallCheck2["default"])(this, AutoDiscovery);
  }

  (0, _createClass2["default"])(AutoDiscovery, null, [{
    key: "fromDiscoveryConfig",

    /**
     * Validates and verifies client configuration information for purposes
     * of logging in. Such information includes the homeserver URL
     * and identity server URL the client would want. Additional details
     * may also be included, and will be transparently brought into the
     * response object unaltered.
     * @param {string} wellknown The configuration object itself, as returned
     * by the .well-known auto-discovery endpoint.
     * @return {Promise<DiscoveredClientConfig>} Resolves to the verified
     * configuration, which may include error states. Rejects on unexpected
     * failure, not when verification fails.
     */
    value: function () {
      var _fromDiscoveryConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(wellknown) {
        var clientConfig, hsUrl, hsVersions, isUrl, failingClientConfig, isResponse;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // Step 1 is to get the config, which is provided to us here.
                // We default to an error state to make the first few checks easier to
                // write. We'll update the properties of this object over the duration
                // of this function.
                clientConfig = {
                  "m.homeserver": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: AutoDiscovery.ERROR_INVALID,
                    base_url: null
                  },
                  "m.identity_server": {
                    // Technically, we don't have a problem with the identity server
                    // config at this point.
                    state: AutoDiscovery.PROMPT,
                    error: null,
                    base_url: null
                  }
                };

                if (!(!wellknown || !wellknown["m.homeserver"])) {
                  _context.next = 6;
                  break;
                }

                _logger.logger.error("No m.homeserver key in config");

                clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
                clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID;
                return _context.abrupt("return", Promise.resolve(clientConfig));

              case 6:
                if (wellknown["m.homeserver"]["base_url"]) {
                  _context.next = 11;
                  break;
                }

                _logger.logger.error("No m.homeserver base_url in config");

                clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
                clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
                return _context.abrupt("return", Promise.resolve(clientConfig));

              case 11:
                // Step 2: Make sure the homeserver URL is valid *looking*. We'll make
                // sure it points to a homeserver in Step 3.
                hsUrl = this._sanitizeWellKnownUrl(wellknown["m.homeserver"]["base_url"]);

                if (hsUrl) {
                  _context.next = 16;
                  break;
                }

                _logger.logger.error("Invalid base_url for m.homeserver");

                clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
                return _context.abrupt("return", Promise.resolve(clientConfig));

              case 16:
                _context.next = 18;
                return this._fetchWellKnownObject("".concat(hsUrl, "/_matrix/client/versions"));

              case 18:
                hsVersions = _context.sent;

                if (!(!hsVersions || !hsVersions.raw["versions"])) {
                  _context.next = 24;
                  break;
                }

                _logger.logger.error("Invalid /versions response");

                clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER; // Supply the base_url to the caller because they may be ignoring liveliness
                // errors, like this one.

                clientConfig["m.homeserver"].base_url = hsUrl;
                return _context.abrupt("return", Promise.resolve(clientConfig));

              case 24:
                // Step 4: Now that the homeserver looks valid, update our client config.
                clientConfig["m.homeserver"] = {
                  state: AutoDiscovery.SUCCESS,
                  error: null,
                  base_url: hsUrl
                }; // Step 5: Try to pull out the identity server configuration

                isUrl = "";

                if (!wellknown["m.identity_server"]) {
                  _context.next = 41;
                  break;
                }

                // We prepare a failing identity server response to save lines later
                // in this branch.
                failingClientConfig = {
                  "m.homeserver": clientConfig["m.homeserver"],
                  "m.identity_server": {
                    state: AutoDiscovery.FAIL_PROMPT,
                    error: AutoDiscovery.ERROR_INVALID_IS,
                    base_url: null
                  }
                }; // Step 5a: Make sure the URL is valid *looking*. We'll make sure it
                // points to an identity server in Step 5b.

                isUrl = this._sanitizeWellKnownUrl(wellknown["m.identity_server"]["base_url"]);

                if (isUrl) {
                  _context.next = 33;
                  break;
                }

                _logger.logger.error("Invalid base_url for m.identity_server");

                failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;
                return _context.abrupt("return", Promise.resolve(failingClientConfig));

              case 33:
                _context.next = 35;
                return this._fetchWellKnownObject("".concat(isUrl, "/_matrix/identity/api/v1"));

              case 35:
                isResponse = _context.sent;

                if (!(!isResponse || !isResponse.raw || isResponse.action !== "SUCCESS")) {
                  _context.next = 41;
                  break;
                }

                _logger.logger.error("Invalid /api/v1 response");

                failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER; // Supply the base_url to the caller because they may be ignoring
                // liveliness errors, like this one.

                failingClientConfig["m.identity_server"].base_url = isUrl;
                return _context.abrupt("return", Promise.resolve(failingClientConfig));

              case 41:
                // Step 6: Now that the identity server is valid, or never existed,
                // populate the IS section.
                if (isUrl && isUrl.length > 0) {
                  clientConfig["m.identity_server"] = {
                    state: AutoDiscovery.SUCCESS,
                    error: null,
                    base_url: isUrl
                  };
                } // Step 7: Copy any other keys directly into the clientConfig. This is for
                // things like custom configuration of services.


                Object.keys(wellknown).map(function (k) {
                  if (k === "m.homeserver" || k === "m.identity_server") {
                    // Only copy selected parts of the config to avoid overwriting
                    // properties computed by the validation logic above.
                    var notProps = ["error", "state", "base_url"];

                    for (var _i = 0, _Object$keys = Object.keys(wellknown[k]); _i < _Object$keys.length; _i++) {
                      var prop = _Object$keys[_i];
                      if (notProps.includes(prop)) continue;
                      clientConfig[k][prop] = wellknown[k][prop];
                    }
                  } else {
                    // Just copy the whole thing over otherwise
                    clientConfig[k] = wellknown[k];
                  }
                }); // Step 8: Give the config to the caller (finally)

                return _context.abrupt("return", Promise.resolve(clientConfig));

              case 44:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function fromDiscoveryConfig(_x) {
        return _fromDiscoveryConfig.apply(this, arguments);
      }

      return fromDiscoveryConfig;
    }()
    /**
     * Attempts to automatically discover client configuration information
     * prior to logging in. Such information includes the homeserver URL
     * and identity server URL the client would want. Additional details
     * may also be discovered, and will be transparently included in the
     * response object unaltered.
     * @param {string} domain The homeserver domain to perform discovery
     * on. For example, "matrix.org".
     * @return {Promise<DiscoveredClientConfig>} Resolves to the discovered
     * configuration, which may include error states. Rejects on unexpected
     * failure, not when discovery fails.
     */

  }, {
    key: "findClientConfig",
    value: function () {
      var _findClientConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(domain) {
        var clientConfig, wellknown;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!(!domain || typeof domain !== "string" || domain.length === 0)) {
                  _context2.next = 2;
                  break;
                }

                throw new Error("'domain' must be a string of non-zero length");

              case 2:
                // We use a .well-known lookup for all cases. According to the spec, we
                // can do other discovery mechanisms if we want such as custom lookups
                // however we won't bother with that here (mostly because the spec only
                // supports .well-known right now).
                //
                // By using .well-known, we need to ensure we at least pull out a URL
                // for the homeserver. We don't really need an identity server configuration
                // but will return one anyways (with state PROMPT) to make development
                // easier for clients. If we can't get a homeserver URL, all bets are
                // off on the rest of the config and we'll assume it is invalid too.
                // We default to an error state to make the first few checks easier to
                // write. We'll update the properties of this object over the duration
                // of this function.
                clientConfig = {
                  "m.homeserver": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: AutoDiscovery.ERROR_INVALID,
                    base_url: null
                  },
                  "m.identity_server": {
                    // Technically, we don't have a problem with the identity server
                    // config at this point.
                    state: AutoDiscovery.PROMPT,
                    error: null,
                    base_url: null
                  }
                }; // Step 1: Actually request the .well-known JSON file and make sure it
                // at least has a homeserver definition.

                _context2.next = 5;
                return this._fetchWellKnownObject("https://".concat(domain, "/.well-known/matrix/client"));

              case 5:
                wellknown = _context2.sent;

                if (!(!wellknown || wellknown.action !== "SUCCESS")) {
                  _context2.next = 11;
                  break;
                }

                _logger.logger.error("No response or error when parsing .well-known");

                if (wellknown.reason) _logger.logger.error(wellknown.reason);

                if (wellknown.action === "IGNORE") {
                  clientConfig["m.homeserver"] = {
                    state: AutoDiscovery.PROMPT,
                    error: null,
                    base_url: null
                  };
                } else {
                  // this can only ever be FAIL_PROMPT at this point.
                  clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
                  clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID;
                }

                return _context2.abrupt("return", Promise.resolve(clientConfig));

              case 11:
                return _context2.abrupt("return", AutoDiscovery.fromDiscoveryConfig(wellknown.raw));

              case 12:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function findClientConfig(_x2) {
        return _findClientConfig.apply(this, arguments);
      }

      return findClientConfig;
    }()
    /**
     * Gets the raw discovery client configuration for the given domain name.
     * Should only be used if there's no validation to be done on the resulting
     * object, otherwise use findClientConfig().
     * @param {string} domain The domain to get the client config for.
     * @returns {Promise<object>} Resolves to the domain's client config. Can
     * be an empty object.
     */

  }, {
    key: "getRawClientConfig",
    value: function () {
      var _getRawClientConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(domain) {
        var response;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                if (!(!domain || typeof domain !== "string" || domain.length === 0)) {
                  _context3.next = 2;
                  break;
                }

                throw new Error("'domain' must be a string of non-zero length");

              case 2:
                _context3.next = 4;
                return this._fetchWellKnownObject("https://".concat(domain, "/.well-known/matrix/client"));

              case 4:
                response = _context3.sent;

                if (response) {
                  _context3.next = 7;
                  break;
                }

                return _context3.abrupt("return", {});

              case 7:
                return _context3.abrupt("return", response.raw || {});

              case 8:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function getRawClientConfig(_x3) {
        return _getRawClientConfig.apply(this, arguments);
      }

      return getRawClientConfig;
    }()
    /**
     * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and
     * is suitable for the requirements laid out by .well-known auto discovery.
     * If valid, the URL will also be stripped of any trailing slashes.
     * @param {string} url The potentially invalid URL to sanitize.
     * @return {string|boolean} The sanitized URL or a falsey value if the URL is invalid.
     * @private
     */

  }, {
    key: "_sanitizeWellKnownUrl",
    value: function _sanitizeWellKnownUrl(url) {
      if (!url) return false;

      try {
        // We have to try and parse the URL using the NodeJS URL
        // library if we're on NodeJS and use the browser's URL
        // library when we're in a browser. To accomplish this, we
        // try the NodeJS version first and fall back to the browser.
        var parsed = null;

        try {
          if (_url.URL) parsed = new _url.URL(url);else parsed = new URL(url);
        } catch (e) {
          parsed = new URL(url);
        }

        if (!parsed || !parsed.hostname) return false;
        if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
        var port = parsed.port ? ":".concat(parsed.port) : "";
        var path = parsed.pathname ? parsed.pathname : "";
        var saferUrl = "".concat(parsed.protocol, "//").concat(parsed.hostname).concat(port).concat(path);

        if (saferUrl.endsWith("/")) {
          saferUrl = saferUrl.substring(0, saferUrl.length - 1);
        }

        return saferUrl;
      } catch (e) {
        _logger.logger.error(e);

        return false;
      }
    }
    /**
     * Fetches a JSON object from a given URL, as expected by all .well-known
     * related lookups. If the server gives a 404 then the `action` will be
     * IGNORE. If the server returns something that isn't JSON, the `action`
     * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.
     *
     * The returned object will be a result of the call in object form with
     * the following properties:
     *   raw: The JSON object returned by the server.
     *   action: One of SUCCESS, IGNORE, or FAIL_PROMPT.
     *   reason: Relatively human readable description of what went wrong.
     *   error: The actual Error, if one exists.
     * @param {string} url The URL to fetch a JSON object from.
     * @return {Promise<object>} Resolves to the returned state.
     * @private
     */

  }, {
    key: "_fetchWellKnownObject",
    value: function () {
      var _fetchWellKnownObject2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(url) {
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                return _context4.abrupt("return", new Promise(function (resolve, reject) {
                  var request = require("./matrix").getRequest();

                  if (!request) throw new Error("No request library available");
                  request({
                    method: "GET",
                    uri: url,
                    timeout: 5000
                  }, function (err, response, body) {
                    if (err || response && (response.statusCode < 200 || response.statusCode >= 300)) {
                      var action = "FAIL_PROMPT";
                      var reason = (err ? err.message : null) || "General failure";

                      if (response && response.statusCode === 404) {
                        action = "IGNORE";
                        reason = AutoDiscovery.ERROR_MISSING_WELLKNOWN;
                      }

                      resolve({
                        raw: {},
                        action: action,
                        reason: reason,
                        error: err
                      });
                      return;
                    }

                    try {
                      resolve({
                        raw: JSON.parse(body),
                        action: "SUCCESS"
                      });
                    } catch (e) {
                      var _reason = AutoDiscovery.ERROR_INVALID;

                      if (e.name === "SyntaxError") {
                        _reason = AutoDiscovery.ERROR_INVALID_JSON;
                      }

                      resolve({
                        raw: {},
                        action: "FAIL_PROMPT",
                        reason: _reason,
                        error: e
                      });
                    }
                  });
                }));

              case 1:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }));

      function _fetchWellKnownObject(_x4) {
        return _fetchWellKnownObject2.apply(this, arguments);
      }

      return _fetchWellKnownObject;
    }()
  }, {
    key: "ERROR_INVALID",
    // Dev note: the constants defined here are related to but not
    // exactly the same as those in the spec. This is to hopefully
    // translate the meaning of the states in the spec, but also
    // support our own if needed.
    get: function get() {
      return "Invalid homeserver discovery response";
    }
  }, {
    key: "ERROR_GENERIC_FAILURE",
    get: function get() {
      return "Failed to get autodiscovery configuration from server";
    }
  }, {
    key: "ERROR_INVALID_HS_BASE_URL",
    get: function get() {
      return "Invalid base_url for m.homeserver";
    }
  }, {
    key: "ERROR_INVALID_HOMESERVER",
    get: function get() {
      return "Homeserver URL does not appear to be a valid Matrix homeserver";
    }
  }, {
    key: "ERROR_INVALID_IS_BASE_URL",
    get: function get() {
      return "Invalid base_url for m.identity_server";
    }
  }, {
    key: "ERROR_INVALID_IDENTITY_SERVER",
    get: function get() {
      return "Identity server URL does not appear to be a valid identity server";
    }
  }, {
    key: "ERROR_INVALID_IS",
    get: function get() {
      return "Invalid identity server discovery response";
    }
  }, {
    key: "ERROR_MISSING_WELLKNOWN",
    get: function get() {
      return "No .well-known JSON file found";
    }
  }, {
    key: "ERROR_INVALID_JSON",
    get: function get() {
      return "Invalid JSON";
    }
  }, {
    key: "ALL_ERRORS",
    get: function get() {
      return [AutoDiscovery.ERROR_INVALID, AutoDiscovery.ERROR_GENERIC_FAILURE, AutoDiscovery.ERROR_INVALID_HS_BASE_URL, AutoDiscovery.ERROR_INVALID_HOMESERVER, AutoDiscovery.ERROR_INVALID_IS_BASE_URL, AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER, AutoDiscovery.ERROR_INVALID_IS, AutoDiscovery.ERROR_MISSING_WELLKNOWN, AutoDiscovery.ERROR_INVALID_JSON];
    }
    /**
     * The auto discovery failed. The client is expected to communicate
     * the error to the user and refuse logging in.
     * @return {string}
     * @constructor
     */

  }, {
    key: "FAIL_ERROR",
    get: function get() {
      return "FAIL_ERROR";
    }
    /**
     * The auto discovery failed, however the client may still recover
     * from the problem. The client is recommended to that the same
     * action it would for PROMPT while also warning the user about
     * what went wrong. The client may also treat this the same as
     * a FAIL_ERROR state.
     * @return {string}
     * @constructor
     */

  }, {
    key: "FAIL_PROMPT",
    get: function get() {
      return "FAIL_PROMPT";
    }
    /**
     * The auto discovery didn't fail but did not find anything of
     * interest. The client is expected to prompt the user for more
     * information, or fail if it prefers.
     * @return {string}
     * @constructor
     */

  }, {
    key: "PROMPT",
    get: function get() {
      return "PROMPT";
    }
    /**
     * The auto discovery was successful.
     * @return {string}
     * @constructor
     */

  }, {
    key: "SUCCESS",
    get: function get() {
      return "SUCCESS";
    }
  }]);
  return AutoDiscovery;
}();

exports.AutoDiscovery = AutoDiscovery;

},{"./logger":106,"./matrix":107,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27,"url":56}],63:[function(require,module,exports){
(function (global){(function (){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
var _exportNames = {};
exports["default"] = void 0;

var matrixcs = _interopRequireWildcard(require("./matrix"));

Object.keys(matrixcs).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
  if (key in exports && exports[key] === matrixcs[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return matrixcs[key];
    }
  });
});

var _browserRequest = _interopRequireDefault(require("browser-request"));

var _qs = _interopRequireDefault(require("qs"));

/*
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
matrixcs.request(function (opts, fn) {
  // We manually fix the query string for browser-request because
  // it doesn't correctly handle cases like ?via=one&via=two. Instead
  // we mimic `request`'s query string interface to make it all work
  // as expected.
  // browser-request will happily take the constructed string as the
  // query string without trying to modify it further.
  opts.qs = _qs["default"].stringify(opts.qs || {}, opts.qsStringifyOptions);
  return (0, _browserRequest["default"])(opts, fn);
}); // just *accessing* indexedDB throws an exception in firefox with
// indexeddb disabled.

var indexedDB;

try {
  indexedDB = global.indexedDB;
} catch (e) {} // if our browser (appears to) support indexeddb, use an indexeddb crypto store.


if (indexedDB) {
  matrixcs.setCryptoStoreFactory(function () {
    return new matrixcs.IndexedDBCryptoStore(indexedDB, "matrix-js-sdk:crypto");
  });
} // We export 3 things to make browserify happy as well as downstream projects.
// It's awkward, but required.


var _default = matrixcs; // keep export for browserify package deps

exports["default"] = _default;
global.matrixcs = matrixcs;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./matrix":107,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"browser-request":31,"qs":42}],64:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2015-2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MatrixClient = exports.RoomVersionStability = exports.PendingEventOrdering = exports.CRYPTO_ENABLED = void 0;
/**
 * This is an internal module. See {@link MatrixClient} for the public class.
 * @module client
 */
const events_1 = require("events");
const sync_1 = require("./sync");
const event_1 = require("./models/event");
const stub_1 = require("./store/stub");
const call_1 = require("./webrtc/call");
const filter_1 = require("./filter");
const callEventHandler_1 = require("./webrtc/callEventHandler");
const utils = __importStar(require("./utils"));
const utils_1 = require("./utils");
const event_timeline_1 = require("./models/event-timeline");
const pushprocessor_1 = require("./pushprocessor");
const autodiscovery_1 = require("./autodiscovery");
const olmlib = __importStar(require("./crypto/olmlib"));
const olmlib_1 = require("./crypto/olmlib");
const ReEmitter_1 = require("./ReEmitter");
const RoomList_1 = require("./crypto/RoomList");
const logger_1 = require("./logger");
const service_types_1 = require("./service-types");
const http_api_1 = require("./http-api");
const crypto_1 = require("./crypto");
const recoverykey_1 = require("./crypto/recoverykey");
const key_passphrase_1 = require("./crypto/key_passphrase");
const user_1 = require("./models/user");
const content_repo_1 = require("./content-repo");
const search_result_1 = require("./models/search-result");
const dehydration_1 = require("./crypto/dehydration");
const matrix_1 = require("./matrix");
const sync_api_1 = require("./sync.api");
const ContentHelpers = __importStar(require("./content-helpers"));
const api_1 = require("./crypto/api");
const event_2 = require("./@types/event");
const partials_1 = require("./@types/partials");
const event_mapper_1 = require("./event-mapper");
const url_1 = __importDefault(require("url"));
const randomstring_1 = require("./randomstring");
const backup_1 = require("./crypto/backup");
const MSC3089TreeSpace_1 = require("./models/MSC3089TreeSpace");
const SCROLLBACK_DELAY_MS = 3000;
exports.CRYPTO_ENABLED = crypto_1.isCryptoAvailable();
const CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value
const TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes
var PendingEventOrdering;
(function (PendingEventOrdering) {
    PendingEventOrdering["Chronological"] = "chronological";
    PendingEventOrdering["Detached"] = "detached";
})(PendingEventOrdering = exports.PendingEventOrdering || (exports.PendingEventOrdering = {}));
var RoomVersionStability;
(function (RoomVersionStability) {
    RoomVersionStability["Stable"] = "stable";
    RoomVersionStability["Unstable"] = "unstable";
})(RoomVersionStability = exports.RoomVersionStability || (exports.RoomVersionStability = {}));
var CrossSigningKeyType;
(function (CrossSigningKeyType) {
    CrossSigningKeyType["MasterKey"] = "master_key";
    CrossSigningKeyType["SelfSigningKey"] = "self_signing_key";
    CrossSigningKeyType["UserSigningKey"] = "user_signing_key";
})(CrossSigningKeyType || (CrossSigningKeyType = {}));
/**
 * Represents a Matrix Client. Only directly construct this if you want to use
 * custom modules. Normally, {@link createClient} should be used
 * as it specifies 'sensible' defaults for these modules.
 */
class MatrixClient extends events_1.EventEmitter {
    constructor(opts) {
        super();
        this.reEmitter = new ReEmitter_1.ReEmitter(this);
        this.olmVersion = null; // populated after initCrypto
        this.usingExternalCrypto = false;
        this.clientRunning = false;
        this.timelineSupport = false;
        this.urlPreviewCache = {}; // TODO: Types
        this.unstableClientRelationAggregation = false;
        this.supportsCallTransfer = false; // XXX: Intended private, used in code.
        this.forceTURN = false; // XXX: Intended private, used in code.
        this.iceCandidatePoolSize = 0; // XXX: Intended private, used in code.
        // Note: these are all `protected` to let downstream consumers make mistakes if they want to.
        // We don't technically support this usage, but have reasons to do this.
        this.canSupportVoip = false;
        this.peekSync = null;
        this.isGuestAccount = false;
        this.ongoingScrollbacks = {}; // TODO: Types
        this.notifTimelineSet = null;
        this.fallbackICEServerAllowed = false;
        this.syncedLeftRooms = false;
        // The pushprocessor caches useful things, so keep one and re-use it
        this.pushProcessor = new pushprocessor_1.PushProcessor(this);
        this.turnServers = []; // TODO: Types
        this.turnServersExpiry = 0;
        this.txnCtr = 0;
        this.startCallEventHandler = () => {
            if (this.isInitialSyncComplete()) {
                this.callEventHandler.start();
                this.off("sync", this.startCallEventHandler);
            }
        };
        opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);
        opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);
        this.baseUrl = opts.baseUrl;
        this.idBaseUrl = opts.idBaseUrl;
        this.usingExternalCrypto = opts.usingExternalCrypto;
        this.store = opts.store || new stub_1.StubStore();
        this.deviceId = opts.deviceId || null;
        const userId = opts.userId || null;
        this.credentials = { userId };
        this.http = new http_api_1.MatrixHttpApi(this, {
            baseUrl: opts.baseUrl,
            idBaseUrl: opts.idBaseUrl,
            accessToken: opts.accessToken,
            request: opts.request,
            prefix: http_api_1.PREFIX_R0,
            onlyData: true,
            extraParams: opts.queryParams,
            localTimeoutMs: opts.localTimeoutMs,
            useAuthorizationHeader: opts.useAuthorizationHeader,
        });
        if (opts.deviceToImport) {
            if (this.deviceId) {
                logger_1.logger.warn('not importing device because device ID is provided to ' +
                    'constructor independently of exported data');
            }
            else if (this.credentials.userId) {
                logger_1.logger.warn('not importing device because user ID is provided to ' +
                    'constructor independently of exported data');
            }
            else if (!opts.deviceToImport.deviceId) {
                logger_1.logger.warn('not importing device because no device ID in exported data');
            }
            else {
                this.deviceId = opts.deviceToImport.deviceId;
                this.credentials.userId = opts.deviceToImport.userId;
                // will be used during async initialization of the crypto
                this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;
            }
        }
        else if (opts.pickleKey) {
            this.pickleKey = opts.pickleKey;
        }
        this.scheduler = opts.scheduler;
        if (this.scheduler) {
            this.scheduler.setProcessFunction((eventToSend) => __awaiter(this, void 0, void 0, function* () {
                const room = this.getRoom(eventToSend.getRoomId());
                if (eventToSend.status !== event_1.EventStatus.SENDING) {
                    this.updatePendingEventStatus(room, eventToSend, event_1.EventStatus.SENDING);
                }
                const res = yield this.sendEventHttpRequest(eventToSend);
                if (room) {
                    // ensure we update pending event before the next scheduler run so that any listeners to event id
                    // updates on the synchronous event emitter get a chance to run first.
                    room.updatePendingEvent(eventToSend, event_1.EventStatus.SENT, res.event_id);
                }
                return res;
            }));
        }
        // try constructing a MatrixCall to see if we are running in an environment
        // which has WebRTC. If we are, listen for and handle m.call.* events.
        const call = call_1.createNewMatrixCall(this, undefined, undefined);
        if (call) {
            this.callEventHandler = new callEventHandler_1.CallEventHandler(this);
            this.canSupportVoip = true;
            // Start listening for calls after the initial sync is done
            // We do not need to backfill the call event buffer
            // with encrypted events that might never get decrypted
            this.on("sync", this.startCallEventHandler);
        }
        this.timelineSupport = Boolean(opts.timelineSupport);
        this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;
        this.cryptoStore = opts.cryptoStore;
        this.sessionStore = opts.sessionStore;
        this.verificationMethods = opts.verificationMethods;
        this.cryptoCallbacks = opts.cryptoCallbacks || {};
        this.forceTURN = opts.forceTURN || false;
        this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;
        this.supportsCallTransfer = opts.supportsCallTransfer || false;
        this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;
        // List of which rooms have encryption enabled: separate from crypto because
        // we still want to know which rooms are encrypted even if crypto is disabled:
        // we don't want to start sending unencrypted events to them.
        this.roomList = new RoomList_1.RoomList(this.cryptoStore);
        // The SDK doesn't really provide a clean way for events to recalculate the push
        // actions for themselves, so we have to kinda help them out when they are encrypted.
        // We do this so that push rules are correctly executed on events in their decrypted
        // state, such as highlights when the user's name is mentioned.
        this.on("Event.decrypted", (event) => {
            const oldActions = event.getPushActions();
            const actions = this.pushProcessor.actionsForEvent(event);
            event.setPushActions(actions); // Might as well while we're here
            const room = this.getRoom(event.getRoomId());
            if (!room)
                return;
            const currentCount = room.getUnreadNotificationCount(matrix_1.NotificationCountType.Highlight);
            // Ensure the unread counts are kept up to date if the event is encrypted
            // We also want to make sure that the notification count goes up if we already
            // have encrypted events to avoid other code from resetting 'highlight' to zero.
            const oldHighlight = oldActions && oldActions.tweaks
                ? !!oldActions.tweaks.highlight : false;
            const newHighlight = actions && actions.tweaks
                ? !!actions.tweaks.highlight : false;
            if (oldHighlight !== newHighlight || currentCount > 0) {
                // TODO: Handle mentions received while the client is offline
                // See also https://github.com/vector-im/element-web/issues/9069
                if (!room.hasUserReadEvent(this.getUserId(), event.getId())) {
                    let newCount = currentCount;
                    if (newHighlight && !oldHighlight)
                        newCount++;
                    if (!newHighlight && oldHighlight)
                        newCount--;
                    room.setUnreadNotificationCount(matrix_1.NotificationCountType.Highlight, newCount);
                    // Fix 'Mentions Only' rooms from not having the right badge count
                    const totalCount = room.getUnreadNotificationCount(matrix_1.NotificationCountType.Total);
                    if (totalCount < newCount) {
                        room.setUnreadNotificationCount(matrix_1.NotificationCountType.Total, newCount);
                    }
                }
            }
        });
        // Like above, we have to listen for read receipts from ourselves in order to
        // correctly handle notification counts on encrypted rooms.
        // This fixes https://github.com/vector-im/element-web/issues/9421
        this.on("Room.receipt", (event, room) => {
            if (room && this.isRoomEncrypted(room.roomId)) {
                // Figure out if we've read something or if it's just informational
                const content = event.getContent();
                const isSelf = Object.keys(content).filter(eid => {
                    return Object.keys(content[eid]['m.read']).includes(this.getUserId());
                }).length > 0;
                if (!isSelf)
                    return;
                // Work backwards to determine how many events are unread. We also set
                // a limit for how back we'll look to avoid spinning CPU for too long.
                // If we hit the limit, we assume the count is unchanged.
                const maxHistory = 20;
                const events = room.getLiveTimeline().getEvents();
                let highlightCount = 0;
                for (let i = events.length - 1; i >= 0; i--) {
                    if (i === events.length - maxHistory)
                        return; // limit reached
                    const event = events[i];
                    if (room.hasUserReadEvent(this.getUserId(), event.getId())) {
                        // If the user has read the event, then the counting is done.
                        break;
                    }
                    const pushActions = this.getPushActionsForEvent(event);
                    highlightCount += pushActions.tweaks &&
                        pushActions.tweaks.highlight ? 1 : 0;
                }
                // Note: we don't need to handle 'total' notifications because the counts
                // will come from the server.
                room.setUnreadNotificationCount("highlight", highlightCount);
            }
        });
    }
    /**
     * High level helper method to begin syncing and poll for new events. To listen for these
     * events, add a listener for {@link module:client~MatrixClient#event:"event"}
     * via {@link module:client~MatrixClient#on}. Alternatively, listen for specific
     * state change events.
     * @param {Object=} opts Options to apply when syncing.
     */
    startClient(opts) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.clientRunning) {
                // client is already running.
                return;
            }
            this.clientRunning = true;
            // backwards compat for when 'opts' was 'historyLen'.
            if (typeof opts === "number") {
                opts = {
                    initialSyncLimit: opts,
                };
            }
            // Create our own user object artificially (instead of waiting for sync)
            // so it's always available, even if the user is not in any rooms etc.
            const userId = this.getUserId();
            if (userId) {
                this.store.storeUser(new user_1.User(userId));
            }
            if (this.crypto) {
                this.crypto.uploadDeviceKeys();
                this.crypto.start();
            }
            // periodically poll for turn servers if we support voip
            if (this.canSupportVoip) {
                this.checkTurnServersIntervalID = setInterval(() => {
                    this.checkTurnServers();
                }, TURN_CHECK_INTERVAL); // XXX: Typecast because we know better
                // noinspection ES6MissingAwait
                this.checkTurnServers();
            }
            if (this.syncApi) {
                // This shouldn't happen since we thought the client was not running
                logger_1.logger.error("Still have sync object whilst not running: stopping old one");
                this.syncApi.stop();
            }
            // shallow-copy the opts dict before modifying and storing it
            this.clientOpts = Object.assign({}, opts); // XXX: Typecast because we're about to add the missing props
            this.clientOpts.crypto = this.crypto;
            this.clientOpts.canResetEntireTimeline = (roomId) => {
                if (!this.canResetTimelineCallback) {
                    return false;
                }
                return this.canResetTimelineCallback(roomId);
            };
            this.syncApi = new sync_1.SyncApi(this, this.clientOpts);
            this.syncApi.sync();
            if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {
                this.clientWellKnownIntervalID =
                    // XXX: Typecast on timer ID because we know better
                    setInterval(() => {
                        this.fetchClientWellKnown();
                    }, 1000 * this.clientOpts.clientWellKnownPollPeriod);
                this.fetchClientWellKnown();
            }
        });
    }
    /**
     * High level helper method to stop the client from polling and allow a
     * clean shutdown.
     */
    stopClient() {
        var _a, _b, _c, _d;
        logger_1.logger.log('stopping MatrixClient');
        this.clientRunning = false;
        (_a = this.syncApi) === null || _a === void 0 ? void 0 : _a.stop();
        this.syncApi = null;
        (_b = this.crypto) === null || _b === void 0 ? void 0 : _b.stop();
        (_c = this.peekSync) === null || _c === void 0 ? void 0 : _c.stopPeeking();
        (_d = this.callEventHandler) === null || _d === void 0 ? void 0 : _d.stop();
        this.callEventHandler = null;
        global.clearInterval(this.checkTurnServersIntervalID);
        if (this.clientWellKnownIntervalID !== undefined) {
            global.clearInterval(this.clientWellKnownIntervalID);
        }
    }
    /**
     * Try to rehydrate a device if available.  The client must have been
     * initialized with a `cryptoCallback.getDehydrationKey` option, and this
     * function must be called before initCrypto and startClient are called.
     *
     * @return {Promise<string>} Resolves to undefined if a device could not be dehydrated, or
     *     to the new device ID if the dehydration was successful.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    rehydrateDevice() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.crypto) {
                throw new Error("Cannot rehydrate device after crypto is initialized");
            }
            if (!this.cryptoCallbacks.getDehydrationKey) {
                return;
            }
            const getDeviceResult = yield this.getDehydratedDevice();
            if (!getDeviceResult) {
                return;
            }
            if (!getDeviceResult.device_data || !getDeviceResult.device_id) {
                logger_1.logger.info("no dehydrated device found");
                return;
            }
            const account = new global.Olm.Account();
            try {
                const deviceData = getDeviceResult.device_data;
                if (deviceData.algorithm !== dehydration_1.DEHYDRATION_ALGORITHM) {
                    logger_1.logger.warn("Wrong algorithm for dehydrated device");
                    return;
                }
                logger_1.logger.log("unpickling dehydrated device");
                const key = yield this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => {
                    // copy the key so that it doesn't get clobbered
                    account.unpickle(new Uint8Array(k), deviceData.account);
                });
                account.unpickle(key, deviceData.account);
                logger_1.logger.log("unpickled device");
                const rehydrateResult = yield this.http.authedRequest(undefined, "POST", "/dehydrated_device/claim", undefined, {
                    device_id: getDeviceResult.device_id,
                }, {
                    prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2",
                });
                if (rehydrateResult.success === true) {
                    this.deviceId = getDeviceResult.device_id;
                    logger_1.logger.info("using dehydrated device");
                    const pickleKey = this.pickleKey || "DEFAULT_KEY";
                    this.exportedOlmDeviceToImport = {
                        pickledAccount: account.pickle(pickleKey),
                        sessions: [],
                        pickleKey: pickleKey,
                    };
                    account.free();
                    return this.deviceId;
                }
                else {
                    account.free();
                    logger_1.logger.info("not using dehydrated device");
                    return;
                }
            }
            catch (e) {
                account.free();
                logger_1.logger.warn("could not unpickle", e);
            }
        });
    }
    /**
     * Get the current dehydrated device, if any
     * @return {Promise} A promise of an object containing the dehydrated device
     */
    getDehydratedDevice() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.http.authedRequest(undefined, "GET", "/dehydrated_device", undefined, undefined, {
                    prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2",
                });
            }
            catch (e) {
                logger_1.logger.info("could not get dehydrated device", e.toString());
                return;
            }
        });
    }
    /**
     * Set the dehydration key.  This will also periodically dehydrate devices to
     * the server.
     *
     * @param {Uint8Array} key the dehydration key
     * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key.  Primarily for
     *     information about how to generate the key from a passphrase.
     * @param {string} [deviceDisplayName] The device display name for the
     *     dehydrated device.
     * @return {Promise} A promise that resolves when the dehydrated device is stored.
     */
    setDehydrationKey(key, keyInfo, deviceDisplayName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                logger_1.logger.warn('not dehydrating device if crypto is not enabled');
                return;
            }
            // XXX: Private member access.
            return yield this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName);
        });
    }
    /**
     * Creates a new dehydrated device (without queuing periodic dehydration)
     * @param {Uint8Array} key the dehydration key
     * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key.  Primarily for
     *     information about how to generate the key from a passphrase.
     * @param {string} [deviceDisplayName] The device display name for the
     *     dehydrated device.
     * @return {Promise<String>} the device id of the newly created dehydrated device
     */
    createDehydratedDevice(key, keyInfo, deviceDisplayName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                logger_1.logger.warn('not dehydrating device if crypto is not enabled');
                return;
            }
            yield this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName);
            // XXX: Private member access.
            return yield this.crypto.dehydrationManager.dehydrateDevice();
        });
    }
    exportDevice() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                logger_1.logger.warn('not exporting device if crypto is not enabled');
                return;
            }
            return {
                userId: this.credentials.userId,
                deviceId: this.deviceId,
                // XXX: Private member access.
                olmDevice: yield this.crypto.olmDevice.export(),
            };
        });
    }
    /**
     * Clear any data out of the persistent stores used by the client.
     *
     * @returns {Promise} Promise which resolves when the stores have been cleared.
     */
    clearStores() {
        if (this.clientRunning) {
            throw new Error("Cannot clear stores while client is running");
        }
        const promises = [];
        promises.push(this.store.deleteAllData());
        if (this.cryptoStore) {
            promises.push(this.cryptoStore.deleteAllData());
        }
        return Promise.all(promises).then(); // .then to fix types
    }
    /**
     * Get the user-id of the logged-in user
     *
     * @return {?string} MXID for the logged-in user, or null if not logged in
     */
    getUserId() {
        if (this.credentials && this.credentials.userId) {
            return this.credentials.userId;
        }
        return null;
    }
    /**
     * Get the domain for this client's MXID
     * @return {?string} Domain of this MXID
     */
    getDomain() {
        if (this.credentials && this.credentials.userId) {
            return this.credentials.userId.replace(/^.*?:/, '');
        }
        return null;
    }
    /**
     * Get the local part of the current user ID e.g. "foo" in "@foo:bar".
     * @return {?string} The user ID localpart or null.
     */
    getUserIdLocalpart() {
        if (this.credentials && this.credentials.userId) {
            return this.credentials.userId.split(":")[0].substring(1);
        }
        return null;
    }
    /**
     * Get the device ID of this client
     * @return {?string} device ID
     */
    getDeviceId() {
        return this.deviceId;
    }
    /**
     * Check if the runtime environment supports VoIP calling.
     * @return {boolean} True if VoIP is supported.
     */
    supportsVoip() {
        return this.canSupportVoip;
    }
    /**
     * Set whether VoIP calls are forced to use only TURN
     * candidates. This is the same as the forceTURN option
     * when creating the client.
     * @param {boolean} force True to force use of TURN servers
     */
    setForceTURN(force) {
        this.forceTURN = force;
    }
    /**
     * Set whether to advertise transfer support to other parties on Matrix calls.
     * @param {boolean} support True to advertise the 'm.call.transferee' capability
     */
    setSupportsCallTransfer(support) {
        this.supportsCallTransfer = support;
    }
    getLocalVideoStream() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.localAVStreamType === call_1.ConstraintsType.Video) {
                return this.localAVStream.clone();
            }
            const constraints = call_1.getUserMediaContraints(call_1.ConstraintsType.Video);
            logger_1.logger.log("Getting user media with constraints", constraints);
            const mediaStream = yield navigator.mediaDevices.getUserMedia(constraints);
            this.localAVStreamType = call_1.ConstraintsType.Video;
            this.localAVStream = mediaStream;
            return mediaStream;
        });
    }
    getLocalAudioStream() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.localAVStreamType === call_1.ConstraintsType.Audio) {
                return this.localAVStream.clone();
            }
            const constraints = call_1.getUserMediaContraints(call_1.ConstraintsType.Audio);
            logger_1.logger.log("Getting user media with constraints", constraints);
            const mediaStream = yield navigator.mediaDevices.getUserMedia(constraints);
            this.localAVStreamType = call_1.ConstraintsType.Audio;
            this.localAVStream = mediaStream;
            return mediaStream;
        });
    }
    stopLocalMediaStream() {
        if (this.localAVStream) {
            for (const track of this.localAVStream.getTracks()) {
                track.stop();
            }
            this.localAVStreamType = null;
            this.localAVStream = null;
        }
    }
    /**
     * Creates a new call.
     * The place*Call methods on the returned call can be used to actually place a call
     *
     * @param {string} roomId The room the call is to be placed in.
     * @param {string} invitee The user to call in the given room.
     * @return {MatrixCall} the call or null if the browser doesn't support calling.
     */
    createCall(roomId, invitee) {
        return call_1.createNewMatrixCall(this, roomId, { invitee });
    }
    /**
     * Get the current sync state.
     * @return {?SyncState} the sync state, which may be null.
     * @see module:client~MatrixClient#event:"sync"
     */
    getSyncState() {
        if (!this.syncApi) {
            return null;
        }
        return this.syncApi.getSyncState();
    }
    /**
     * Returns the additional data object associated with
     * the current sync state, or null if there is no
     * such data.
     * Sync errors, if available, are put in the 'error' key of
     * this object.
     * @return {?Object}
     */
    getSyncStateData() {
        if (!this.syncApi) {
            return null;
        }
        return this.syncApi.getSyncStateData();
    }
    /**
     * Whether the initial sync has completed.
     * @return {boolean} True if at least one sync has happened.
     */
    isInitialSyncComplete() {
        const state = this.getSyncState();
        if (!state) {
            return false;
        }
        return state === sync_api_1.SyncState.Prepared || state === sync_api_1.SyncState.Syncing;
    }
    /**
     * Return whether the client is configured for a guest account.
     * @return {boolean} True if this is a guest access_token (or no token is supplied).
     */
    isGuest() {
        return this.isGuestAccount;
    }
    /**
     * Set whether this client is a guest account. <b>This method is experimental
     * and may change without warning.</b>
     * @param {boolean} guest True if this is a guest account.
     */
    setGuest(guest) {
        // EXPERIMENTAL:
        // If the token is a macaroon, it should be encoded in it that it is a 'guest'
        // access token, which means that the SDK can determine this entirely without
        // the dev manually flipping this flag.
        this.isGuestAccount = guest;
    }
    /**
     * Return the provided scheduler, if any.
     * @return {?module:scheduler~MatrixScheduler} The scheduler or null
     */
    getScheduler() {
        return this.scheduler;
    }
    /**
     * Retry a backed off syncing request immediately. This should only be used when
     * the user <b>explicitly</b> attempts to retry their lost connection.
     * @return {boolean} True if this resulted in a request being retried.
     */
    retryImmediately() {
        return this.syncApi.retryImmediately();
    }
    /**
     * Return the global notification EventTimelineSet, if any
     *
     * @return {EventTimelineSet} the globl notification EventTimelineSet
     */
    getNotifTimelineSet() {
        return this.notifTimelineSet;
    }
    /**
     * Set the global notification EventTimelineSet
     *
     * @param {EventTimelineSet} set
     */
    setNotifTimelineSet(set) {
        this.notifTimelineSet = set;
    }
    /**
     * Gets the capabilities of the homeserver. Always returns an object of
     * capability keys and their options, which may be empty.
     * @param {boolean} fresh True to ignore any cached values.
     * @return {Promise} Resolves to the capabilities of the homeserver
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getCapabilities(fresh = false) {
        const now = new Date().getTime();
        if (this.cachedCapabilities && !fresh) {
            if (now < this.cachedCapabilities.expiration) {
                logger_1.logger.log("Returning cached capabilities");
                return Promise.resolve(this.cachedCapabilities.capabilities);
            }
        }
        // We swallow errors because we need a default object anyhow
        return this.http.authedRequest(undefined, "GET", "/capabilities").catch((e) => {
            logger_1.logger.error(e);
            return null; // otherwise consume the error
        }).then((r) => {
            if (!r)
                r = {};
            const capabilities = r["capabilities"] || {};
            // If the capabilities missed the cache, cache it for a shorter amount
            // of time to try and refresh them later.
            const cacheMs = Object.keys(capabilities).length
                ? CAPABILITIES_CACHE_MS
                : 60000 + (Math.random() * 5000);
            this.cachedCapabilities = {
                capabilities,
                expiration: now + cacheMs,
            };
            logger_1.logger.log("Caching capabilities: ", capabilities);
            return capabilities;
        });
    }
    /**
     * Initialise support for end-to-end encryption in this client
     *
     * You should call this method after creating the matrixclient, but *before*
     * calling `startClient`, if you want to support end-to-end encryption.
     *
     * It will return a Promise which will resolve when the crypto layer has been
     * successfully initialised.
     */
    initCrypto() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!crypto_1.isCryptoAvailable()) {
                throw new Error(`End-to-end encryption not supported in this js-sdk build: did ` +
                    `you remember to load the olm library?`);
            }
            if (this.crypto) {
                logger_1.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");
                return;
            }
            if (!this.sessionStore) {
                // this is temporary, the sessionstore is supposed to be going away
                throw new Error(`Cannot enable encryption: no sessionStore provided`);
            }
            if (!this.cryptoStore) {
                // the cryptostore is provided by sdk.createClient, so this shouldn't happen
                throw new Error(`Cannot enable encryption: no cryptoStore provided`);
            }
            logger_1.logger.log("Crypto: Starting up crypto store...");
            yield this.cryptoStore.startup();
            // initialise the list of encrypted rooms (whether or not crypto is enabled)
            logger_1.logger.log("Crypto: initialising roomlist...");
            yield this.roomList.init();
            const userId = this.getUserId();
            if (userId === null) {
                throw new Error(`Cannot enable encryption on MatrixClient with unknown userId: ` +
                    `ensure userId is passed in createClient().`);
            }
            if (this.deviceId === null) {
                throw new Error(`Cannot enable encryption on MatrixClient with unknown deviceId: ` +
                    `ensure deviceId is passed in createClient().`);
            }
            const crypto = new crypto_1.Crypto(this, this.sessionStore, userId, this.deviceId, this.store, this.cryptoStore, this.roomList, this.verificationMethods);
            this.reEmitter.reEmit(crypto, [
                "crypto.keyBackupFailed",
                "crypto.keyBackupSessionsRemaining",
                "crypto.roomKeyRequest",
                "crypto.roomKeyRequestCancellation",
                "crypto.warning",
                "crypto.devicesUpdated",
                "crypto.willUpdateDevices",
                "deviceVerificationChanged",
                "userTrustStatusChanged",
                "crossSigning.keysChanged",
            ]);
            logger_1.logger.log("Crypto: initialising crypto object...");
            yield crypto.init({
                exportedOlmDevice: this.exportedOlmDeviceToImport,
                pickleKey: this.pickleKey,
            });
            delete this.exportedOlmDeviceToImport;
            this.olmVersion = crypto_1.Crypto.getOlmVersion();
            // if crypto initialisation was successful, tell it to attach its event
            // handlers.
            crypto.registerEventHandlers(this);
            this.crypto = crypto;
        });
    }
    /**
     * Is end-to-end crypto enabled for this client.
     * @return {boolean} True if end-to-end is enabled.
     */
    isCryptoEnabled() {
        return !!this.crypto;
    }
    /**
     * Get the Ed25519 key for this device
     *
     * @return {?string} base64-encoded ed25519 key. Null if crypto is
     *    disabled.
     */
    getDeviceEd25519Key() {
        if (!this.crypto)
            return null;
        return this.crypto.getDeviceEd25519Key();
    }
    /**
     * Get the Curve25519 key for this device
     *
     * @return {?string} base64-encoded curve25519 key. Null if crypto is
     *    disabled.
     */
    getDeviceCurve25519Key() {
        if (!this.crypto)
            return null;
        return this.crypto.getDeviceCurve25519Key();
    }
    /**
     * Upload the device keys to the homeserver.
     * @return {Promise<void>} A promise that will resolve when the keys are uploaded.
     */
    uploadKeys() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            yield this.crypto.uploadDeviceKeys();
        });
    }
    /**
     * Download the keys for a list of users and stores the keys in the session
     * store.
     * @param {Array} userIds The users to fetch.
     * @param {boolean} forceDownload Always download the keys even if cached.
     *
     * @return {Promise} A promise which resolves to a map userId->deviceId->{@link
        * module:crypto~DeviceInfo|DeviceInfo}.
     */
    downloadKeys(userIds, forceDownload) {
        if (!this.crypto) {
            return Promise.reject(new Error("End-to-end encryption disabled"));
        }
        return this.crypto.downloadKeys(userIds, forceDownload);
    }
    /**
     * Get the stored device keys for a user id
     *
     * @param {string} userId the user to list keys for.
     *
     * @return {module:crypto/deviceinfo[]} list of devices
     */
    getStoredDevicesForUser(userId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getStoredDevicesForUser(userId) || [];
    }
    /**
     * Get the stored device key for a user id and device id
     *
     * @param {string} userId the user to list keys for.
     * @param {string} deviceId unique identifier for the device
     *
     * @return {module:crypto/deviceinfo} device or null
     */
    getStoredDevice(userId, deviceId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getStoredDevice(userId, deviceId) || null;
    }
    /**
     * Mark the given device as verified
     *
     * @param {string} userId owner of the device
     * @param {string} deviceId unique identifier for the device or user's
     * cross-signing public key ID.
     *
     * @param {boolean=} verified whether to mark the device as verified. defaults
     *   to 'true'.
     *
     * @returns {Promise}
     *
     * @fires module:client~event:MatrixClient"deviceVerificationChanged"
     */
    setDeviceVerified(userId, deviceId, verified = true) {
        const prom = this.setDeviceVerification(userId, deviceId, verified, null, null);
        // if one of the user's own devices is being marked as verified / unverified,
        // check the key backup status, since whether or not we use this depends on
        // whether it has a signature from a verified device
        if (userId == this.credentials.userId) {
            this.checkKeyBackup();
        }
        return prom;
    }
    /**
     * Mark the given device as blocked/unblocked
     *
     * @param {string} userId owner of the device
     * @param {string} deviceId unique identifier for the device or user's
     * cross-signing public key ID.
     *
     * @param {boolean=} blocked whether to mark the device as blocked. defaults
     *   to 'true'.
     *
     * @returns {Promise}
     *
     * @fires module:client~event:MatrixClient"deviceVerificationChanged"
     */
    setDeviceBlocked(userId, deviceId, blocked = true) {
        return this.setDeviceVerification(userId, deviceId, null, blocked, null);
    }
    /**
     * Mark the given device as known/unknown
     *
     * @param {string} userId owner of the device
     * @param {string} deviceId unique identifier for the device or user's
     * cross-signing public key ID.
     *
     * @param {boolean=} known whether to mark the device as known. defaults
     *   to 'true'.
     *
     * @returns {Promise}
     *
     * @fires module:client~event:MatrixClient"deviceVerificationChanged"
     */
    setDeviceKnown(userId, deviceId, known = true) {
        return this.setDeviceVerification(userId, deviceId, null, null, known);
    }
    setDeviceVerification(userId, deviceId, verified, blocked, known) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            yield this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);
        });
    }
    /**
     * Request a key verification from another user, using a DM.
     *
     * @param {string} userId the user to request verification with
     * @param {string} roomId the room to use for verification
     *
     * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest
     *    when the request has been sent to the other party.
     */
    requestVerificationDM(userId, roomId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.requestVerificationDM(userId, roomId);
    }
    /**
     * Finds a DM verification request that is already in progress for the given room id
     *
     * @param {string} roomId the room to use for verification
     *
     * @returns {module:crypto/verification/request/VerificationRequest?} the VerificationRequest that is in progress, if any
     */
    findVerificationRequestDMInProgress(roomId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.findVerificationRequestDMInProgress(roomId);
    }
    /**
     * Returns all to-device verification requests that are already in progress for the given user id
     *
     * @param {string} userId the ID of the user to query
     *
     * @returns {module:crypto/verification/request/VerificationRequest[]} the VerificationRequests that are in progress
     */
    getVerificationRequestsToDeviceInProgress(userId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getVerificationRequestsToDeviceInProgress(userId);
    }
    /**
     * Request a key verification from another user.
     *
     * @param {string} userId the user to request verification with
     * @param {Array} devices array of device IDs to send requests to.  Defaults to
     *    all devices owned by the user
     *
     * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest
     *    when the request has been sent to the other party.
     */
    requestVerification(userId, devices) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.requestVerification(userId, devices);
    }
    /**
     * Begin a key verification.
     *
     * @param {string} method the verification method to use
     * @param {string} userId the user to verify keys with
     * @param {string} deviceId the device to verify
     *
     * @returns {Verification} a verification object
     */
    beginKeyVerification(method, userId, deviceId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.beginKeyVerification(method, userId, deviceId);
    }
    checkSecretStorageKey(key, info) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkSecretStorageKey(key, info);
    }
    /**
     * Set the global override for whether the client should ever send encrypted
     * messages to unverified devices.  This provides the default for rooms which
     * do not specify a value.
     *
     * @param {boolean} value whether to blacklist all unverified devices by default
     */
    setGlobalBlacklistUnverifiedDevices(value) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.setGlobalBlacklistUnverifiedDevices(value);
    }
    /**
     * @return {boolean} whether to blacklist all unverified devices by default
     */
    getGlobalBlacklistUnverifiedDevices() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getGlobalBlacklistUnverifiedDevices();
    }
    /**
     * Set whether sendMessage in a room with unknown and unverified devices
     * should throw an error and not send them message. This has 'Global' for
     * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently
     * no room-level equivalent for this setting.
     *
     * This API is currently UNSTABLE and may change or be removed without notice.
     *
     * @param {boolean} value whether error on unknown devices
     */
    setGlobalErrorOnUnknownDevices(value) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.setGlobalErrorOnUnknownDevices(value);
    }
    /**
     * @return {boolean} whether to error on unknown devices
     *
     * This API is currently UNSTABLE and may change or be removed without notice.
     */
    getGlobalErrorOnUnknownDevices() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getGlobalErrorOnUnknownDevices();
    }
    /**
     * Get the user's cross-signing key ID.
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {CrossSigningKey} [type=master] The type of key to get the ID of.  One of
     *     "master", "self_signing", or "user_signing".  Defaults to "master".
     *
     * @returns {string} the key ID
     */
    getCrossSigningId(type = api_1.CrossSigningKey.Master) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getCrossSigningId(type);
    }
    /**
     * Get the cross signing information for a given user.
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {string} userId the user ID to get the cross-signing info for.
     *
     * @returns {CrossSigningInfo} the cross signing information for the user.
     */
    getStoredCrossSigningForUser(userId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getStoredCrossSigningForUser(userId);
    }
    /**
     * Check whether a given user is trusted.
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {string} userId The ID of the user to check.
     *
     * @returns {UserTrustLevel}
     */
    checkUserTrust(userId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkUserTrust(userId);
    }
    /**
     * Check whether a given device is trusted.
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @function module:client~MatrixClient#checkDeviceTrust
     * @param {string} userId The ID of the user whose devices is to be checked.
     * @param {string} deviceId The ID of the device to check
     *
     * @returns {DeviceTrustLevel}
     */
    checkDeviceTrust(userId, deviceId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkDeviceTrust(userId, deviceId);
    }
    /**
     * Check the copy of our cross-signing key that we have in the device list and
     * see if we can get the private key. If so, mark it as trusted.
     * @param {Object} opts TODO
     */
    checkOwnCrossSigningTrust(opts) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkOwnCrossSigningTrust(opts);
    }
    /**
     * Checks that a given cross-signing private key matches a given public key.
     * This can be used by the getCrossSigningKey callback to verify that the
     * private key it is about to supply is the one that was requested.
     * @param {Uint8Array} privateKey The private key
     * @param {string} expectedPublicKey The public key
     * @returns {boolean} true if the key matches, otherwise false
     */
    checkCrossSigningPrivateKey(privateKey, expectedPublicKey) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey);
    }
    legacyDeviceVerification(userId, deviceId, method) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.legacyDeviceVerification(userId, deviceId, method);
    }
    /**
     * Perform any background tasks that can be done before a message is ready to
     * send, in order to speed up sending of the message.
     * @param {module:models/room} room the room the event is in
     */
    prepareToEncrypt(room) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.prepareToEncrypt(room);
    }
    /**
     * Checks whether cross signing:
     * - is enabled on this account and trusted by this device
     * - has private keys either cached locally or stored in secret storage
     *
     * If this function returns false, bootstrapCrossSigning() can be used
     * to fix things such that it returns true. That is to say, after
     * bootstrapCrossSigning() completes successfully, this function should
     * return true.
     * @return {boolean} True if cross-signing is ready to be used on this device
     */
    isCrossSigningReady() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.isCrossSigningReady();
    }
    /**
     * Bootstrap cross-signing by creating keys if needed. If everything is already
     * set up, then no changes are made, so this is safe to run to ensure
     * cross-signing is ready for use.
     *
     * This function:
     * - creates new cross-signing keys if they are not found locally cached nor in
     *   secret storage (if it has been setup)
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {function} opts.authUploadDeviceSigningKeys Function
     * called to await an interactive auth flow when uploading device signing keys.
     * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys
     * already exist.
     * Args:
     *     {function} A function that makes the request requiring auth. Receives the
     *     auth data as an object. Can be called multiple times, first with an empty
     *     authDict, to obtain the flows.
     */
    bootstrapCrossSigning(opts) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.bootstrapCrossSigning(opts);
    }
    /**
     * Whether to trust a others users signatures of their devices.
     * If false, devices will only be considered 'verified' if we have
     * verified that device individually (effectively disabling cross-signing).
     *
     * Default: true
     *
     * @return {boolean} True if trusting cross-signed devices
     */
    getCryptoTrustCrossSignedDevices() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getCryptoTrustCrossSignedDevices();
    }
    /**
     * See getCryptoTrustCrossSignedDevices

     * This may be set before initCrypto() is called to ensure no races occur.
     *
     * @param {boolean} val True to trust cross-signed devices
     */
    setCryptoTrustCrossSignedDevices(val) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.setCryptoTrustCrossSignedDevices(val);
    }
    /**
     * Counts the number of end to end session keys that are waiting to be backed up
     * @returns {Promise<int>} Resolves to the number of sessions requiring backup
     */
    countSessionsNeedingBackup() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.countSessionsNeedingBackup();
    }
    /**
     * Get information about the encryption of an event
     *
     * @param {module:models/event.MatrixEvent} event event to be checked
     * @returns {IEncryptedEventInfo} The event information.
     */
    getEventEncryptionInfo(event) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getEventEncryptionInfo(event);
    }
    /**
     * Create a recovery key from a user-supplied passphrase.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} password Passphrase string that can be entered by the user
     *     when restoring the backup as an alternative to entering the recovery key.
     *     Optional.
     * @returns {Promise<Object>} Object with public key metadata, encoded private
     *     recovery key which should be disposed of after displaying to the user,
     *     and raw private key to avoid round tripping if needed.
     */
    createRecoveryKeyFromPassphrase(password) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.createRecoveryKeyFromPassphrase(password);
    }
    /**
     * Checks whether secret storage:
     * - is enabled on this account
     * - is storing cross-signing private keys
     * - is storing session backup key (if enabled)
     *
     * If this function returns false, bootstrapSecretStorage() can be used
     * to fix things such that it returns true. That is to say, after
     * bootstrapSecretStorage() completes successfully, this function should
     * return true.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @return {boolean} True if secret storage is ready to be used on this device
     */
    isSecretStorageReady() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.isSecretStorageReady();
    }
    /**
     * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is
     * already set up, then no changes are made, so this is safe to run to ensure secret
     * storage is ready for use.
     *
     * This function
     * - creates a new Secure Secret Storage key if no default key exists
     *   - if a key backup exists, it is migrated to store the key in the Secret
     *     Storage
     * - creates a backup if none exists, and one is requested
     * - migrates Secure Secret Storage to use the latest algorithm, if an outdated
     *   algorithm is found
     *
     * @param opts
     */
    bootstrapSecretStorage(opts) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.bootstrapSecretStorage(opts);
    }
    /**
     * Add a key for encrypting secrets.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} algorithm the algorithm used by the key
     * @param {object} opts the options for the algorithm.  The properties used
     *     depend on the algorithm given.
     * @param {string} [keyName] the name of the key.  If not given, a random name will be generated.
     *
     * @return {object} An object with:
     *     keyId: {string} the ID of the key
     *     keyInfo: {object} details about the key (iv, mac, passphrase)
     */
    addSecretStorageKey(algorithm, opts, keyName) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.addSecretStorageKey(algorithm, opts, keyName);
    }
    /**
     * Check whether we have a key with a given ID.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} [keyId = default key's ID] The ID of the key to check
     *     for. Defaults to the default key ID if not provided.
     * @return {boolean} Whether we have the key.
     */
    hasSecretStorageKey(keyId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.hasSecretStorageKey(keyId);
    }
    /**
     * Store an encrypted secret on the server.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} name The name of the secret
     * @param {string} secret The secret contents.
     * @param {Array} keys The IDs of the keys to use to encrypt the secret or null/undefined
     *     to use the default (will throw if no default key is set).
     */
    storeSecret(name, secret, keys) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.storeSecret(name, secret, keys);
    }
    /**
     * Get a secret from storage.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} name the name of the secret
     *
     * @return {string} the contents of the secret
     */
    getSecret(name) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getSecret(name);
    }
    /**
     * Check if a secret is stored on the server.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} name the name of the secret
     * @param {boolean} checkKey check if the secret is encrypted by a trusted
     *     key
     *
     * @return {object?} map of key name to key info the secret is encrypted
     *     with, or null if it is not present or not encrypted with a trusted
     *     key
     */
    isSecretStored(name, checkKey) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.isSecretStored(name, checkKey);
    }
    /**
     * Request a secret from another device.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} name the name of the secret to request
     * @param {string[]} devices the devices to request the secret from
     *
     * @return {string} the contents of the secret
     */
    requestSecret(name, devices) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.requestSecret(name, devices);
    }
    /**
     * Get the current default key ID for encrypting secrets.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @return {string} The default key ID or null if no default key ID is set
     */
    getDefaultSecretStorageKeyId() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.getDefaultSecretStorageKeyId();
    }
    /**
     * Set the current default key ID for encrypting secrets.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {string} keyId The new default key ID
     */
    setDefaultSecretStorageKeyId(keyId) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.setDefaultSecretStorageKeyId(keyId);
    }
    /**
     * Checks that a given secret storage private key matches a given public key.
     * This can be used by the getSecretStorageKey callback to verify that the
     * private key it is about to supply is the one that was requested.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {Uint8Array} privateKey The private key
     * @param {string} expectedPublicKey The public key
     * @returns {boolean} true if the key matches, otherwise false
     */
    checkSecretStoragePrivateKey(privateKey, expectedPublicKey) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey);
    }
    /**
     * Get e2e information on the device that sent an event
     *
     * @param {MatrixEvent} event event to be checked
     *
     * @return {Promise<module:crypto/deviceinfo?>}
     */
    getEventSenderDeviceInfo(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                return null;
            }
            return this.crypto.getEventSenderDeviceInfo(event);
        });
    }
    /**
     * Check if the sender of an event is verified
     *
     * @param {MatrixEvent} event event to be checked
     *
     * @return {boolean} true if the sender of this event has been verified using
     * {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}.
     */
    isEventSenderVerified(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const device = yield this.getEventSenderDeviceInfo(event);
            if (!device) {
                return false;
            }
            return device.isVerified();
        });
    }
    /**
     * Cancel a room key request for this event if one is ongoing and resend the
     * request.
     * @param  {MatrixEvent} event event of which to cancel and resend the room
     *                            key request.
     * @return {Promise} A promise that will resolve when the key request is queued
     */
    cancelAndResendEventRoomKeyRequest(event) {
        return event.cancelAndResendKeyRequest(this.crypto, this.getUserId());
    }
    /**
     * Enable end-to-end encryption for a room. This does not modify room state.
     * Any messages sent before the returned promise resolves will be sent unencrypted.
     * @param {string} roomId The room ID to enable encryption in.
     * @param {object} config The encryption config for the room.
     * @return {Promise} A promise that will resolve when encryption is set up.
     */
    setRoomEncryption(roomId, config) {
        if (!this.crypto) {
            throw new Error("End-to-End encryption disabled");
        }
        return this.crypto.setRoomEncryption(roomId, config);
    }
    /**
     * Whether encryption is enabled for a room.
     * @param {string} roomId the room id to query.
     * @return {boolean} whether encryption is enabled.
     */
    isRoomEncrypted(roomId) {
        const room = this.getRoom(roomId);
        if (!room) {
            // we don't know about this room, so can't determine if it should be
            // encrypted. Let's assume not.
            return false;
        }
        // if there is an 'm.room.encryption' event in this room, it should be
        // encrypted (independently of whether we actually support encryption)
        const ev = room.currentState.getStateEvents("m.room.encryption", "");
        if (ev) {
            return true;
        }
        // we don't have an m.room.encrypted event, but that might be because
        // the server is hiding it from us. Check the store to see if it was
        // previously encrypted.
        return this.roomList.isRoomEncrypted(roomId);
    }
    /**
     * Forces the current outbound group session to be discarded such
     * that another one will be created next time an event is sent.
     *
     * @param {string} roomId The ID of the room to discard the session for
     *
     * This should not normally be necessary.
     */
    forceDiscardSession(roomId) {
        if (!this.crypto) {
            throw new Error("End-to-End encryption disabled");
        }
        this.crypto.forceDiscardSession(roomId);
    }
    /**
     * Get a list containing all of the room keys
     *
     * This should be encrypted before returning it to the user.
     *
     * @return {Promise} a promise which resolves to a list of
     *    session export objects
     */
    exportRoomKeys() {
        if (!this.crypto) {
            return Promise.reject(new Error("End-to-end encryption disabled"));
        }
        return this.crypto.exportRoomKeys();
    }
    /**
     * Import a list of room keys previously exported by exportRoomKeys
     *
     * @param {Object[]} keys a list of session export objects
     * @param {Object} opts
     * @param {Function} opts.progressCallback called with an object that has a "stage" param
     *
     * @return {Promise} a promise which resolves when the keys
     *    have been imported
     */
    importRoomKeys(keys, opts) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.importRoomKeys(keys, opts);
    }
    /**
     * Force a re-check of the local key backup status against
     * what's on the server.
     *
     * @returns {Object} Object with backup info (as returned by
     *     getKeyBackupVersion) in backupInfo and
     *     trust information (as returned by isKeyBackupTrusted)
     *     in trustInfo.
     */
    checkKeyBackup() {
        return this.crypto.backupManager.checkKeyBackup();
    }
    /**
     * Get information about the current key backup.
     * @returns {Promise} Information object from API or null
     */
    getKeyBackupVersion() {
        return __awaiter(this, void 0, void 0, function* () {
            let res;
            try {
                res = yield this.http.authedRequest(undefined, "GET", "/room_keys/version", undefined, undefined, { prefix: http_api_1.PREFIX_UNSTABLE });
            }
            catch (e) {
                if (e.errcode === 'M_NOT_FOUND') {
                    return null;
                }
                else {
                    throw e;
                }
            }
            try {
                backup_1.BackupManager.checkBackupVersion(res);
            }
            catch (e) {
                throw e;
            }
            return res;
        });
    }
    /**
     * @param {object} info key backup info dict from getKeyBackupVersion()
     * @return {object} {
     *     usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device
     *     sigs: [
     *         valid: [bool],
     *         device: [DeviceInfo],
     *     ]
     * }
     */
    isKeyBackupTrusted(info) {
        return this.crypto.backupManager.isKeyBackupTrusted(info);
    }
    /**
     * @returns {boolean} true if the client is configured to back up keys to
     *     the server, otherwise false. If we haven't completed a successful check
     *     of key backup status yet, returns null.
     */
    getKeyBackupEnabled() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.backupManager.getKeyBackupEnabled();
    }
    /**
     * Enable backing up of keys, using data previously returned from
     * getKeyBackupVersion.
     *
     * @param {object} info Backup information object as returned by getKeyBackupVersion
     * @returns {Promise<void>} Resolves when complete.
     */
    enableKeyBackup(info) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.backupManager.enableKeyBackup(info);
    }
    /**
     * Disable backing up of keys.
     */
    disableKeyBackup() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        this.crypto.backupManager.disableKeyBackup();
    }
    /**
     * Set up the data required to create a new backup version.  The backup version
     * will not be created and enabled until createKeyBackupVersion is called.
     *
     * @param {string} password Passphrase string that can be entered by the user
     *     when restoring the backup as an alternative to entering the recovery key.
     *     Optional.
     * @param {boolean} [opts.secureSecretStorage = false] Whether to use Secure
     *     Secret Storage to store the key encrypting key backups.
     *     Optional, defaults to false.
     *
     * @returns {Promise<object>} Object that can be passed to createKeyBackupVersion and
     *     additionally has a 'recovery_key' member with the user-facing recovery key string.
     */
    // TODO: Verify types
    prepareKeyBackupVersion(password, opts = { secureSecretStorage: false }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            // eslint-disable-next-line camelcase
            const { algorithm, auth_data, recovery_key, privateKey } = yield this.crypto.backupManager.prepareKeyBackupVersion(password);
            if (opts.secureSecretStorage) {
                yield this.storeSecret("m.megolm_backup.v1", olmlib_1.encodeBase64(privateKey));
                logger_1.logger.info("Key backup private key stored in secret storage");
            }
            return {
                algorithm,
                auth_data,
                recovery_key,
            };
        });
    }
    /**
     * Check whether the key backup private key is stored in secret storage.
     * @return {Promise<object?>} map of key name to key info the secret is
     *     encrypted with, or null if it is not present or not encrypted with a
     *     trusted key
     */
    isKeyBackupKeyStored() {
        return Promise.resolve(this.isSecretStored("m.megolm_backup.v1", false /* checkKey */));
    }
    /**
     * Create a new key backup version and enable it, using the information return
     * from prepareKeyBackupVersion.
     *
     * @param {object} info Info object from prepareKeyBackupVersion
     * @returns {Promise<object>} Object with 'version' param indicating the version created
     */
    // TODO: Fix types
    createKeyBackupVersion(info) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            yield this.crypto.backupManager.createKeyBackupVersion(info);
            const data = {
                algorithm: info.algorithm,
                auth_data: info.auth_data,
            };
            // Sign the backup auth data with the device key for backwards compat with
            // older devices with cross-signing. This can probably go away very soon in
            // favour of just signing with the cross-singing master key.
            // XXX: Private member access
            yield this.crypto.signObject(data.auth_data);
            if (this.cryptoCallbacks.getCrossSigningKey &&
                // XXX: Private member access
                this.crypto.crossSigningInfo.getId()) {
                // now also sign the auth data with the cross-signing master key
                // we check for the callback explicitly here because we still want to be able
                // to create an un-cross-signed key backup if there is a cross-signing key but
                // no callback supplied.
                // XXX: Private member access
                yield this.crypto.crossSigningInfo.signObject(data.auth_data, "master");
            }
            const res = yield this.http.authedRequest(undefined, "POST", "/room_keys/version", undefined, data, { prefix: http_api_1.PREFIX_UNSTABLE });
            // We could assume everything's okay and enable directly, but this ensures
            // we run the same signature verification that will be used for future
            // sessions.
            yield this.checkKeyBackup();
            if (!this.getKeyBackupEnabled()) {
                logger_1.logger.error("Key backup not usable even though we just created it");
            }
            return res;
        });
    }
    deleteKeyBackupVersion(version) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        // If we're currently backing up to this backup... stop.
        // (We start using it automatically in createKeyBackupVersion
        // so this is symmetrical).
        if (this.crypto.backupManager.version) {
            this.crypto.backupManager.disableKeyBackup();
        }
        const path = utils.encodeUri("/room_keys/version/$version", {
            $version: version,
        });
        return this.http.authedRequest(undefined, "DELETE", path, undefined, undefined, { prefix: http_api_1.PREFIX_UNSTABLE });
    }
    makeKeyBackupPath(roomId, sessionId, version) {
        let path;
        if (sessionId !== undefined) {
            path = utils.encodeUri("/room_keys/keys/$roomId/$sessionId", {
                $roomId: roomId,
                $sessionId: sessionId,
            });
        }
        else if (roomId !== undefined) {
            path = utils.encodeUri("/room_keys/keys/$roomId", {
                $roomId: roomId,
            });
        }
        else {
            path = "/room_keys/keys";
        }
        const queryData = version === undefined ? undefined : { version: version };
        return {
            path: path,
            queryData: queryData,
        };
    }
    /**
     * Back up session keys to the homeserver.
     * @param {string} roomId ID of the room that the keys are for Optional.
     * @param {string} sessionId ID of the session that the keys are for Optional.
     * @param {number} version backup version Optional.
     * @param {object} data Object keys to send
     * @return {Promise} a promise that will resolve when the keys
     * are uploaded
     */
    // TODO: Verify types
    sendKeyBackup(roomId, sessionId, version, data) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        const path = this.makeKeyBackupPath(roomId, sessionId, version);
        return this.http.authedRequest(undefined, "PUT", path.path, path.queryData, data, { prefix: http_api_1.PREFIX_UNSTABLE });
    }
    /**
     * Marks all group sessions as needing to be backed up and schedules them to
     * upload in the background as soon as possible.
     */
    scheduleAllGroupSessionsForBackup() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            yield this.crypto.backupManager.scheduleAllGroupSessionsForBackup();
        });
    }
    /**
     * Marks all group sessions as needing to be backed up without scheduling
     * them to upload in the background.
     * @returns {Promise<int>} Resolves to the number of sessions requiring a backup.
     */
    flagAllGroupSessionsForBackup() {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        return this.crypto.backupManager.flagAllGroupSessionsForBackup();
    }
    isValidRecoveryKey(recoveryKey) {
        try {
            recoverykey_1.decodeRecoveryKey(recoveryKey);
            return true;
        }
        catch (e) {
            return false;
        }
    }
    /**
     * Get the raw key for a key backup from the password
     * Used when migrating key backups into SSSS
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {string} password Passphrase
     * @param {object} backupInfo Backup metadata from `checkKeyBackup`
     * @return {Promise<Uint8Array>} key backup key
     */
    keyBackupKeyFromPassword(password, backupInfo) {
        return key_passphrase_1.keyFromAuthData(backupInfo.auth_data, password);
    }
    /**
     * Get the raw key for a key backup from the recovery key
     * Used when migrating key backups into SSSS
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {string} recoveryKey The recovery key
     * @return {Uint8Array} key backup key
     */
    keyBackupKeyFromRecoveryKey(recoveryKey) {
        return recoverykey_1.decodeRecoveryKey(recoveryKey);
    }
    /**
     * Restore from an existing key backup via a passphrase.
     *
     * @param {string} password Passphrase
     * @param {string} [targetRoomId] Room ID to target a specific room.
     * Restores all rooms if omitted.
     * @param {string} [targetSessionId] Session ID to target a specific session.
     * Restores all sessions if omitted.
     * @param {object} backupInfo Backup metadata from `checkKeyBackup`
     * @param {object} opts Optional params such as callbacks
     * @return {Promise<object>} Status of restoration with `total` and `imported`
     * key counts.
     */
    // TODO: Types
    restoreKeyBackupWithPassword(password, targetRoomId, targetSessionId, backupInfo, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const privKey = yield key_passphrase_1.keyFromAuthData(backupInfo.auth_data, password);
            return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);
        });
    }
    /**
     * Restore from an existing key backup via a private key stored in secret
     * storage.
     *
     * @param {object} backupInfo Backup metadata from `checkKeyBackup`
     * @param {string} [targetRoomId] Room ID to target a specific room.
     * Restores all rooms if omitted.
     * @param {string} [targetSessionId] Session ID to target a specific session.
     * Restores all sessions if omitted.
     * @param {object} opts Optional params such as callbacks
     * @return {Promise<object>} Status of restoration with `total` and `imported`
     * key counts.
     */
    // TODO: Types
    restoreKeyBackupWithSecretStorage(backupInfo, targetRoomId, targetSessionId, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const storedKey = yield this.getSecret("m.megolm_backup.v1");
            // ensure that the key is in the right format.  If not, fix the key and
            // store the fixed version
            const fixedKey = crypto_1.fixBackupKey(storedKey);
            if (fixedKey) {
                const [keyId] = yield this.crypto.getSecretStorageKey();
                yield this.storeSecret("m.megolm_backup.v1", fixedKey, [keyId]);
            }
            const privKey = olmlib_1.decodeBase64(fixedKey || storedKey);
            return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);
        });
    }
    /**
     * Restore from an existing key backup via an encoded recovery key.
     *
     * @param {string} recoveryKey Encoded recovery key
     * @param {string} [targetRoomId] Room ID to target a specific room.
     * Restores all rooms if omitted.
     * @param {string} [targetSessionId] Session ID to target a specific session.
     * Restores all sessions if omitted.
     * @param {object} backupInfo Backup metadata from `checkKeyBackup`
     * @param {object} opts Optional params such as callbacks

     * @return {Promise<object>} Status of restoration with `total` and `imported`
     * key counts.
     */
    // TODO: Types
    restoreKeyBackupWithRecoveryKey(recoveryKey, targetRoomId, targetSessionId, backupInfo, opts) {
        const privKey = recoverykey_1.decodeRecoveryKey(recoveryKey);
        return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);
    }
    // TODO: Types
    restoreKeyBackupWithCache(targetRoomId, targetSessionId, backupInfo, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const privKey = yield this.crypto.getSessionBackupPrivateKey();
            if (!privKey) {
                throw new Error("Couldn't get key");
            }
            return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);
        });
    }
    restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const cacheCompleteCallback = opts === null || opts === void 0 ? void 0 : opts.cacheCompleteCallback;
            const progressCallback = opts === null || opts === void 0 ? void 0 : opts.progressCallback;
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            let totalKeyCount = 0;
            let keys = [];
            const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupInfo.version);
            const algorithm = yield backup_1.BackupManager.makeAlgorithm(backupInfo, () => __awaiter(this, void 0, void 0, function* () { return privKey; }));
            const untrusted = algorithm.untrusted;
            try {
                // If the pubkey computed from the private data we've been given
                // doesn't match the one in the auth_data, the user has entered
                // a different recovery key / the wrong passphrase.
                if (!(yield algorithm.keyMatches(privKey))) {
                    return Promise.reject(new http_api_1.MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }));
                }
                // Cache the key, if possible.
                // This is async.
                this.crypto.storeSessionBackupPrivateKey(privKey)
                    .catch((e) => {
                    logger_1.logger.warn("Error caching session backup key:", e);
                }).then(cacheCompleteCallback);
                if (progressCallback) {
                    progressCallback({
                        stage: "fetch",
                    });
                }
                const res = yield this.http.authedRequest(undefined, "GET", path.path, path.queryData, undefined, { prefix: http_api_1.PREFIX_UNSTABLE });
                if (res.rooms) {
                    // TODO: Types
                    for (const [roomId, roomData] of Object.entries(res.rooms)) {
                        if (!roomData.sessions)
                            continue;
                        totalKeyCount += Object.keys(roomData.sessions).length;
                        const roomKeys = yield algorithm.decryptSessions(roomData.sessions);
                        for (const k of roomKeys) {
                            k.room_id = roomId;
                            keys.push(k);
                        }
                    }
                }
                else if (res.sessions) {
                    totalKeyCount = Object.keys(res.sessions).length;
                    keys = yield algorithm.decryptSessions(res.sessions);
                    for (const k of keys) {
                        k.room_id = targetRoomId;
                    }
                }
                else {
                    totalKeyCount = 1;
                    try {
                        const [key] = yield algorithm.decryptSessions({
                            [targetSessionId]: res,
                        });
                        key.room_id = targetRoomId;
                        key.session_id = targetSessionId;
                        keys.push(key);
                    }
                    catch (e) {
                        logger_1.logger.log("Failed to decrypt megolm session from backup", e);
                    }
                }
            }
            finally {
                algorithm.free();
            }
            yield this.importRoomKeys(keys, {
                progressCallback,
                untrusted,
                source: "backup",
            });
            yield this.checkKeyBackup();
            return { total: totalKeyCount, imported: keys.length };
        });
    }
    deleteKeysFromBackup(roomId, sessionId, version) {
        if (!this.crypto) {
            throw new Error("End-to-end encryption disabled");
        }
        const path = this.makeKeyBackupPath(roomId, sessionId, version);
        return this.http.authedRequest(undefined, "DELETE", path.path, path.queryData, undefined, { prefix: http_api_1.PREFIX_UNSTABLE });
    }
    /**
     * Share shared-history decryption keys with the given users.
     *
     * @param {string} roomId the room for which keys should be shared.
     * @param {array} userIds a list of users to share with.  The keys will be sent to
     *     all of the user's current devices.
     */
    sendSharedHistoryKeys(roomId, userIds) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.crypto) {
                throw new Error("End-to-end encryption disabled");
            }
            const roomEncryption = this.roomList.getRoomEncryption(roomId);
            if (!roomEncryption) {
                // unknown room, or unencrypted room
                logger_1.logger.error("Unknown room.  Not sharing decryption keys");
                return;
            }
            const deviceInfos = yield this.crypto.downloadKeys(userIds);
            const devicesByUser = {};
            for (const [userId, devices] of Object.entries(deviceInfos)) {
                devicesByUser[userId] = Object.values(devices);
            }
            // XXX: Private member access
            const alg = this.crypto.getRoomDecryptor(roomId, roomEncryption.algorithm);
            if (alg.sendSharedHistoryInboundSessions) {
                yield alg.sendSharedHistoryInboundSessions(devicesByUser);
            }
            else {
                logger_1.logger.warn("Algorithm does not support sharing previous keys", roomEncryption.algorithm);
            }
        });
    }
    /**
     * Get the group for the given group ID.
     * This function will return a valid group for any group for which a Group event
     * has been emitted.
     * @param {string} groupId The group ID
     * @return {Group} The Group or null if the group is not known or there is no data store.
     */
    getGroup(groupId) {
        return this.store.getGroup(groupId);
    }
    /**
     * Retrieve all known groups.
     * @return {Group[]} A list of groups, or an empty list if there is no data store.
     */
    getGroups() {
        return this.store.getGroups();
    }
    /**
     * Get the config for the media repository.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves with an object containing the config.
     */
    getMediaConfig(callback) {
        return this.http.authedRequest(callback, "GET", "/config", undefined, undefined, {
            prefix: http_api_1.PREFIX_MEDIA_R0,
        });
    }
    /**
     * Get the room for the given room ID.
     * This function will return a valid room for any room for which a Room event
     * has been emitted. Note in particular that other events, eg. RoomState.members
     * will be emitted for a room before this function will return the given room.
     * @param {string} roomId The room ID
     * @return {Room} The Room or null if it doesn't exist or there is no data store.
     */
    getRoom(roomId) {
        return this.store.getRoom(roomId);
    }
    /**
     * Retrieve all known rooms.
     * @return {Room[]} A list of rooms, or an empty list if there is no data store.
     */
    getRooms() {
        return this.store.getRooms();
    }
    /**
     * Retrieve all rooms that should be displayed to the user
     * This is essentially getRooms() with some rooms filtered out, eg. old versions
     * of rooms that have been replaced or (in future) other rooms that have been
     * marked at the protocol level as not to be displayed to the user.
     * @return {Room[]} A list of rooms, or an empty list if there is no data store.
     */
    getVisibleRooms() {
        const allRooms = this.store.getRooms();
        const replacedRooms = new Set();
        for (const r of allRooms) {
            const createEvent = r.currentState.getStateEvents('m.room.create', '');
            // invites are included in this list and we don't know their create events yet
            if (createEvent) {
                const predecessor = createEvent.getContent()['predecessor'];
                if (predecessor && predecessor['room_id']) {
                    replacedRooms.add(predecessor['room_id']);
                }
            }
        }
        return allRooms.filter((r) => {
            const tombstone = r.currentState.getStateEvents('m.room.tombstone', '');
            if (tombstone && replacedRooms.has(r.roomId)) {
                return false;
            }
            return true;
        });
    }
    /**
     * Retrieve a user.
     * @param {string} userId The user ID to retrieve.
     * @return {?User} A user or null if there is no data store or the user does
     * not exist.
     */
    getUser(userId) {
        return this.store.getUser(userId);
    }
    /**
     * Retrieve all known users.
     * @return {User[]} A list of users, or an empty list if there is no data store.
     */
    getUsers() {
        return this.store.getUsers();
    }
    /**
     * Set account data event for the current user.
     * It will retry the request up to 5 times.
     * @param {string} eventType The event type
     * @param {Object} content the contents object for the event
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setAccountData(eventType, content, callback) {
        const path = utils.encodeUri("/user/$userId/account_data/$type", {
            $userId: this.credentials.userId,
            $type: eventType,
        });
        const promise = http_api_1.retryNetworkOperation(5, () => {
            return this.http.authedRequest(undefined, "PUT", path, undefined, content);
        });
        if (callback) {
            promise.then(result => callback(null, result), callback);
        }
        return promise;
    }
    /**
     * Get account data event of given type for the current user.
     * @param {string} eventType The event type
     * @return {?object} The contents of the given account data event
     */
    getAccountData(eventType) {
        return this.store.getAccountData(eventType);
    }
    /**
     * Get account data event of given type for the current user. This variant
     * gets account data directly from the homeserver if the local store is not
     * ready, which can be useful very early in startup before the initial sync.
     * @param {string} eventType The event type
     * @return {Promise} Resolves: The contents of the given account
     * data event.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getAccountDataFromServer(eventType) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.isInitialSyncComplete()) {
                const event = this.store.getAccountData(eventType);
                if (!event) {
                    return null;
                }
                // The network version below returns just the content, so this branch
                // does the same to match.
                return event.getContent();
            }
            const path = utils.encodeUri("/user/$userId/account_data/$type", {
                $userId: this.credentials.userId,
                $type: eventType,
            });
            try {
                return yield this.http.authedRequest(undefined, "GET", path, undefined);
            }
            catch (e) {
                if (e.data && e.data.errcode === 'M_NOT_FOUND') {
                    return null;
                }
                throw e;
            }
        });
    }
    /**
     * Gets the users that are ignored by this client
     * @returns {string[]} The array of users that are ignored (empty if none)
     */
    getIgnoredUsers() {
        const event = this.getAccountData("m.ignored_user_list");
        if (!event || !event.getContent() || !event.getContent()["ignored_users"])
            return [];
        return Object.keys(event.getContent()["ignored_users"]);
    }
    /**
     * Sets the users that the current user should ignore.
     * @param {string[]} userIds the user IDs to ignore
     * @param {module:client.callback} [callback] Optional.
     * @return {Promise} Resolves: Account data event
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setIgnoredUsers(userIds, callback) {
        const content = { ignored_users: {} };
        userIds.map((u) => content.ignored_users[u] = {});
        return this.setAccountData("m.ignored_user_list", content, callback);
    }
    /**
     * Gets whether or not a specific user is being ignored by this client.
     * @param {string} userId the user ID to check
     * @returns {boolean} true if the user is ignored, false otherwise
     */
    isUserIgnored(userId) {
        return this.getIgnoredUsers().includes(userId);
    }
    /**
     * Join a room. If you have already joined the room, this will no-op.
     * @param {string} roomIdOrAlias The room ID or room alias to join.
     * @param {Object} opts Options when joining the room.
     * @param {boolean} opts.syncRoom True to do a room initial sync on the resulting
     * room. If false, the <strong>returned Room object will have no current state.
     * </strong> Default: true.
     * @param {boolean} opts.inviteSignUrl If the caller has a keypair 3pid invite, the signing URL is passed in this parameter.
     * @param {string[]} opts.viaServers The server names to try and join through in addition to those that are automatically chosen.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Room object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    joinRoom(roomIdOrAlias, opts, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            // to help people when upgrading..
            if (utils.isFunction(opts)) {
                throw new Error("Expected 'opts' object, got function.");
            }
            opts = opts || {};
            if (opts.syncRoom === undefined) {
                opts.syncRoom = true;
            }
            const room = this.getRoom(roomIdOrAlias);
            if (room && room.hasMembershipState(this.credentials.userId, "join")) {
                return Promise.resolve(room);
            }
            let signPromise = Promise.resolve();
            if (opts.inviteSignUrl) {
                signPromise = this.http.requestOtherUrl(undefined, 'POST', opts.inviteSignUrl, { mxid: this.credentials.userId });
            }
            const queryString = {};
            if (opts.viaServers) {
                queryString["server_name"] = opts.viaServers;
            }
            const reqOpts = { qsStringifyOptions: { arrayFormat: 'repeat' } };
            try {
                const data = {};
                // XXX: Explicit cast due to underlying types not existing
                const signedInviteObj = (yield signPromise);
                if (signedInviteObj) {
                    data['third_party_signed'] = signedInviteObj;
                }
                const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias });
                const res = yield this.http.authedRequest(undefined, "POST", path, queryString, data, reqOpts);
                const roomId = res['room_id'];
                const syncApi = new sync_1.SyncApi(this, this.clientOpts);
                const room = syncApi.createRoom(roomId);
                if (opts.syncRoom) {
                    // v2 will do this for us
                    // return syncApi.syncRoom(room);
                }
                callback === null || callback === void 0 ? void 0 : callback(null, room);
                return room;
            }
            catch (e) {
                callback === null || callback === void 0 ? void 0 : callback(e);
                throw e; // rethrow for reject
            }
        });
    }
    /**
     * Resend an event.
     * @param {MatrixEvent} event The event to resend.
     * @param {Room} room Optional. The room the event is in. Will update the
     * timeline entry if provided.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    resendEvent(event, room) {
        this.updatePendingEventStatus(room, event, event_1.EventStatus.SENDING);
        return this.encryptAndSendEvent(room, event);
    }
    /**
     * Cancel a queued or unsent event.
     *
     * @param {MatrixEvent} event   Event to cancel
     * @throws Error if the event is not in QUEUED or NOT_SENT state
     */
    cancelPendingEvent(event) {
        if ([event_1.EventStatus.QUEUED, event_1.EventStatus.NOT_SENT].indexOf(event.status) < 0) {
            throw new Error("cannot cancel an event with status " + event.status);
        }
        // first tell the scheduler to forget about it, if it's queued
        if (this.scheduler) {
            this.scheduler.removeEventFromQueue(event);
        }
        // then tell the room about the change of state, which will remove it
        // from the room's list of pending events.
        const room = this.getRoom(event.getRoomId());
        this.updatePendingEventStatus(room, event, event_1.EventStatus.CANCELLED);
    }
    /**
     * @param {string} roomId
     * @param {string} name
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomName(roomId, name, callback) {
        return this.sendStateEvent(roomId, "m.room.name", { name: name }, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} topic
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomTopic(roomId, topic, callback) {
        return this.sendStateEvent(roomId, "m.room.topic", { topic: topic }, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getRoomTags(roomId, callback) {
        const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", {
            $userId: this.credentials.userId,
            $roomId: roomId,
        });
        return this.http.authedRequest(callback, "GET", path, undefined);
    }
    /**
     * @param {string} roomId
     * @param {string} tagName name of room tag to be set
     * @param {object} metadata associated with that tag to be stored
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomTag(roomId, tagName, metadata, callback) {
        const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
            $userId: this.credentials.userId,
            $roomId: roomId,
            $tag: tagName,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, metadata);
    }
    /**
     * @param {string} roomId
     * @param {string} tagName name of room tag to be removed
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deleteRoomTag(roomId, tagName, callback) {
        const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
            $userId: this.credentials.userId,
            $roomId: roomId,
            $tag: tagName,
        });
        return this.http.authedRequest(callback, "DELETE", path, undefined, undefined);
    }
    /**
     * @param {string} roomId
     * @param {string} eventType event type to be set
     * @param {object} content event content
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomAccountData(roomId, eventType, content, callback) {
        const path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", {
            $userId: this.credentials.userId,
            $roomId: roomId,
            $type: eventType,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, content);
    }
    /**
     * Set a user's power level.
     * @param {string} roomId
     * @param {string} userId
     * @param {Number} powerLevel
     * @param {MatrixEvent} event
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setPowerLevel(roomId, userId, powerLevel, event, callback) {
        let content = {
            users: {},
        };
        if (event && event.getType() === "m.room.power_levels") {
            // take a copy of the content to ensure we don't corrupt
            // existing client state with a failed power level change
            content = utils.deepCopy(event.getContent());
        }
        content.users[userId] = powerLevel;
        const path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", {
            $roomId: roomId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, content);
    }
    /**
     * @param {string} roomId
     * @param {string} eventType
     * @param {Object} content
     * @param {string} txnId Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendEvent(roomId, eventType, content, txnId, callback) {
        return this.sendCompleteEvent(roomId, { type: eventType, content }, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {object} 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.
     * @param {string} txnId the txnId.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendCompleteEvent(roomId, eventObject, txnId, callback) {
        if (utils.isFunction(txnId)) {
            callback = txnId; // convert for legacy
            txnId = undefined;
        }
        if (!txnId) {
            txnId = this.makeTxnId();
        }
        // we always construct a MatrixEvent when sending because the store and
        // scheduler use them. We'll extract the params back out if it turns out
        // the client has no scheduler or store.
        const localEvent = new event_1.MatrixEvent(Object.assign(eventObject, {
            event_id: "~" + roomId + ":" + txnId,
            user_id: this.credentials.userId,
            sender: this.credentials.userId,
            room_id: roomId,
            origin_server_ts: new Date().getTime(),
        }));
        const room = this.getRoom(roomId);
        // if this is a relation or redaction of an event
        // that hasn't been sent yet (e.g. with a local id starting with a ~)
        // then listen for the remote echo of that event so that by the time
        // this event does get sent, we have the correct event_id
        const targetId = localEvent.getAssociatedId();
        if (targetId && targetId.startsWith("~")) {
            const target = room.getPendingEvents().find(e => e.getId() === targetId);
            target.once("Event.localEventIdReplaced", () => {
                localEvent.updateAssociatedId(target.getId());
            });
        }
        const type = localEvent.getType();
        logger_1.logger.log(`sendEvent of type ${type} in ${roomId} with txnId ${txnId}`);
        localEvent.setTxnId(txnId);
        localEvent.setStatus(event_1.EventStatus.SENDING);
        // add this event immediately to the local store as 'sending'.
        if (room) {
            room.addPendingEvent(localEvent, txnId);
        }
        // addPendingEvent can change the state to NOT_SENT if it believes
        // that there's other events that have failed. We won't bother to
        // try sending the event if the state has changed as such.
        if (localEvent.status === event_1.EventStatus.NOT_SENT) {
            return Promise.reject(new Error("Event blocked by other events not yet sent"));
        }
        return this.encryptAndSendEvent(room, localEvent, callback);
    }
    /**
     * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent
     * @param room
     * @param event
     * @param callback
     * @returns {Promise} returns a promise which resolves with the result of the send request
     * @private
     */
    encryptAndSendEvent(room, event, callback) {
        // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections,
        // so that we can handle synchronous and asynchronous exceptions with the
        // same code path.
        return Promise.resolve().then(() => {
            const encryptionPromise = this.encryptEventIfNeeded(event, room);
            if (!encryptionPromise)
                return null;
            this.updatePendingEventStatus(room, event, event_1.EventStatus.ENCRYPTING);
            return encryptionPromise.then(() => this.updatePendingEventStatus(room, event, event_1.EventStatus.SENDING));
        }).then(() => {
            let promise;
            if (this.scheduler) {
                // if this returns a promise then the scheduler has control now and will
                // resolve/reject when it is done. Internally, the scheduler will invoke
                // processFn which is set to this._sendEventHttpRequest so the same code
                // path is executed regardless.
                promise = this.scheduler.queueEvent(event);
                if (promise && this.scheduler.getQueueForEvent(event).length > 1) {
                    // event is processed FIFO so if the length is 2 or more we know
                    // this event is stuck behind an earlier event.
                    this.updatePendingEventStatus(room, event, event_1.EventStatus.QUEUED);
                }
            }
            if (!promise) {
                promise = this.sendEventHttpRequest(event);
                if (room) {
                    promise = promise.then(res => {
                        room.updatePendingEvent(event, event_1.EventStatus.SENT, res['event_id']);
                        return res;
                    });
                }
            }
            return promise;
        }).then(res => {
            callback === null || callback === void 0 ? void 0 : callback(null, res);
            return res;
        }).catch(err => {
            logger_1.logger.error("Error sending event", err.stack || err);
            try {
                // set the error on the event before we update the status:
                // updating the status emits the event, so the state should be
                // consistent at that point.
                event.error = err;
                this.updatePendingEventStatus(room, event, event_1.EventStatus.NOT_SENT);
                // also put the event object on the error: the caller will need this
                // to resend or cancel the event
                err.event = event;
                callback === null || callback === void 0 ? void 0 : callback(err);
            }
            catch (e) {
                logger_1.logger.error("Exception in error handler!", e.stack || err);
            }
            throw err;
        });
    }
    encryptEventIfNeeded(event, room) {
        if (event.isEncrypted()) {
            // this event has already been encrypted; this happens if the
            // encryption step succeeded, but the send step failed on the first
            // attempt.
            return null;
        }
        if (!this.isRoomEncrypted(event.getRoomId())) {
            return null;
        }
        if (!this.crypto && this.usingExternalCrypto) {
            // The client has opted to allow sending messages to encrypted
            // rooms even if the room is encrypted, and we haven't setup
            // crypto. This is useful for users of matrix-org/pantalaimon
            return null;
        }
        if (event.getType() === event_2.EventType.Reaction) {
            // For reactions, there is a very little gained by encrypting the entire
            // event, as relation data is already kept in the clear. Event
            // encryption for a reaction effectively only obscures the event type,
            // but the purpose is still obvious from the relation data, so nothing
            // is really gained. It also causes quite a few problems, such as:
            //   * triggers notifications via default push rules
            //   * prevents server-side bundling for reactions
            // The reaction key / content / emoji value does warrant encrypting, but
            // this will be handled separately by encrypting just this value.
            // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642
            return null;
        }
        if (!this.crypto) {
            throw new Error("This room is configured to use encryption, but your client does " +
                "not support encryption.");
        }
        return this.crypto.encryptEvent(event, room);
    }
    /**
     * Returns the eventType that should be used taking encryption into account
     * for a given eventType.
     * @param {MatrixClient} client the client
     * @param {string} roomId the room for the events `eventType` relates to
     * @param {string} eventType the event type
     * @return {string} the event type taking encryption into account
     */
    getEncryptedIfNeededEventType(roomId, eventType) {
        if (eventType === event_2.EventType.Reaction)
            return eventType;
        return this.isRoomEncrypted(roomId) ? event_2.EventType.RoomMessageEncrypted : eventType;
    }
    updatePendingEventStatus(room, event, newStatus) {
        if (room) {
            room.updatePendingEvent(event, newStatus);
        }
        else {
            event.setStatus(newStatus);
        }
    }
    sendEventHttpRequest(event) {
        let txnId = event.getTxnId();
        if (!txnId) {
            txnId = this.makeTxnId();
            event.setTxnId(txnId);
        }
        const pathParams = {
            $roomId: event.getRoomId(),
            $eventType: event.getWireType(),
            $stateKey: event.getStateKey(),
            $txnId: txnId,
        };
        let path;
        if (event.isState()) {
            let pathTemplate = "/rooms/$roomId/state/$eventType";
            if (event.getStateKey() && event.getStateKey().length > 0) {
                pathTemplate = "/rooms/$roomId/state/$eventType/$stateKey";
            }
            path = utils.encodeUri(pathTemplate, pathParams);
        }
        else if (event.isRedaction()) {
            const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;
            path = utils.encodeUri(pathTemplate, Object.assign({
                $redactsEventId: event.event.redacts,
            }, pathParams));
        }
        else {
            path = utils.encodeUri("/rooms/$roomId/send/$eventType/$txnId", pathParams);
        }
        return this.http.authedRequest(undefined, "PUT", path, undefined, event.getWireContent()).then((res) => {
            logger_1.logger.log(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);
            return res;
        });
    }
    /**
     * @param {string} roomId
     * @param {string} eventId
     * @param {string} [txnId]  transaction id. One will be made up if not
     *    supplied.
     * @param {object|module:client.callback} cbOrOpts
     *    Options to pass on, may contain `reason`.
     *    Can be callback for backwards compatibility.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    redactEvent(roomId, eventId, txnId, cbOrOpts) {
        const opts = typeof (cbOrOpts) === 'object' ? cbOrOpts : {};
        const reason = opts.reason;
        const callback = typeof (cbOrOpts) === 'function' ? cbOrOpts : undefined;
        return this.sendCompleteEvent(roomId, {
            type: event_2.EventType.RoomRedaction,
            content: { reason: reason },
            redacts: eventId,
        }, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {Object} content
     * @param {string} txnId Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendMessage(roomId, content, txnId, callback) {
        if (utils.isFunction(txnId)) {
            callback = txnId; // for legacy
            txnId = undefined;
        }
        return this.sendEvent(roomId, "m.room.message", content, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} txnId Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendTextMessage(roomId, body, txnId, callback) {
        const content = ContentHelpers.makeTextMessage(body);
        return this.sendMessage(roomId, content, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} txnId Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendNotice(roomId, body, txnId, callback) {
        const content = ContentHelpers.makeNotice(body);
        return this.sendMessage(roomId, content, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} txnId Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendEmoteMessage(roomId, body, txnId, callback) {
        const content = ContentHelpers.makeEmoteMessage(body);
        return this.sendMessage(roomId, content, txnId, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} url
     * @param {Object} info
     * @param {string} text
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendImageMessage(roomId, url, info, text = "Image", callback) {
        if (utils.isFunction(text)) {
            callback = text; // legacy
            text = undefined;
        }
        const content = {
            msgtype: "m.image",
            url: url,
            info: info,
            body: text,
        };
        return this.sendMessage(roomId, content, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} url
     * @param {Object} info
     * @param {string} text
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendStickerMessage(roomId, url, info, text = "Sticker", callback) {
        if (utils.isFunction(text)) {
            callback = text; // legacy
            text = undefined;
        }
        const content = {
            url: url,
            info: info,
            body: text,
        };
        return this.sendEvent(roomId, event_2.EventType.Sticker, content, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} htmlBody
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendHtmlMessage(roomId, body, htmlBody, callback) {
        const content = ContentHelpers.makeHtmlMessage(body, htmlBody);
        return this.sendMessage(roomId, content, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} htmlBody
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendHtmlNotice(roomId, body, htmlBody, callback) {
        const content = ContentHelpers.makeHtmlNotice(body, htmlBody);
        return this.sendMessage(roomId, content, undefined, callback);
    }
    /**
     * @param {string} roomId
     * @param {string} body
     * @param {string} htmlBody
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendHtmlEmote(roomId, body, htmlBody, callback) {
        const content = ContentHelpers.makeHtmlEmote(body, htmlBody);
        return this.sendMessage(roomId, content, undefined, callback);
    }
    /**
     * Send a receipt.
     * @param {Event} event The event being acknowledged
     * @param {string} receiptType The kind of receipt e.g. "m.read"
     * @param {object} opts Additional content to send alongside the receipt.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendReceipt(event, receiptType, body, callback) {
        if (typeof (body) === 'function') {
            callback = body; // legacy
            body = {};
        }
        if (this.isGuest()) {
            return Promise.resolve({}); // guests cannot send receipts so don't bother.
        }
        const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
            $roomId: event.getRoomId(),
            $receiptType: receiptType,
            $eventId: event.getId(),
        });
        const promise = this.http.authedRequest(callback, "POST", path, undefined, body || {});
        const room = this.getRoom(event.getRoomId());
        if (room) {
            room.addLocalEchoReceipt(this.credentials.userId, event, receiptType);
        }
        return promise;
    }
    /**
     * Send a read receipt.
     * @param {Event} event The event that has been read.
     * @param {object} opts The options for the read receipt.
     * @param {boolean} opts.hidden True to prevent the receipt from being sent to
     * other users and homeservers. Default false (send to everyone). <b>This
     * property is unstable and may change in the future.</b>
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendReadReceipt(event, opts, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof (opts) === 'function') {
                callback = opts; // legacy
                opts = {};
            }
            if (!opts)
                opts = {};
            const eventId = event.getId();
            const room = this.getRoom(event.getRoomId());
            if (room && room.hasPendingEvent(eventId)) {
                throw new Error(`Cannot set read receipt to a pending event (${eventId})`);
            }
            const addlContent = {
                "m.hidden": Boolean(opts.hidden),
            };
            return this.sendReceipt(event, "m.read", addlContent, callback);
        });
    }
    /**
     * Set a marker to indicate the point in a room before which the user has read every
     * event. This can be retrieved from room account data (the event type is `m.fully_read`)
     * and displayed as a horizontal line in the timeline that is visually distinct to the
     * position of the user's own read receipt.
     * @param {string} roomId ID of the room that has been read
     * @param {string} rmEventId ID of the event that has been read
     * @param {MatrixEvent} rrEvent the event tracked by the read receipt. This is here for
     * convenience because the RR and the RM are commonly updated at the same time as each
     * other. The local echo of this receipt will be done if set. Optional.
     * @param {object} opts Options for the read markers
     * @param {object} opts.hidden True to hide the receipt from other users and homeservers.
     * <b>This property is unstable and may change in the future.</b>
     * @return {Promise} Resolves: the empty object, {}.
     */
    setRoomReadMarkers(roomId, rmEventId, rrEvent, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const room = this.getRoom(roomId);
            if (room && room.hasPendingEvent(rmEventId)) {
                throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);
            }
            // Add the optional RR update, do local echo like `sendReceipt`
            let rrEventId;
            if (rrEvent) {
                rrEventId = rrEvent.getId();
                if (room && room.hasPendingEvent(rrEventId)) {
                    throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);
                }
                if (room) {
                    room.addLocalEchoReceipt(this.credentials.userId, rrEvent, "m.read");
                }
            }
            return this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, opts);
        });
    }
    /**
     * Get a preview of the given URL as of (roughly) the given point in time,
     * described as an object with OpenGraph keys and associated values.
     * Attributes may be synthesized where actual OG metadata is lacking.
     * Caches results to prevent hammering the server.
     * @param {string} url The URL to get preview data for
     * @param {Number} ts The preferred point in time that the preview should
     * describe (ms since epoch).  The preview returned will either be the most
     * recent one preceding this timestamp if available, or failing that the next
     * most recent available preview.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Object of OG metadata.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     * May return synthesized attributes if the URL lacked OG meta.
     */
    getUrlPreview(url, ts, callback) {
        // bucket the timestamp to the nearest minute to prevent excessive spam to the server
        // Surely 60-second accuracy is enough for anyone.
        ts = Math.floor(ts / 60000) * 60000;
        const parsed = new URL(url);
        parsed.hash = ""; // strip the hash as it won't affect the preview
        url = parsed.toString();
        const key = ts + "_" + url;
        // If there's already a request in flight (or we've handled it), return that instead.
        const cachedPreview = this.urlPreviewCache[key];
        if (cachedPreview) {
            if (callback) {
                cachedPreview.then(callback).catch(callback);
            }
            return cachedPreview;
        }
        const resp = this.http.authedRequest(callback, "GET", "/preview_url", {
            url: url,
            ts: ts,
        }, undefined, {
            prefix: http_api_1.PREFIX_MEDIA_R0,
        });
        // TODO: Expire the URL preview cache sometimes
        this.urlPreviewCache[key] = resp;
        return resp;
    }
    /**
     * @param {string} roomId
     * @param {boolean} isTyping
     * @param {Number} timeoutMs
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendTyping(roomId, isTyping, timeoutMs, callback) {
        if (this.isGuest()) {
            return Promise.resolve({}); // guests cannot send typing notifications so don't bother.
        }
        const path = utils.encodeUri("/rooms/$roomId/typing/$userId", {
            $roomId: roomId,
            $userId: this.credentials.userId,
        });
        const data = {
            typing: isTyping,
        };
        if (isTyping) {
            data.timeout = timeoutMs ? timeoutMs : 20000;
        }
        return this.http.authedRequest(callback, "PUT", path, undefined, data);
    }
    /**
     * Determines the history of room upgrades for a given room, as far as the
     * client can see. Returns an array of Rooms where the first entry is the
     * oldest and the last entry is the newest (likely current) room. If the
     * provided room is not found, this returns an empty list. This works in
     * both directions, looking for older and newer rooms of the given room.
     * @param {string} roomId The room ID to search from
     * @param {boolean} verifyLinks If true, the function will only return rooms
     * which can be proven to be linked. For example, rooms which have a create
     * event pointing to an old room which the client is not aware of or doesn't
     * have a matching tombstone would not be returned.
     * @return {Room[]} An array of rooms representing the upgrade
     * history.
     */
    getRoomUpgradeHistory(roomId, verifyLinks = false) {
        let currentRoom = this.getRoom(roomId);
        if (!currentRoom)
            return [];
        const upgradeHistory = [currentRoom];
        // Work backwards first, looking at create events.
        let createEvent = currentRoom.currentState.getStateEvents("m.room.create", "");
        while (createEvent) {
            logger_1.logger.log(`Looking at ${createEvent.getId()}`);
            const predecessor = createEvent.getContent()['predecessor'];
            if (predecessor && predecessor['room_id']) {
                logger_1.logger.log(`Looking at predecessor ${predecessor['room_id']}`);
                const refRoom = this.getRoom(predecessor['room_id']);
                if (!refRoom)
                    break; // end of the chain
                if (verifyLinks) {
                    const tombstone = refRoom.currentState
                        .getStateEvents("m.room.tombstone", "");
                    if (!tombstone
                        || tombstone.getContent()['replacement_room'] !== refRoom.roomId) {
                        break;
                    }
                }
                // Insert at the front because we're working backwards from the currentRoom
                upgradeHistory.splice(0, 0, refRoom);
                createEvent = refRoom.currentState.getStateEvents("m.room.create", "");
            }
            else {
                // No further create events to look at
                break;
            }
        }
        // Work forwards next, looking at tombstone events
        let tombstoneEvent = currentRoom.currentState.getStateEvents("m.room.tombstone", "");
        while (tombstoneEvent) {
            const refRoom = this.getRoom(tombstoneEvent.getContent()['replacement_room']);
            if (!refRoom)
                break; // end of the chain
            if (refRoom.roomId === currentRoom.roomId)
                break; // Tombstone is referencing it's own room
            if (verifyLinks) {
                createEvent = refRoom.currentState.getStateEvents("m.room.create", "");
                if (!createEvent || !createEvent.getContent()['predecessor'])
                    break;
                const predecessor = createEvent.getContent()['predecessor'];
                if (predecessor['room_id'] !== currentRoom.roomId)
                    break;
            }
            // Push to the end because we're looking forwards
            upgradeHistory.push(refRoom);
            const roomIds = new Set(upgradeHistory.map((ref) => ref.roomId));
            if (roomIds.size < upgradeHistory.length) {
                // The last room added to the list introduced a previous roomId
                // To avoid recursion, return the last rooms - 1
                return upgradeHistory.slice(0, upgradeHistory.length - 1);
            }
            // Set the current room to the reference room so we know where we're at
            currentRoom = refRoom;
            tombstoneEvent = currentRoom.currentState.getStateEvents("m.room.tombstone", "");
        }
        return upgradeHistory;
    }
    /**
     * @param {string} roomId
     * @param {string} userId
     * @param {module:client.callback} callback Optional.
     * @param {string} reason Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    invite(roomId, userId, callback, reason) {
        return this.membershipChange(roomId, userId, "invite", reason, callback);
    }
    /**
     * Invite a user to a room based on their email address.
     * @param {string} roomId The room to invite the user to.
     * @param {string} email The email address to invite.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    inviteByEmail(roomId, email, callback) {
        return this.inviteByThreePid(roomId, "email", email, callback);
    }
    /**
     * Invite a user to a room based on a third-party identifier.
     * @param {string} roomId The room to invite the user to.
     * @param {string} medium The medium to invite the user e.g. "email".
     * @param {string} address The address for the specified medium.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    inviteByThreePid(roomId, medium, address, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = utils.encodeUri("/rooms/$roomId/invite", { $roomId: roomId });
            const identityServerUrl = this.getIdentityServerUrl(true);
            if (!identityServerUrl) {
                return Promise.reject(new http_api_1.MatrixError({
                    error: "No supplied identity server URL",
                    errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM",
                }));
            }
            const params = {
                id_server: identityServerUrl,
                medium: medium,
                address: address,
            };
            if (this.identityServer &&
                this.identityServer.getAccessToken &&
                (yield this.doesServerAcceptIdentityAccessToken())) {
                const identityAccessToken = yield this.identityServer.getAccessToken();
                if (identityAccessToken) {
                    params['id_access_token'] = identityAccessToken;
                }
            }
            return this.http.authedRequest(callback, "POST", path, undefined, params);
        });
    }
    /**
     * @param {string} roomId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    leave(roomId, callback) {
        return this.membershipChange(roomId, undefined, "leave", undefined, callback);
    }
    /**
     * Leaves all rooms in the chain of room upgrades based on the given room. By
     * default, this will leave all the previous and upgraded rooms, including the
     * given room. To only leave the given room and any previous rooms, keeping the
     * upgraded (modern) rooms untouched supply `false` to `includeFuture`.
     * @param {string} roomId The room ID to start leaving at
     * @param {boolean} includeFuture If true, the whole chain (past and future) of
     * upgraded rooms will be left.
     * @return {Promise} Resolves when completed with an object keyed
     * by room ID and value of the error encountered when leaving or null.
     */
    leaveRoomChain(roomId, includeFuture = true) {
        const upgradeHistory = this.getRoomUpgradeHistory(roomId);
        let eligibleToLeave = upgradeHistory;
        if (!includeFuture) {
            eligibleToLeave = [];
            for (const room of upgradeHistory) {
                eligibleToLeave.push(room);
                if (room.roomId === roomId) {
                    break;
                }
            }
        }
        const populationResults = {}; // {roomId: Error}
        const promises = [];
        const doLeave = (roomId) => {
            return this.leave(roomId).then(() => {
                populationResults[roomId] = null;
            }).catch((err) => {
                populationResults[roomId] = err;
                return null; // suppress error
            });
        };
        for (const room of eligibleToLeave) {
            promises.push(doLeave(room.roomId));
        }
        return Promise.all(promises).then(() => populationResults);
    }
    /**
     * @param {string} roomId
     * @param {string} userId
     * @param {string} reason Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    ban(roomId, userId, reason, callback) {
        return this.membershipChange(roomId, userId, "ban", reason, callback);
    }
    /**
     * @param {string} roomId
     * @param {boolean} deleteRoom True to delete the room from the store on success.
     * Default: true.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    forget(roomId, deleteRoom, callback) {
        if (deleteRoom === undefined) {
            deleteRoom = true;
        }
        const promise = this.membershipChange(roomId, undefined, "forget", undefined, callback);
        if (!deleteRoom) {
            return promise;
        }
        return promise.then((response) => {
            this.store.removeRoom(roomId);
            this.emit("deleteRoom", roomId);
            return response;
        });
    }
    /**
     * @param {string} roomId
     * @param {string} userId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Object (currently empty)
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    unban(roomId, userId, callback) {
        // unbanning != set their state to leave: this used to be
        // the case, but was then changed so that leaving was always
        // a revoking of privilege, otherwise two people racing to
        // kick / ban someone could end up banning and then un-banning
        // them.
        const path = utils.encodeUri("/rooms/$roomId/unban", {
            $roomId: roomId,
        });
        const data = {
            user_id: userId,
        };
        return this.http.authedRequest(callback, "POST", path, undefined, data);
    }
    /**
     * @param {string} roomId
     * @param {string} userId
     * @param {string} reason Optional.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    kick(roomId, userId, reason, callback) {
        return this.setMembershipState(roomId, userId, "leave", reason, callback);
    }
    /**
     * This is an internal method.
     * @param {MatrixClient} client
     * @param {string} roomId
     * @param {string} userId
     * @param {string} membershipValue
     * @param {string} reason
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setMembershipState(roomId, userId, membershipValue, reason, callback) {
        if (utils.isFunction(reason)) {
            callback = reason; // legacy
            reason = undefined;
        }
        const path = utils.encodeUri("/rooms/$roomId/state/m.room.member/$userId", { $roomId: roomId, $userId: userId });
        return this.http.authedRequest(callback, "PUT", path, undefined, {
            membership: membershipValue,
            reason: reason,
        });
    }
    membershipChange(roomId, userId, membership, reason, callback) {
        if (utils.isFunction(reason)) {
            callback = reason; // legacy
            reason = undefined;
        }
        const path = utils.encodeUri("/rooms/$room_id/$membership", {
            $room_id: roomId,
            $membership: membership,
        });
        return this.http.authedRequest(callback, "POST", path, undefined, {
            user_id: userId,
            reason: reason,
        });
    }
    /**
     * Obtain a dict of actions which should be performed for this event according
     * to the push rules for this user.  Caches the dict on the event.
     * @param {MatrixEvent} event The event to get push actions for.
     * @return {module:pushprocessor~PushAction} A dict of actions to perform.
     */
    getPushActionsForEvent(event) {
        if (!event.getPushActions()) {
            event.setPushActions(this.pushProcessor.actionsForEvent(event));
        }
        return event.getPushActions();
    }
    /**
     * @param {string} info The kind of info to set (e.g. 'avatar_url')
     * @param {Object} data The JSON object to set.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setProfileInfo(info, data, callback) {
        const path = utils.encodeUri("/profile/$userId/$info", {
            $userId: this.credentials.userId,
            $info: info,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, data);
    }
    /**
     * @param {string} name
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setDisplayName(name, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const prom = yield this.setProfileInfo("displayname", { displayname: name }, callback);
            // XXX: synthesise a profile update for ourselves because Synapse is broken and won't
            const user = this.getUser(this.getUserId());
            if (user) {
                user.displayName = name;
                user.emit("User.displayName", user.events.presence, user);
            }
            return prom;
        });
    }
    /**
     * @param {string} url
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: {} an empty object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setAvatarUrl(url, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const prom = yield this.setProfileInfo("avatar_url", { avatar_url: url }, callback);
            // XXX: synthesise a profile update for ourselves because Synapse is broken and won't
            const user = this.getUser(this.getUserId());
            if (user) {
                user.avatarUrl = url;
                user.emit("User.avatarUrl", user.events.presence, user);
            }
            return prom;
        });
    }
    /**
     * Turn an MXC URL into an HTTP one. <strong>This method is experimental and
     * may change.</strong>
     * @param {string} mxcUrl The MXC URL
     * @param {Number} width The desired width of the thumbnail.
     * @param {Number} height The desired height of the thumbnail.
     * @param {string} resizeMethod The thumbnail resize method to use, either
     * "crop" or "scale".
     * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs
     * directly. Fetching such URLs will leak information about the user to
     * anyone they share a room with. If false, will return null for such URLs.
     * @return {?string} the avatar URL or null.
     */
    mxcUrlToHttp(mxcUrl, width, height, resizeMethod, allowDirectLinks) {
        return content_repo_1.getHttpUriForMxc(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks);
    }
    /**
     * Sets a new status message for the user. The message may be null/falsey
     * to clear the message.
     * @param {string} newMessage The new message to set.
     * @return {Promise} Resolves: to nothing
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    _unstable_setStatusMessage(newMessage) {
        const type = "im.vector.user_status";
        return Promise.all(this.getRooms().map((room) => {
            const isJoined = room.getMyMembership() === "join";
            const looksLikeDm = room.getInvitedAndJoinedMemberCount() === 2;
            if (!isJoined || !looksLikeDm) {
                return Promise.resolve();
            }
            // Check power level separately as it's a bit more expensive.
            const maySend = room.currentState.mayClientSendStateEvent(type, this);
            if (!maySend) {
                return Promise.resolve();
            }
            return this.sendStateEvent(room.roomId, type, {
                status: newMessage,
            }, this.getUserId());
        })).then(); // .then to fix return type
    }
    /**
     * @param {Object} opts Options to apply
     * @param {string} opts.presence One of "online", "offline" or "unavailable"
     * @param {string} opts.status_msg The status message to attach.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     * @throws If 'presence' isn't a valid presence enum value.
     */
    setPresence(opts, callback) {
        const path = utils.encodeUri("/presence/$userId/status", {
            $userId: this.credentials.userId,
        });
        if (typeof opts === "string") {
            opts = { presence: opts }; // legacy
        }
        const validStates = ["offline", "online", "unavailable"];
        if (validStates.indexOf(opts.presence) === -1) {
            throw new Error("Bad presence value: " + opts.presence);
        }
        return this.http.authedRequest(callback, "PUT", path, undefined, opts);
    }
    /**
     * @param {string} userId The user to get presence for
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: The presence state for this user.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getPresence(userId, callback) {
        const path = utils.encodeUri("/presence/$userId/status", {
            $userId: userId,
        });
        return this.http.authedRequest(callback, "GET", path, undefined, undefined);
    }
    /**
     * Retrieve older messages from the given room and put them in the timeline.
     *
     * If this is called multiple times whilst a request is ongoing, the <i>same</i>
     * Promise will be returned. If there was a problem requesting scrollback, there
     * will be a small delay before another request can be made (to prevent tight-looping
     * when there is no connection).
     *
     * @param {Room} room The room to get older messages in.
     * @param {Integer} limit Optional. The maximum number of previous events to
     * pull in. Default: 30.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Room. If you are at the beginning
     * of the timeline, <code>Room.oldState.paginationToken</code> will be
     * <code>null</code>.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    scrollback(room, limit, callback) {
        if (utils.isFunction(limit)) {
            callback = limit; // legacy
            limit = undefined;
        }
        limit = limit || 30;
        let timeToWaitMs = 0;
        let info = this.ongoingScrollbacks[room.roomId] || {};
        if (info.promise) {
            return info.promise;
        }
        else if (info.errorTs) {
            const timeWaitedMs = Date.now() - info.errorTs;
            timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);
        }
        if (room.oldState.paginationToken === null) {
            return Promise.resolve(room); // already at the start.
        }
        // attempt to grab more events from the store first
        const numAdded = this.store.scrollback(room, limit).length;
        if (numAdded === limit) {
            // store contained everything we needed.
            return Promise.resolve(room);
        }
        // reduce the required number of events appropriately
        limit = limit - numAdded;
        const prom = new Promise((resolve, reject) => {
            // wait for a time before doing this request
            // (which may be 0 in order not to special case the code paths)
            utils_1.sleep(timeToWaitMs).then(() => {
                return this.createMessagesRequest(room.roomId, room.oldState.paginationToken, limit, 'b');
            }).then((res) => {
                const matrixEvents = res.chunk.map(this.getEventMapper());
                if (res.state) {
                    const stateEvents = res.state.map(this.getEventMapper());
                    room.currentState.setUnknownStateEvents(stateEvents);
                }
                room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline());
                room.oldState.paginationToken = res.end;
                if (res.chunk.length === 0) {
                    room.oldState.paginationToken = null;
                }
                this.store.storeEvents(room, matrixEvents, res.end, true);
                this.ongoingScrollbacks[room.roomId] = null;
                callback === null || callback === void 0 ? void 0 : callback(null, room);
                resolve(room);
            }).catch((err) => {
                this.ongoingScrollbacks[room.roomId] = {
                    errorTs: Date.now(),
                };
                callback === null || callback === void 0 ? void 0 : callback(err);
                reject(err);
            });
        });
        info = {
            promise: prom,
            errorTs: null,
        };
        this.ongoingScrollbacks[room.roomId] = info;
        return prom;
    }
    /**
     * @param {object} [options]
     * @param {boolean} options.preventReEmit don't reemit events emitted on an event mapped by this mapper on the client
     * @param {boolean} options.decrypt decrypt event proactively
     * @return {Function}
     */
    getEventMapper(options) {
        return event_mapper_1.eventMapperFor(this, options || {});
    }
    /**
     * Get an EventTimeline for the given event
     *
     * <p>If the EventTimelineSet object already has the given event in its store, the
     * corresponding timeline will be returned. Otherwise, a /context request is
     * made, and used to construct an EventTimeline.
     *
     * @param {EventTimelineSet} timelineSet  The timelineSet to look for the event in
     * @param {string} eventId  The ID of the event to look for
     *
     * @return {Promise} Resolves:
     *    {@link module:models/event-timeline~EventTimeline} including the given
     *    event
     */
    getEventTimeline(timelineSet, eventId) {
        // don't allow any timeline support unless it's been enabled.
        if (!this.timelineSupport) {
            throw new Error("timeline support is disabled. Set the 'timelineSupport'" +
                " parameter to true when creating MatrixClient to enable" +
                " it.");
        }
        if (timelineSet.getTimelineForEvent(eventId)) {
            return Promise.resolve(timelineSet.getTimelineForEvent(eventId));
        }
        const path = utils.encodeUri("/rooms/$roomId/context/$eventId", {
            $roomId: timelineSet.room.roomId,
            $eventId: eventId,
        });
        let params = undefined;
        if (this.clientOpts.lazyLoadMembers) {
            params = { filter: JSON.stringify(filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER) };
        }
        // TODO: we should implement a backoff (as per scrollback()) to deal more
        // nicely with HTTP errors.
        const promise = this.http.authedRequest(undefined, "GET", path, params).then((res) => {
            if (!res.event) {
                throw new Error("'event' not in '/context' result - homeserver too old?");
            }
            // by the time the request completes, the event might have ended up in
            // the timeline.
            if (timelineSet.getTimelineForEvent(eventId)) {
                return timelineSet.getTimelineForEvent(eventId);
            }
            // we start with the last event, since that's the point at which we
            // have known state.
            // events_after is already backwards; events_before is forwards.
            res.events_after.reverse();
            const events = res.events_after
                .concat([res.event])
                .concat(res.events_before);
            const matrixEvents = events.map(this.getEventMapper());
            let timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId());
            if (!timeline) {
                timeline = timelineSet.addTimeline();
                timeline.initialiseState(res.state.map(this.getEventMapper()));
                timeline.getState(event_timeline_1.EventTimeline.FORWARDS).paginationToken = res.end;
            }
            else {
                const stateEvents = res.state.map(this.getEventMapper());
                timeline.getState(event_timeline_1.EventTimeline.BACKWARDS).setUnknownStateEvents(stateEvents);
            }
            timelineSet.addEventsToTimeline(matrixEvents, true, timeline, res.start);
            // there is no guarantee that the event ended up in "timeline" (we
            // might have switched to a neighbouring timeline) - so check the
            // room's index again. On the other hand, there's no guarantee the
            // event ended up anywhere, if it was later redacted, so we just
            // return the timeline we first thought of.
            return timelineSet.getTimelineForEvent(eventId) || timeline;
        });
        return promise;
    }
    /**
     * Makes a request to /messages with the appropriate lazy loading filter set.
     * XXX: if we do get rid of scrollback (as it's not used at the moment),
     * we could inline this method again in paginateEventTimeline as that would
     * then be the only call-site
     * @param {string} roomId
     * @param {string} fromToken
     * @param {number} limit the maximum amount of events the retrieve
     * @param {string} dir 'f' or 'b'
     * @param {Filter} timelineFilter the timeline filter to pass
     * @return {Promise}
     */
    // XXX: Intended private, used in code.
    createMessagesRequest(roomId, fromToken, limit, dir, timelineFilter) {
        var _a;
        const path = utils.encodeUri("/rooms/$roomId/messages", { $roomId: roomId });
        if (limit === undefined) {
            limit = 30;
        }
        const params = {
            from: fromToken,
            limit: limit,
            dir: dir,
        };
        let filter = null;
        if (this.clientOpts.lazyLoadMembers) {
            // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,
            // so the timelineFilter doesn't get written into it below
            filter = Object.assign({}, filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER);
        }
        if (timelineFilter) {
            // XXX: it's horrific that /messages' filter parameter doesn't match
            // /sync's one - see https://matrix.org/jira/browse/SPEC-451
            filter = filter || {};
            Object.assign(filter, (_a = timelineFilter.getRoomTimelineFilterComponent()) === null || _a === void 0 ? void 0 : _a.toJSON());
        }
        if (filter) {
            params.filter = JSON.stringify(filter);
        }
        return this.http.authedRequest(undefined, "GET", path, params);
    }
    /**
     * Take an EventTimeline, and back/forward-fill results.
     *
     * @param {module:models/event-timeline~EventTimeline} eventTimeline timeline
     *    object to be updated
     * @param {Object}   [opts]
     * @param {boolean}     [opts.backwards = false]  true to fill backwards,
     *    false to go forwards
     * @param {number}   [opts.limit = 30]         number of events to request
     *
     * @return {Promise} Resolves to a boolean: false if there are no
     *    events and we reached either end of the timeline; else true.
     */
    paginateEventTimeline(eventTimeline, opts) {
        const isNotifTimeline = (eventTimeline.getTimelineSet() === this.notifTimelineSet);
        // TODO: we should implement a backoff (as per scrollback()) to deal more
        // nicely with HTTP errors.
        opts = opts || {};
        const backwards = opts.backwards || false;
        if (isNotifTimeline) {
            if (!backwards) {
                throw new Error("paginateNotifTimeline can only paginate backwards");
            }
        }
        const dir = backwards ? event_timeline_1.EventTimeline.BACKWARDS : event_timeline_1.EventTimeline.FORWARDS;
        const token = eventTimeline.getPaginationToken(dir);
        if (!token) {
            // no token - no results.
            return Promise.resolve(false);
        }
        const pendingRequest = eventTimeline.paginationRequests[dir];
        if (pendingRequest) {
            // already a request in progress - return the existing promise
            return pendingRequest;
        }
        let path;
        let params;
        let promise;
        if (isNotifTimeline) {
            path = "/notifications";
            params = {
                limit: ('limit' in opts) ? opts.limit : 30,
                only: 'highlight',
            };
            if (token && token !== "end") {
                params.from = token;
            }
            promise = this.http.authedRequest(undefined, "GET", path, params, undefined).then((res) => {
                const token = res.next_token;
                const matrixEvents = [];
                for (let i = 0; i < res.notifications.length; i++) {
                    const notification = res.notifications[i];
                    const event = this.getEventMapper()(notification.event);
                    event.setPushActions(pushprocessor_1.PushProcessor.actionListToActionsObject(notification.actions));
                    event.event.room_id = notification.room_id; // XXX: gutwrenching
                    matrixEvents[i] = event;
                }
                eventTimeline.getTimelineSet()
                    .addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);
                // if we've hit the end of the timeline, we need to stop trying to
                // paginate. We need to keep the 'forwards' token though, to make sure
                // we can recover from gappy syncs.
                if (backwards && !res.next_token) {
                    eventTimeline.setPaginationToken(null, dir);
                }
                return res.next_token ? true : false;
            }).finally(() => {
                eventTimeline.paginationRequests[dir] = null;
            });
            eventTimeline.paginationRequests[dir] = promise;
        }
        else {
            const room = this.getRoom(eventTimeline.getRoomId());
            if (!room) {
                throw new Error("Unknown room " + eventTimeline.getRoomId());
            }
            promise = this.createMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, eventTimeline.getFilter());
            promise.then((res) => {
                if (res.state) {
                    const roomState = eventTimeline.getState(dir);
                    const stateEvents = res.state.map(this.getEventMapper());
                    roomState.setUnknownStateEvents(stateEvents);
                }
                const token = res.end;
                const matrixEvents = res.chunk.map(this.getEventMapper());
                eventTimeline.getTimelineSet()
                    .addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);
                // if we've hit the end of the timeline, we need to stop trying to
                // paginate. We need to keep the 'forwards' token though, to make sure
                // we can recover from gappy syncs.
                if (backwards && res.end == res.start) {
                    eventTimeline.setPaginationToken(null, dir);
                }
                return res.end != res.start;
            }).finally(() => {
                eventTimeline.paginationRequests[dir] = null;
            });
            eventTimeline.paginationRequests[dir] = promise;
        }
        return promise;
    }
    /**
     * Reset the notifTimelineSet entirely, paginating in some historical notifs as
     * a starting point for subsequent pagination.
     */
    resetNotifTimelineSet() {
        if (!this.notifTimelineSet) {
            return;
        }
        // FIXME: This thing is a total hack, and results in duplicate events being
        // added to the timeline both from /sync and /notifications, and lots of
        // slow and wasteful processing and pagination.  The correct solution is to
        // extend /messages or /search or something to filter on notifications.
        // use the fictitious token 'end'. in practice we would ideally give it
        // the oldest backwards pagination token from /sync, but /sync doesn't
        // know about /notifications, so we have no choice but to start paginating
        // from the current point in time.  This may well overlap with historical
        // notifs which are then inserted into the timeline by /sync responses.
        this.notifTimelineSet.resetLiveTimeline('end', null);
        // we could try to paginate a single event at this point in order to get
        // a more valid pagination token, but it just ends up with an out of order
        // timeline. given what a mess this is and given we're going to have duplicate
        // events anyway, just leave it with the dummy token for now.
        /*
        this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {
            backwards: true,
            limit: 1
        });
        */
    }
    /**
     * Peek into a room and receive updates about the room. This only works if the
     * history visibility for the room is world_readable.
     * @param {String} roomId The room to attempt to peek into.
     * @return {Promise} Resolves: Room object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    peekInRoom(roomId) {
        if (this.peekSync) {
            this.peekSync.stopPeeking();
        }
        this.peekSync = new sync_1.SyncApi(this, this.clientOpts);
        return this.peekSync.peek(roomId);
    }
    /**
     * Stop any ongoing room peeking.
     */
    stopPeeking() {
        if (this.peekSync) {
            this.peekSync.stopPeeking();
            this.peekSync = null;
        }
    }
    /**
     * Set r/w flags for guest access in a room.
     * @param {string} roomId The room to configure guest access in.
     * @param {Object} opts Options
     * @param {boolean} opts.allowJoin True to allow guests to join this room. This
     * implicitly gives guests write access. If false or not given, guests are
     * explicitly forbidden from joining the room.
     * @param {boolean} opts.allowRead True to set history visibility to
     * be world_readable. This gives guests read access *from this point forward*.
     * If false or not given, history visibility is not modified.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setGuestAccess(roomId, opts) {
        const writePromise = this.sendStateEvent(roomId, "m.room.guest_access", {
            guest_access: opts.allowJoin ? "can_join" : "forbidden",
        }, "");
        let readPromise = Promise.resolve();
        if (opts.allowRead) {
            readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", {
                history_visibility: "world_readable",
            }, "");
        }
        return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract
    }
    /**
     * Requests an email verification token for the purposes of registration.
     * This API requests a token from the homeserver.
     * The doesServerRequireIdServerParam() method can be used to determine if
     * the server requires the id_server parameter to be provided.
     *
     * Parameters and return value are as for requestEmailToken

     * @param {string} email As requestEmailToken
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestRegisterEmailToken(email, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/register/email/requestToken", {
            email: email,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Requests a text message verification token for the purposes of registration.
     * This API requests a token from the homeserver.
     * The doesServerRequireIdServerParam() method can be used to determine if
     * the server requires the id_server parameter to be provided.
     *
     * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in which
     *    phoneNumber should be parsed relative to.
     * @param {string} phoneNumber The phone number, in national or international format
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestRegisterMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/register/msisdn/requestToken", {
            country: phoneCountry,
            phone_number: phoneNumber,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Requests an email verification token for the purposes of adding a
     * third party identifier to an account.
     * This API requests a token from the homeserver.
     * The doesServerRequireIdServerParam() method can be used to determine if
     * the server requires the id_server parameter to be provided.
     * If an account with the given email address already exists and is
     * associated with an account other than the one the user is authed as,
     * it will either send an email to the address informing them of this
     * or return M_THREEPID_IN_USE (which one is up to the Home Server).
     *
     * @param {string} email As requestEmailToken
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestAdd3pidEmailToken(email, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/account/3pid/email/requestToken", {
            email: email,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Requests a text message verification token for the purposes of adding a
     * third party identifier to an account.
     * This API proxies the Identity Server /validate/email/requestToken API,
     * adding specific behaviour for the addition of phone numbers to an
     * account, as requestAdd3pidEmailToken.
     *
     * @param {string} phoneCountry As requestRegisterMsisdnToken
     * @param {string} phoneNumber As requestRegisterMsisdnToken
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestAdd3pidMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken", {
            country: phoneCountry,
            phone_number: phoneNumber,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Requests an email verification token for the purposes of resetting
     * the password on an account.
     * This API proxies the Identity Server /validate/email/requestToken API,
     * adding specific behaviour for the password resetting. Specifically,
     * if no account with the given email address exists, it may either
     * return M_THREEPID_NOT_FOUND or send an email
     * to the address informing them of this (which one is up to the Home Server).
     *
     * requestEmailToken calls the equivalent API directly on the ID server,
     * therefore bypassing the password reset specific logic.
     *
     * @param {string} email As requestEmailToken
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @param {module:client.callback} callback Optional. As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestPasswordEmailToken(email, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/account/password/email/requestToken", {
            email: email,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Requests a text message verification token for the purposes of resetting
     * the password on an account.
     * This API proxies the Identity Server /validate/email/requestToken API,
     * adding specific behaviour for the password resetting, as requestPasswordEmailToken.
     *
     * @param {string} phoneCountry As requestRegisterMsisdnToken
     * @param {string} phoneNumber As requestRegisterMsisdnToken
     * @param {string} clientSecret As requestEmailToken
     * @param {number} sendAttempt As requestEmailToken
     * @param {string} nextLink As requestEmailToken
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestPasswordMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
        return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken", {
            country: phoneCountry,
            phone_number: phoneNumber,
            client_secret: clientSecret,
            send_attempt: sendAttempt,
            next_link: nextLink,
        });
    }
    /**
     * Internal utility function for requesting validation tokens from usage-specific
     * requestToken endpoints.
     *
     * @param {string} endpoint The endpoint to send the request to
     * @param {object} params Parameters for the POST request
     * @return {Promise} Resolves: As requestEmailToken
     */
    requestTokenFromEndpoint(endpoint, params) {
        return __awaiter(this, void 0, void 0, function* () {
            const postParams = Object.assign({}, params);
            // If the HS supports separate add and bind, then requestToken endpoints
            // don't need an IS as they are all validated by the HS directly.
            if (!(yield this.doesServerSupportSeparateAddAndBind()) && this.idBaseUrl) {
                const idServerUrl = url_1.default.parse(this.idBaseUrl);
                if (!idServerUrl.host) {
                    throw new Error("Invalid ID server URL: " + this.idBaseUrl);
                }
                postParams.id_server = idServerUrl.host;
                if (this.identityServer &&
                    this.identityServer.getAccessToken &&
                    (yield this.doesServerAcceptIdentityAccessToken())) {
                    const identityAccessToken = yield this.identityServer.getAccessToken();
                    if (identityAccessToken) {
                        postParams.id_access_token = identityAccessToken;
                    }
                }
            }
            return this.http.request(undefined, "POST", endpoint, undefined, postParams);
        });
    }
    /**
     * Get the room-kind push rule associated with a room.
     * @param {string} scope "global" or device-specific.
     * @param {string} roomId the id of the room.
     * @return {object} the rule or undefined.
     */
    getRoomPushRule(scope, roomId) {
        // There can be only room-kind push rule per room
        // and its id is the room id.
        if (this.pushRules) {
            for (let i = 0; i < this.pushRules[scope].room.length; i++) {
                const rule = this.pushRules[scope].room[i];
                if (rule.rule_id === roomId) {
                    return rule;
                }
            }
        }
        else {
            throw new Error("SyncApi.sync() must be done before accessing to push rules.");
        }
    }
    /**
     * Set a room-kind muting push rule in a room.
     * The operation also updates MatrixClient.pushRules at the end.
     * @param {string} scope "global" or device-specific.
     * @param {string} roomId the id of the room.
     * @param {string} mute the mute state.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomMutePushRule(scope, roomId, mute) {
        let deferred;
        let hasDontNotifyRule;
        // Get the existing room-kind push rule if any
        const roomPushRule = this.getRoomPushRule(scope, roomId);
        if (roomPushRule) {
            if (0 <= roomPushRule.actions.indexOf("dont_notify")) {
                hasDontNotifyRule = true;
            }
        }
        if (!mute) {
            // Remove the rule only if it is a muting rule
            if (hasDontNotifyRule) {
                deferred = this.deletePushRule(scope, "room", roomPushRule.rule_id);
            }
        }
        else {
            if (!roomPushRule) {
                deferred = this.addPushRule(scope, "room", roomId, {
                    actions: ["dont_notify"],
                });
            }
            else if (!hasDontNotifyRule) {
                // Remove the existing one before setting the mute push rule
                // This is a workaround to SYN-590 (Push rule update fails)
                deferred = utils.defer();
                this.deletePushRule(scope, "room", roomPushRule.rule_id)
                    .then(() => {
                    this.addPushRule(scope, "room", roomId, {
                        actions: ["dont_notify"],
                    }).then(() => {
                        deferred.resolve();
                    }).catch((err) => {
                        deferred.reject(err);
                    });
                }).catch((err) => {
                    deferred.reject(err);
                });
                deferred = deferred.promise;
            }
        }
        if (deferred) {
            return new Promise((resolve, reject) => {
                // Update this.pushRules when the operation completes
                deferred.then(() => {
                    this.getPushRules().then((result) => {
                        this.pushRules = result;
                        resolve();
                    }).catch((err) => {
                        reject(err);
                    });
                }).catch((err) => {
                    // Update it even if the previous operation fails. This can help the
                    // app to recover when push settings has been modifed from another client
                    this.getPushRules().then((result) => {
                        this.pushRules = result;
                        reject(err);
                    }).catch((err2) => {
                        reject(err);
                    });
                });
            });
        }
    }
    searchMessageText(opts, callback) {
        const roomEvents = {
            search_term: opts.query,
        };
        if ('keys' in opts) {
            roomEvents.keys = opts.keys;
        }
        return this.search({
            body: {
                search_categories: {
                    room_events: roomEvents,
                },
            },
        }, callback);
    }
    /**
     * Perform a server-side search for room events.
     *
     * The returned promise resolves to an object containing the fields:
     *
     *  * {number}  count:       estimate of the number of results
     *  * {string}  next_batch:  token for back-pagination; if undefined, there are
     *                           no more results
     *  * {Array}   highlights:  a list of words to highlight from the stemming
     *                           algorithm
     *  * {Array}   results:     a list of results
     *
     * Each entry in the results list is a {module:models/search-result.SearchResult}.
     *
     * @param {Object} opts
     * @param {string} opts.term     the term to search for
     * @param {Object} opts.filter   a JSON filter object to pass in the request
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    searchRoomEvents(opts) {
        // TODO: support groups
        const body = {
            search_categories: {
                room_events: {
                    search_term: opts.term,
                    filter: opts.filter,
                    order_by: "recent",
                    event_context: {
                        before_limit: 1,
                        after_limit: 1,
                        include_profile: true,
                    },
                },
            },
        };
        const searchResults = {
            _query: body,
            results: [],
            highlights: [],
        };
        return this.search({ body: body }).then(res => this.processRoomEventsSearch(searchResults, res));
    }
    /**
     * Take a result from an earlier searchRoomEvents call, and backfill results.
     *
     * @param  {object} searchResults  the results object to be updated
     * @return {Promise} Resolves: updated result object
     * @return {Error} Rejects: with an error response.
     */
    backPaginateRoomEventsSearch(searchResults) {
        // TODO: we should implement a backoff (as per scrollback()) to deal more
        // nicely with HTTP errors.
        if (!searchResults.next_batch) {
            return Promise.reject(new Error("Cannot backpaginate event search any further"));
        }
        if (searchResults.pendingRequest) {
            // already a request in progress - return the existing promise
            return searchResults.pendingRequest;
        }
        const searchOpts = {
            body: searchResults._query,
            next_batch: searchResults.next_batch,
        };
        const promise = this.search(searchOpts)
            .then(res => this.processRoomEventsSearch(searchResults, res))
            .finally(() => {
            searchResults.pendingRequest = null;
        });
        searchResults.pendingRequest = promise;
        return promise;
    }
    /**
     * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the
     * response from the API call and updates the searchResults
     *
     * @param {Object} searchResults
     * @param {Object} response
     * @return {Object} searchResults
     * @private
     */
    processRoomEventsSearch(searchResults, response) {
        const roomEvents = response.search_categories.room_events; // eslint-disable-line camelcase
        searchResults.count = roomEvents.count;
        searchResults.next_batch = roomEvents.next_batch;
        // combine the highlight list with our existing list; build an object
        // to avoid O(N^2) fail
        const highlights = {};
        roomEvents.highlights.forEach((hl) => {
            highlights[hl] = 1;
        });
        searchResults.highlights.forEach((hl) => {
            highlights[hl] = 1;
        });
        // turn it back into a list.
        searchResults.highlights = Object.keys(highlights);
        // append the new results to our existing results
        const resultsLength = roomEvents.results ? roomEvents.results.length : 0;
        for (let i = 0; i < resultsLength; i++) {
            const sr = search_result_1.SearchResult.fromJson(roomEvents.results[i], this.getEventMapper());
            searchResults.results.push(sr);
        }
        return searchResults;
    }
    /**
     * Populate the store with rooms the user has left.
     * @return {Promise} Resolves: TODO - Resolved when the rooms have
     * been added to the data store.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    syncLeftRooms() {
        // Guard against multiple calls whilst ongoing and multiple calls post success
        if (this.syncedLeftRooms) {
            return Promise.resolve([]); // don't call syncRooms again if it succeeded.
        }
        if (this.syncLeftRoomsPromise) {
            return this.syncLeftRoomsPromise; // return the ongoing request
        }
        const syncApi = new sync_1.SyncApi(this, this.clientOpts);
        this.syncLeftRoomsPromise = syncApi.syncLeftRooms();
        // cleanup locks
        this.syncLeftRoomsPromise.then((res) => {
            logger_1.logger.log("Marking success of sync left room request");
            this.syncedLeftRooms = true; // flip the bit on success
        }).finally(() => {
            this.syncLeftRoomsPromise = null; // cleanup ongoing request state
        });
        return this.syncLeftRoomsPromise;
    }
    /**
     * Create a new filter.
     * @param {Object} content The HTTP body for the request
     * @return {Filter} Resolves to a Filter object.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    createFilter(content) {
        const path = utils.encodeUri("/user/$userId/filter", {
            $userId: this.credentials.userId,
        });
        return this.http.authedRequest(undefined, "POST", path, undefined, content).then((response) => {
            // persist the filter
            const filter = filter_1.Filter.fromJson(this.credentials.userId, response.filter_id, content);
            this.store.storeFilter(filter);
            return filter;
        });
    }
    /**
     * Retrieve a filter.
     * @param {string} userId The user ID of the filter owner
     * @param {string} filterId The filter ID to retrieve
     * @param {boolean} allowCached True to allow cached filters to be returned.
     * Default: True.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getFilter(userId, filterId, allowCached) {
        if (allowCached) {
            const filter = this.store.getFilter(userId, filterId);
            if (filter) {
                return Promise.resolve(filter);
            }
        }
        const path = utils.encodeUri("/user/$userId/filter/$filterId", {
            $userId: userId,
            $filterId: filterId,
        });
        return this.http.authedRequest(undefined, "GET", path, undefined, undefined).then((response) => {
            // persist the filter
            const filter = filter_1.Filter.fromJson(userId, filterId, response);
            this.store.storeFilter(filter);
            return filter;
        });
    }
    /**
     * @param {string} filterName
     * @param {Filter} filter
     * @return {Promise<String>} Filter ID
     */
    getOrCreateFilter(filterName, filter) {
        return __awaiter(this, void 0, void 0, function* () {
            const filterId = this.store.getFilterIdByName(filterName);
            let existingId = undefined;
            if (filterId) {
                // check that the existing filter matches our expectations
                try {
                    const existingFilter = yield this.getFilter(this.credentials.userId, filterId, true);
                    if (existingFilter) {
                        const oldDef = existingFilter.getDefinition();
                        const newDef = filter.getDefinition();
                        if (utils.deepCompare(oldDef, newDef)) {
                            // super, just use that.
                            // debuglog("Using existing filter ID %s: %s", filterId,
                            //          JSON.stringify(oldDef));
                            existingId = filterId;
                        }
                    }
                }
                catch (error) {
                    // Synapse currently returns the following when the filter cannot be found:
                    // {
                    //     errcode: "M_UNKNOWN",
                    //     name: "M_UNKNOWN",
                    //     message: "No row found",
                    // }
                    if (error.errcode !== "M_UNKNOWN" && error.errcode !== "M_NOT_FOUND") {
                        throw error;
                    }
                }
                // if the filter doesn't exist anymore on the server, remove from store
                if (!existingId) {
                    this.store.setFilterIdByName(filterName, undefined);
                }
            }
            if (existingId) {
                return existingId;
            }
            // create a new filter
            const createdFilter = yield this.createFilter(filter.getDefinition());
            // debuglog("Created new filter ID %s: %s", createdFilter.filterId,
            //          JSON.stringify(createdFilter.getDefinition()));
            this.store.setFilterIdByName(filterName, createdFilter.filterId);
            return createdFilter.filterId;
        });
    }
    /**
     * Gets a bearer token from the Home Server that the user can
     * present to a third party in order to prove their ownership
     * of the Matrix account they are logged into.
     * @return {Promise} Resolves: Token object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getOpenIdToken() {
        const path = utils.encodeUri("/user/$userId/openid/request_token", {
            $userId: this.credentials.userId,
        });
        return this.http.authedRequest(undefined, "POST", path, undefined, {});
    }
    /**
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    turnServer(callback) {
        return this.http.authedRequest(callback, "GET", "/voip/turnServer");
    }
    /**
     * Get the TURN servers for this home server.
     * @return {Array<Object>} The servers or an empty list.
     */
    getTurnServers() {
        return this.turnServers || [];
    }
    /**
     * Get the unix timestamp (in seconds) at which the current
     * TURN credentials (from getTurnServers) expire
     * @return {number} The expiry timestamp, in seconds, or null if no credentials
     */
    getTurnServersExpiry() {
        return this.turnServersExpiry;
    }
    // XXX: Intended private, used in code.
    checkTurnServers() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.canSupportVoip) {
                return;
            }
            let credentialsGood = false;
            const remainingTime = this.turnServersExpiry - Date.now();
            if (remainingTime > TURN_CHECK_INTERVAL) {
                logger_1.logger.debug("TURN creds are valid for another " + remainingTime + " ms: not fetching new ones.");
                credentialsGood = true;
            }
            else {
                logger_1.logger.debug("Fetching new TURN credentials");
                try {
                    const res = yield this.turnServer();
                    if (res.uris) {
                        logger_1.logger.log("Got TURN URIs: " + res.uris + " refresh in " + res.ttl + " secs");
                        // map the response to a format that can be fed to RTCPeerConnection
                        const servers = {
                            urls: res.uris,
                            username: res.username,
                            credential: res.password,
                        };
                        this.turnServers = [servers];
                        // The TTL is in seconds but we work in ms
                        this.turnServersExpiry = Date.now() + (res.ttl * 1000);
                        credentialsGood = true;
                    }
                }
                catch (err) {
                    logger_1.logger.error("Failed to get TURN URIs", err);
                    // If we get a 403, there's no point in looping forever.
                    if (err.httpStatus === 403) {
                        logger_1.logger.info("TURN access unavailable for this account: stopping credentials checks");
                        if (this.checkTurnServersIntervalID !== null)
                            global.clearInterval(this.checkTurnServersIntervalID);
                        this.checkTurnServersIntervalID = null;
                    }
                }
                // otherwise, if we failed for whatever reason, try again the next time we're called.
            }
            return credentialsGood;
        });
    }
    /**
     * Set whether to allow a fallback ICE server should be used for negotiating a
     * WebRTC connection if the homeserver doesn't provide any servers. Defaults to
     * false.
     *
     * @param {boolean} allow
     */
    setFallbackICEServerAllowed(allow) {
        this.fallbackICEServerAllowed = allow;
    }
    /**
     * Get whether to allow a fallback ICE server should be used for negotiating a
     * WebRTC connection if the homeserver doesn't provide any servers. Defaults to
     * false.
     *
     * @returns {boolean}
     */
    isFallbackICEServerAllowed() {
        return this.fallbackICEServerAllowed;
    }
    /**
     * Determines if the current user is an administrator of the Synapse homeserver.
     * Returns false if untrue or the homeserver does not appear to be a Synapse
     * homeserver. <strong>This function is implementation specific and may change
     * as a result.</strong>
     * @return {boolean} true if the user appears to be a Synapse administrator.
     */
    isSynapseAdministrator() {
        const path = utils.encodeUri("/_synapse/admin/v1/users/$userId/admin", { $userId: this.getUserId() });
        return this.http.authedRequest(undefined, 'GET', path, undefined, undefined, { prefix: '' }).then(r => r['admin']); // pull out the specific boolean we want
    }
    /**
     * Performs a whois lookup on a user using Synapse's administrator API.
     * <strong>This function is implementation specific and may change as a
     * result.</strong>
     * @param {string} userId the User ID to look up.
     * @return {object} the whois response - see Synapse docs for information.
     */
    whoisSynapseUser(userId) {
        const path = utils.encodeUri("/_synapse/admin/v1/whois/$userId", { $userId: userId });
        return this.http.authedRequest(undefined, 'GET', path, undefined, undefined, { prefix: '' });
    }
    /**
     * Deactivates a user using Synapse's administrator API. <strong>This
     * function is implementation specific and may change as a result.</strong>
     * @param {string} userId the User ID to deactivate.
     * @return {object} the deactivate response - see Synapse docs for information.
     */
    deactivateSynapseUser(userId) {
        const path = utils.encodeUri("/_synapse/admin/v1/deactivate/$userId", { $userId: userId });
        return this.http.authedRequest(undefined, 'POST', path, undefined, undefined, { prefix: '' });
    }
    fetchClientWellKnown() {
        return __awaiter(this, void 0, void 0, function* () {
            // `getRawClientConfig` does not throw or reject on network errors, instead
            // it absorbs errors and returns `{}`.
            this.clientWellKnownPromise = autodiscovery_1.AutoDiscovery.getRawClientConfig(this.getDomain());
            this.clientWellKnown = yield this.clientWellKnownPromise;
            this.emit("WellKnown.client", this.clientWellKnown);
        });
    }
    getClientWellKnown() {
        return this.clientWellKnown;
    }
    waitForClientWellKnown() {
        return this.clientWellKnownPromise;
    }
    /**
     * store client options with boolean/string/numeric values
     * to know in the next session what flags the sync data was
     * created with (e.g. lazy loading)
     * @param {object} opts the complete set of client options
     * @return {Promise} for store operation
     */
    storeClientOptions() {
        const primTypes = ["boolean", "string", "number"];
        const serializableOpts = Object.entries(this.clientOpts)
            .filter(([key, value]) => {
            return primTypes.includes(typeof value);
        })
            .reduce((obj, [key, value]) => {
            obj[key] = value;
            return obj;
        }, {});
        return this.store.storeClientOptions(serializableOpts);
    }
    /**
     * Gets a set of room IDs in common with another user
     * @param {string} userId The userId to check.
     * @return {Promise<string[]>} Resolves to a set of rooms
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    _unstable_getSharedRooms(userId) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!(yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"))) {
                throw Error('Server does not support shared_rooms API');
            }
            const path = utils.encodeUri("/uk.half-shot.msc2666/user/shared_rooms/$userId", {
                $userId: userId,
            });
            const res = yield this.http.authedRequest(undefined, "GET", path, undefined, undefined, { prefix: http_api_1.PREFIX_UNSTABLE });
            return res.joined;
        });
    }
    /**
     * Get the API versions supported by the server, along with any
     * unstable APIs it supports
     * @return {Promise<object>} The server /versions response
     */
    getVersions() {
        if (this.serverVersionsPromise) {
            return this.serverVersionsPromise;
        }
        this.serverVersionsPromise = this.http.request(undefined, // callback
        "GET", "/_matrix/client/versions", undefined, // queryParams
        undefined, // data
        {
            prefix: '',
        }).catch((e) => {
            // Need to unset this if it fails, otherwise we'll never retry
            this.serverVersionsPromise = null;
            // but rethrow the exception to anything that was waiting
            throw e;
        });
        return this.serverVersionsPromise;
    }
    /**
     * Check if a particular spec version is supported by the server.
     * @param {string} version The spec version (such as "r0.5.0") to check for.
     * @return {Promise<bool>} Whether it is supported
     */
    isVersionSupported(version) {
        return __awaiter(this, void 0, void 0, function* () {
            const { versions } = yield this.getVersions();
            return versions && versions.includes(version);
        });
    }
    /**
     * Query the server to see if it support members lazy loading
     * @return {Promise<boolean>} true if server supports lazy loading
     */
    doesServerSupportLazyLoading() {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return false;
            const versions = response["versions"];
            const unstableFeatures = response["unstable_features"];
            return (versions && versions.includes("r0.5.0"))
                || (unstableFeatures && unstableFeatures["m.lazy_load_members"]);
        });
    }
    /**
     * Query the server to see if the `id_server` parameter is required
     * when registering with an 3pid, adding a 3pid or resetting password.
     * @return {Promise<boolean>} true if id_server parameter is required
     */
    doesServerRequireIdServerParam() {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return true;
            const versions = response["versions"];
            // Supporting r0.6.0 is the same as having the flag set to false
            if (versions && versions.includes("r0.6.0")) {
                return false;
            }
            const unstableFeatures = response["unstable_features"];
            if (!unstableFeatures)
                return true;
            if (unstableFeatures["m.require_identity_server"] === undefined) {
                return true;
            }
            else {
                return unstableFeatures["m.require_identity_server"];
            }
        });
    }
    /**
     * Query the server to see if the `id_access_token` parameter can be safely
     * passed to the homeserver. Some homeservers may trigger errors if they are not
     * prepared for the new parameter.
     * @return {Promise<boolean>} true if id_access_token can be sent
     */
    doesServerAcceptIdentityAccessToken() {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return false;
            const versions = response["versions"];
            const unstableFeatures = response["unstable_features"];
            return (versions && versions.includes("r0.6.0"))
                || (unstableFeatures && unstableFeatures["m.id_access_token"]);
        });
    }
    /**
     * Query the server to see if it supports separate 3PID add and bind functions.
     * This affects the sequence of API calls clients should use for these operations,
     * so it's helpful to be able to check for support.
     * @return {Promise<boolean>} true if separate functions are supported
     */
    doesServerSupportSeparateAddAndBind() {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return false;
            const versions = response["versions"];
            const unstableFeatures = response["unstable_features"];
            return (versions && versions.includes("r0.6.0"))
                || (unstableFeatures && unstableFeatures["m.separate_add_and_bind"]);
        });
    }
    /**
     * Query the server to see if it lists support for an unstable feature
     * in the /versions response
     * @param {string} feature the feature name
     * @return {Promise<boolean>} true if the feature is supported
     */
    doesServerSupportUnstableFeature(feature) {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return false;
            const unstableFeatures = response["unstable_features"];
            return unstableFeatures && !!unstableFeatures[feature];
        });
    }
    /**
     * Query the server to see if it is forcing encryption to be enabled for
     * a given room preset, based on the /versions response.
     * @param {Preset} presetName The name of the preset to check.
     * @returns {Promise<boolean>} true if the server is forcing encryption
     * for the preset.
     */
    doesServerForceEncryptionForPreset(presetName) {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getVersions();
            if (!response)
                return false;
            const unstableFeatures = response["unstable_features"];
            // The preset name in the versions response will be without the _chat suffix.
            const versionsPresetName = presetName.includes("_chat")
                ? presetName.substring(0, presetName.indexOf("_chat"))
                : presetName;
            return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];
        });
    }
    /**
     * Get if lazy loading members is being used.
     * @return {boolean} Whether or not members are lazy loaded by this client
     */
    hasLazyLoadMembersEnabled() {
        return !!this.clientOpts.lazyLoadMembers;
    }
    /**
     * Set a function which is called when /sync returns a 'limited' response.
     * It is called with a room ID and returns a boolean. It should return 'true' if the SDK
     * can SAFELY remove events from this room. It may not be safe to remove events if there
     * are other references to the timelines for this room, e.g because the client is
     * actively viewing events in this room.
     * Default: returns false.
     * @param {Function} cb The callback which will be invoked.
     */
    setCanResetTimelineCallback(cb) {
        this.canResetTimelineCallback = cb;
    }
    /**
     * Get the callback set via `setCanResetTimelineCallback`.
     * @return {?Function} The callback or null
     */
    getCanResetTimelineCallback() {
        return this.canResetTimelineCallback;
    }
    /**
     * Returns relations for a given event. Handles encryption transparently,
     * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.
     * When the returned promise resolves, all messages should have finished trying to decrypt.
     * @param {string} roomId the room of the event
     * @param {string} eventId the id of the event
     * @param {string} relationType the rel_type of the relations requested
     * @param {string} eventType the event type of the relations requested
     * @param {Object} opts options with optional values for the request.
     * @param {Object} opts.from the pagination token returned from a previous request as `nextBatch` to return following relations.
     * @return {Object} an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.
     */
    relations(roomId, eventId, relationType, eventType, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const fetchedEventType = this.getEncryptedIfNeededEventType(roomId, eventType);
            const result = yield this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts);
            const mapper = this.getEventMapper();
            let originalEvent;
            if (result.original_event) {
                originalEvent = mapper(result.original_event);
            }
            let events = result.chunk.map(mapper);
            if (fetchedEventType === "m.room.encrypted") {
                const allEvents = originalEvent ? events.concat(originalEvent) : events;
                yield Promise.all(allEvents.map(e => {
                    return new Promise(resolve => e.once("Event.decrypted", resolve));
                }));
                events = events.filter(e => e.getType() === eventType);
            }
            if (originalEvent && relationType === "m.replace") {
                events = events.filter(e => e.getSender() === originalEvent.getSender());
            }
            return {
                originalEvent,
                events,
                nextBatch: result.next_batch,
            };
        });
    }
    /**
     * The app may wish to see if we have a key cached without
     * triggering a user interaction.
     * @return {object}
     */
    getCrossSigningCacheCallbacks() {
        var _a;
        // XXX: Private member access
        return (_a = this.crypto) === null || _a === void 0 ? void 0 : _a.crossSigningInfo.getCacheCallbacks();
    }
    /**
     * Generates a random string suitable for use as a client secret. <strong>This
     * method is experimental and may change.</strong>
     * @return {string} A new client secret
     */
    generateClientSecret() {
        return randomstring_1.randomString(32);
    }
    /**
     * Attempts to decrypt an event
     * @param {MatrixEvent} event The event to decrypt
     * @returns {Promise<void>} A decryption promise
     * @param {object} options
     * @param {boolean} options.isRetry True if this is a retry (enables more logging)
     * @param {boolean} options.emit Emits "event.decrypted" if set to true
     */
    decryptEventIfNeeded(event, options) {
        if (event.shouldAttemptDecryption()) {
            event.attemptDecryption(this.crypto, options);
        }
        if (event.isBeingDecrypted()) {
            return event.getDecryptionPromise();
        }
        else {
            return Promise.resolve();
        }
    }
    termsUrlForService(serviceType, baseUrl) {
        switch (serviceType) {
            case service_types_1.SERVICE_TYPES.IS:
                return baseUrl + http_api_1.PREFIX_IDENTITY_V2 + '/terms';
            case service_types_1.SERVICE_TYPES.IM:
                return baseUrl + '/_matrix/integrations/v1/terms';
            default:
                throw new Error('Unsupported service type');
        }
    }
    /**
     * Get the Homeserver URL of this client
     * @return {string} Homeserver URL of this client
     */
    getHomeserverUrl() {
        return this.baseUrl;
    }
    /**
     * Get the Identity Server URL of this client
     * @param {boolean} stripProto whether or not to strip the protocol from the URL
     * @return {string} Identity Server URL of this client
     */
    getIdentityServerUrl(stripProto = false) {
        if (stripProto && (this.idBaseUrl.startsWith("http://") ||
            this.idBaseUrl.startsWith("https://"))) {
            return this.idBaseUrl.split("://")[1];
        }
        return this.idBaseUrl;
    }
    /**
     * Set the Identity Server URL of this client
     * @param {string} url New Identity Server URL
     */
    setIdentityServerUrl(url) {
        this.idBaseUrl = utils.ensureNoTrailingSlash(url);
        this.http.setIdBaseUrl(this.idBaseUrl);
    }
    /**
     * Get the access token associated with this account.
     * @return {?String} The access_token or null
     */
    getAccessToken() {
        return this.http.opts.accessToken || null;
    }
    /**
     * @return {boolean} true if there is a valid access_token for this client.
     */
    isLoggedIn() {
        return this.http.opts.accessToken !== undefined;
    }
    /**
     * Make up a new transaction id
     *
     * @return {string} a new, unique, transaction id
     */
    makeTxnId() {
        return "m" + new Date().getTime() + "." + (this.txnCtr++);
    }
    /**
     * Check whether a username is available prior to registration. An error response
     * indicates an invalid/unavailable username.
     * @param {string} username The username to check the availability of.
     * @return {Promise} Resolves: to `true`.
     */
    isUsernameAvailable(username) {
        return this.http.authedRequest(undefined, "GET", '/register/available', { username: username }).then((response) => {
            return response.available;
        });
    }
    /**
     * @param {string} username
     * @param {string} password
     * @param {string} sessionId
     * @param {Object} auth
     * @param {Object} bindThreepids Set key 'email' to true to bind any email
     *     threepid uses during registration in the ID server. Set 'msisdn' to
     *     true to bind msisdn.
     * @param {string} guestAccessToken
     * @param {string} inhibitLogin
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    register(username, password, sessionId, auth, bindThreepids, guestAccessToken, inhibitLogin, callback) {
        // backwards compat
        if (bindThreepids === true) {
            bindThreepids = { email: true };
        }
        else if (bindThreepids === null || bindThreepids === undefined) {
            bindThreepids = {};
        }
        if (typeof inhibitLogin === 'function') {
            callback = inhibitLogin;
            inhibitLogin = undefined;
        }
        if (sessionId) {
            auth.session = sessionId;
        }
        const params = {
            auth: auth,
        };
        if (username !== undefined && username !== null) {
            params.username = username;
        }
        if (password !== undefined && password !== null) {
            params.password = password;
        }
        if (bindThreepids.email) {
            params.bind_email = true;
        }
        if (bindThreepids.msisdn) {
            params.bind_msisdn = true;
        }
        if (guestAccessToken !== undefined && guestAccessToken !== null) {
            params.guest_access_token = guestAccessToken;
        }
        if (inhibitLogin !== undefined && inhibitLogin !== null) {
            params.inhibit_login = inhibitLogin;
        }
        // Temporary parameter added to make the register endpoint advertise
        // msisdn flows. This exists because there are clients that break
        // when given stages they don't recognise. This parameter will cease
        // to be necessary once these old clients are gone.
        // Only send it if we send any params at all (the password param is
        // mandatory, so if we send any params, we'll send the password param)
        if (password !== undefined && password !== null) {
            params.x_show_msisdn = true;
        }
        return this.registerRequest(params, undefined, callback);
    }
    /**
     * Register a guest account.
     * This method returns the auth info needed to create a new authenticated client,
     * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:
     * ```javascript
     * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);
     * const { user_id, device_id, access_token } = tmpClient.registerGuest();
     * const client = createClient({
     *   baseUrl: MATRIX_INSTANCE,
     *   accessToken: access_token,
     *   userId: user_id,
     *   deviceId: device_id,
     * })
     * client.setGuest(true);
     * ```
     *
     * @param {Object=} opts Registration options
     * @param {Object} opts.body JSON HTTP body to provide.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: JSON object that contains:
     *                   { user_id, device_id, access_token, home_server }
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    registerGuest(opts, callback) {
        opts = opts || {};
        opts.body = opts.body || {};
        return this.registerRequest(opts.body, "guest", callback);
    }
    /**
     * @param {Object} data   parameters for registration request
     * @param {string=} kind  type of user to register. may be "guest"
     * @param {module:client.callback=} callback
     * @return {Promise} Resolves: to the /register response
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    registerRequest(data, kind, callback) {
        const params = {};
        if (kind) {
            params.kind = kind;
        }
        return this.http.request(callback, "POST", "/register", params, data);
    }
    /**
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    loginFlows(callback) {
        return this.http.request(callback, "GET", "/login");
    }
    /**
     * @param {string} loginType
     * @param {Object} data
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    login(loginType, data, callback) {
        const loginData = {
            type: loginType,
        };
        // merge data into loginData
        utils.extend(loginData, data);
        return this.http.authedRequest((error, response) => {
            if (response && response.access_token && response.user_id) {
                this.http.opts.accessToken = response.access_token;
                this.credentials = {
                    userId: response.user_id,
                };
            }
            if (callback) {
                callback(error, response);
            }
        }, "POST", "/login", undefined, loginData);
    }
    /**
     * @param {string} user
     * @param {string} password
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    loginWithPassword(user, password, callback) {
        return this.login("m.login.password", {
            user: user,
            password: password,
        }, callback);
    }
    /**
     * @param {string} relayState URL Callback after SAML2 Authentication
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    loginWithSAML2(relayState, callback) {
        return this.login("m.login.saml2", {
            relay_state: relayState,
        }, callback);
    }
    /**
     * @param {string} redirectUrl The URL to redirect to after the HS
     * authenticates with CAS.
     * @return {string} The HS URL to hit to begin the CAS login process.
     */
    getCasLoginUrl(redirectUrl) {
        return this.getSsoLoginUrl(redirectUrl, "cas");
    }
    /**
     * @param {string} redirectUrl The URL to redirect to after the HS
     *     authenticates with the SSO.
     * @param {string} loginType The type of SSO login we are doing (sso or cas).
     *     Defaults to 'sso'.
     * @param {string} idpId The ID of the Identity Provider being targeted, optional.
     * @return {string} The HS URL to hit to begin the SSO login process.
     */
    getSsoLoginUrl(redirectUrl, loginType = "sso", idpId) {
        let url = "/login/" + loginType + "/redirect";
        if (idpId) {
            url += "/" + idpId;
        }
        return this.http.getUrl(url, { redirectUrl }, http_api_1.PREFIX_R0);
    }
    /**
     * @param {string} token Login token previously received from homeserver
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    loginWithToken(token, callback) {
        return this.login("m.login.token", {
            token: token,
        }, callback);
    }
    /**
     * Logs out the current session.
     * Obviously, further calls that require authorisation should fail after this
     * method is called. The state of the MatrixClient object is not affected:
     * it is up to the caller to either reset or destroy the MatrixClient after
     * this method succeeds.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: On success, the empty object
     */
    logout(callback) {
        return this.http.authedRequest(callback, "POST", '/logout');
    }
    /**
     * Deactivates the logged-in account.
     * Obviously, further calls that require authorisation should fail after this
     * method is called. The state of the MatrixClient object is not affected:
     * it is up to the caller to either reset or destroy the MatrixClient after
     * this method succeeds.
     * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
     * @param {boolean} erase Optional. If set, send as `erase` attribute in the
     * JSON request body, indicating whether the account should be erased. Defaults
     * to false.
     * @return {Promise} Resolves: On success, the empty object
     */
    deactivateAccount(auth, erase) {
        if (typeof (erase) === 'function') {
            throw new Error('deactivateAccount no longer accepts a callback parameter');
        }
        const body = {};
        if (auth) {
            body.auth = auth;
        }
        if (erase !== undefined) {
            body.erase = erase;
        }
        return this.http.authedRequest(undefined, "POST", '/account/deactivate', undefined, body);
    }
    /**
     * Get the fallback URL to use for unknown interactive-auth stages.
     *
     * @param {string} loginType     the type of stage being attempted
     * @param {string} authSessionId the auth session ID provided by the homeserver
     *
     * @return {string} HS URL to hit to for the fallback interface
     */
    getFallbackAuthUrl(loginType, authSessionId) {
        const path = utils.encodeUri("/auth/$loginType/fallback/web", {
            $loginType: loginType,
        });
        return this.http.getUrl(path, {
            session: authSessionId,
        }, http_api_1.PREFIX_R0);
    }
    /**
     * Create a new room.
     * @param {Object} options a list of options to pass to the /createRoom API.
     * @param {string} options.room_alias_name The alias localpart to assign to
     * this room.
     * @param {string} options.visibility Either 'public' or 'private'.
     * @param {string[]} options.invite A list of user IDs to invite to this room.
     * @param {string} options.name The name to give this room.
     * @param {string} options.topic The topic to give this room.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: <code>{room_id: {string},
     * room_alias: {string(opt)}}</code>
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    createRoom(options, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            // some valid options include: room_alias_name, visibility, invite
            // inject the id_access_token if inviting 3rd party addresses
            const invitesNeedingToken = (options.invite_3pid || [])
                .filter(i => !i.id_access_token);
            if (invitesNeedingToken.length > 0 &&
                this.identityServer &&
                this.identityServer.getAccessToken &&
                (yield this.doesServerAcceptIdentityAccessToken())) {
                const identityAccessToken = yield this.identityServer.getAccessToken();
                if (identityAccessToken) {
                    for (const invite of invitesNeedingToken) {
                        invite.id_access_token = identityAccessToken;
                    }
                }
            }
            return this.http.authedRequest(callback, "POST", "/createRoom", undefined, options);
        });
    }
    /**
     * Fetches relations for a given event
     * @param {string} roomId the room of the event
     * @param {string} eventId the id of the event
     * @param {string} relationType the rel_type of the relations requested
     * @param {string} eventType the event type of the relations requested
     * @param {Object} opts options with optional values for the request.
     * @param {Object} opts.from the pagination token returned from a previous request as `next_batch` to return following relations.
     * @return {Object} the response, with chunk and next_batch.
     */
    fetchRelations(roomId, eventId, relationType, eventType, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const queryParams = {};
            if (opts.from) {
                queryParams.from = opts.from;
            }
            const queryString = utils.encodeParams(queryParams);
            const path = utils.encodeUri("/rooms/$roomId/relations/$eventId/$relationType/$eventType?" + queryString, {
                $roomId: roomId,
                $eventId: eventId,
                $relationType: relationType,
                $eventType: eventType,
            });
            return yield this.http.authedRequest(undefined, "GET", path, null, null, {
                prefix: http_api_1.PREFIX_UNSTABLE,
            });
        });
    }
    /**
     * @param {string} roomId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    roomState(roomId, callback) {
        const path = utils.encodeUri("/rooms/$roomId/state", { $roomId: roomId });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * Get an event in a room by its event id.
     * @param {string} roomId
     * @param {string} eventId
     * @param {module:client.callback} callback Optional.
     *
     * @return {Promise} Resolves to an object containing the event.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    fetchRoomEvent(roomId, eventId, callback) {
        const path = utils.encodeUri("/rooms/$roomId/event/$eventId", {
            $roomId: roomId,
            $eventId: eventId,
        });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * @param {string} roomId
     * @param {string} includeMembership the membership type to include in the response
     * @param {string} excludeMembership the membership type to exclude from the response
     * @param {string} atEventId the id of the event for which moment in the timeline the members should be returned for
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: dictionary of userid to profile information
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    members(roomId, includeMembership, excludeMembership, atEventId, callback) {
        const queryParams = {};
        if (includeMembership) {
            queryParams.membership = includeMembership;
        }
        if (excludeMembership) {
            queryParams.not_membership = excludeMembership;
        }
        if (atEventId) {
            queryParams.at = atEventId;
        }
        const queryString = utils.encodeParams(queryParams);
        const path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: roomId });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * Upgrades a room to a new protocol version
     * @param {string} roomId
     * @param {string} newVersion The target version to upgrade to
     * @return {Promise} Resolves: Object with key 'replacement_room'
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    upgradeRoom(roomId, newVersion) {
        const path = utils.encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId });
        return this.http.authedRequest(undefined, "POST", path, undefined, { new_version: newVersion });
    }
    /**
     * Retrieve a state event.
     * @param {string} roomId
     * @param {string} eventType
     * @param {string} stateKey
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getStateEvent(roomId, eventType, stateKey, callback) {
        const pathParams = {
            $roomId: roomId,
            $eventType: eventType,
            $stateKey: stateKey,
        };
        let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams);
        if (stateKey !== undefined) {
            path = utils.encodeUri(path + "/$stateKey", pathParams);
        }
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * @param {string} roomId
     * @param {string} eventType
     * @param {Object} content
     * @param {string} stateKey
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    sendStateEvent(roomId, eventType, content, stateKey = "", callback) {
        const pathParams = {
            $roomId: roomId,
            $eventType: eventType,
            $stateKey: stateKey,
        };
        let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams);
        if (stateKey !== undefined) {
            path = utils.encodeUri(path + "/$stateKey", pathParams);
        }
        return this.http.authedRequest(callback, "PUT", path, undefined, content);
    }
    /**
     * @param {string} roomId
     * @param {Number} limit
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    roomInitialSync(roomId, limit, callback) {
        if (utils.isFunction(limit)) {
            callback = limit; // legacy
            limit = undefined;
        }
        const path = utils.encodeUri("/rooms/$roomId/initialSync", { $roomId: roomId });
        if (!limit) {
            limit = 30;
        }
        return this.http.authedRequest(callback, "GET", path, { limit: limit });
    }
    /**
     * Set a marker to indicate the point in a room before which the user has read every
     * event. This can be retrieved from room account data (the event type is `m.fully_read`)
     * and displayed as a horizontal line in the timeline that is visually distinct to the
     * position of the user's own read receipt.
     * @param {string} roomId ID of the room that has been read
     * @param {string} rmEventId ID of the event that has been read
     * @param {string} rrEventId ID of the event tracked by the read receipt. This is here
     * for convenience because the RR and the RM are commonly updated at the same time as
     * each other. Optional.
     * @param {object} opts Options for the read markers.
     * @param {object} opts.hidden True to hide the read receipt from other users. <b>This
     * property is currently unstable and may change in the future.</b>
     * @return {Promise} Resolves: the empty object, {}.
     */
    setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, opts) {
        const path = utils.encodeUri("/rooms/$roomId/read_markers", {
            $roomId: roomId,
        });
        const content = {
            "m.fully_read": rmEventId,
            "m.read": rrEventId,
            "m.hidden": Boolean(opts ? opts.hidden : false),
        };
        return this.http.authedRequest(undefined, "POST", path, undefined, content);
    }
    /**
     * @return {Promise} Resolves: A list of the user's current rooms
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getJoinedRooms() {
        const path = utils.encodeUri("/joined_rooms", {});
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * Retrieve membership info. for a room.
     * @param {string} roomId ID of the room to get membership for
     * @return {Promise} Resolves: A list of currently joined users
     *                                 and their profile data.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getJoinedRoomMembers(roomId) {
        const path = utils.encodeUri("/rooms/$roomId/joined_members", {
            $roomId: roomId,
        });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {Object} options Options for this request
     * @param {string} options.server The remote server to query for the room list.
     *                                Optional. If unspecified, get the local home
     *                                server's public room list.
     * @param {number} options.limit Maximum number of entries to return
     * @param {string} options.since Token to paginate from
     * @param {object} options.filter Filter parameters
     * @param {string} options.filter.generic_search_term String to search for
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    publicRooms(options, callback) {
        if (typeof (options) == 'function') {
            callback = options;
            options = {};
        }
        if (options === undefined) {
            options = {};
        }
        const queryParams = {};
        if (options.server) {
            queryParams.server = options.server;
            delete options.server;
        }
        if (Object.keys(options).length === 0 && Object.keys(queryParams).length === 0) {
            return this.http.authedRequest(callback, "GET", "/publicRooms");
        }
        else {
            return this.http.authedRequest(callback, "POST", "/publicRooms", queryParams, options);
        }
    }
    /**
     * Create an alias to room ID mapping.
     * @param {string} alias The room alias to create.
     * @param {string} roomId The room ID to link the alias to.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    createAlias(alias, roomId, callback) {
        const path = utils.encodeUri("/directory/room/$alias", {
            $alias: alias,
        });
        const data = {
            room_id: roomId,
        };
        return this.http.authedRequest(callback, "PUT", path, undefined, data);
    }
    /**
     * Delete an alias to room ID mapping.  This alias must be on your local server
     * and you must have sufficient access to do this operation.
     * @param {string} alias The room alias to delete.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deleteAlias(alias, callback) {
        const path = utils.encodeUri("/directory/room/$alias", {
            $alias: alias,
        });
        return this.http.authedRequest(callback, "DELETE", path, undefined, undefined);
    }
    /**
     * @param {string} roomId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: an object with an `aliases` property, containing an array of local aliases
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    unstableGetLocalAliases(roomId, callback) {
        const path = utils.encodeUri("/rooms/$roomId/aliases", { $roomId: roomId });
        const prefix = http_api_1.PREFIX_UNSTABLE + "/org.matrix.msc2432";
        return this.http.authedRequest(callback, "GET", path, null, null, { prefix });
    }
    /**
     * Get room info for the given alias.
     * @param {string} alias The room alias to resolve.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Object with room_id and servers.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getRoomIdForAlias(alias, callback) {
        // TODO: deprecate this or resolveRoomAlias
        const path = utils.encodeUri("/directory/room/$alias", {
            $alias: alias,
        });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * @param {string} roomAlias
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    resolveRoomAlias(roomAlias, callback) {
        // TODO: deprecate this or getRoomIdForAlias
        const path = utils.encodeUri("/directory/room/$alias", { $alias: roomAlias });
        return this.http.request(callback, "GET", path);
    }
    /**
     * Get the visibility of a room in the current HS's room directory
     * @param {string} roomId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getRoomDirectoryVisibility(roomId, callback) {
        const path = utils.encodeUri("/directory/list/room/$roomId", {
            $roomId: roomId,
        });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * Set the visbility of a room in the current HS's room directory
     * @param {string} roomId
     * @param {string} visibility "public" to make the room visible
     *                 in the public directory, or "private" to make
     *                 it invisible.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomDirectoryVisibility(roomId, visibility, callback) {
        const path = utils.encodeUri("/directory/list/room/$roomId", {
            $roomId: roomId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility });
    }
    /**
     * Set the visbility of a room bridged to a 3rd party network in
     * the current HS's room directory.
     * @param {string} networkId the network ID of the 3rd party
     *                 instance under which this room is published under.
     * @param {string} roomId
     * @param {string} visibility "public" to make the room visible
     *                 in the public directory, or "private" to make
     *                 it invisible.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setRoomDirectoryVisibilityAppService(networkId, roomId, visibility, callback) {
        const path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", {
            $networkId: networkId,
            $roomId: roomId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility });
    }
    /**
     * Query the user directory with a term matching user IDs, display names and domains.
     * @param {object} opts options
     * @param {string} opts.term the term with which to search.
     * @param {number} opts.limit the maximum number of results to return. The server will
     *                 apply a limit if unspecified.
     * @return {Promise} Resolves: an array of results.
     */
    searchUserDirectory(opts) {
        const body = {
            search_term: opts.term,
        };
        if (opts.limit !== undefined) {
            body.limit = opts.limit;
        }
        return this.http.authedRequest(undefined, "POST", "/user_directory/search", undefined, body);
    }
    /**
     * Upload a file to the media repository on the home server.
     *
     * @param {object} file The object to upload. On a browser, something that
     *   can be sent to XMLHttpRequest.send (typically a File).  Under node.js,
     *   a a Buffer, String or ReadStream.
     *
     * @param {object} opts  options object
     *
     * @param {string=} opts.name   Name to give the file on the server. Defaults
     *   to <tt>file.name</tt>.
     *
     * @param {boolean=} opts.includeFilename if false will not send the filename,
     *   e.g for encrypted file uploads where filename leaks are undesirable.
     *   Defaults to true.
     *
     * @param {string=} opts.type   Content-type for the upload. Defaults to
     *   <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.
     *
     * @param {boolean=} opts.rawResponse Return the raw body, rather than
     *   parsing the JSON. Defaults to false (except on node.js, where it
     *   defaults to true for backwards compatibility).
     *
     * @param {boolean=} opts.onlyContentUri Just return the content URI,
     *   rather than the whole body. Defaults to false (except on browsers,
     *   where it defaults to true for backwards compatibility). Ignored if
     *   opts.rawResponse is true.
     *
     * @param {Function=} opts.callback Deprecated. Optional. The callback to
     *    invoke on success/failure. See the promise return values for more
     *    information.
     *
     * @param {Function=} opts.progressHandler Optional. Called when a chunk of
     *    data has been uploaded, with an object containing the fields `loaded`
     *    (number of bytes transferred) and `total` (total size, if known).
     *
     * @return {Promise} Resolves to response object, as
     *    determined by this.opts.onlyData, opts.rawResponse, and
     *    opts.onlyContentUri.  Rejects with an error (usually a MatrixError).
     */
    uploadContent(file, opts) {
        return this.http.uploadContent(file, opts);
    }
    /**
     * Cancel a file upload in progress
     * @param {Promise} promise The promise returned from uploadContent
     * @return {boolean} true if canceled, otherwise false
     */
    cancelUpload(promise) {
        return this.http.cancelUpload(promise);
    }
    /**
     * Get a list of all file uploads in progress
     * @return {array} Array of objects representing current uploads.
     * Currently in progress is element 0. Keys:
     *  - promise: The promise associated with the upload
     *  - loaded: Number of bytes uploaded
     *  - total: Total number of bytes to upload
     */
    getCurrentUploads() {
        return this.http.getCurrentUploads();
    }
    /**
     * @param {string} userId
     * @param {string} info The kind of info to retrieve (e.g. 'displayname',
     * 'avatar_url').
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getProfileInfo(userId, info, callback) {
        if (utils.isFunction(info)) {
            callback = info; // legacy
            info = undefined;
        }
        const path = info ?
            utils.encodeUri("/profile/$userId/$info", { $userId: userId, $info: info }) :
            utils.encodeUri("/profile/$userId", { $userId: userId });
        return this.http.authedRequest(callback, "GET", path);
    }
    /**
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getThreePids(callback) {
        const path = "/account/3pid";
        return this.http.authedRequest(callback, "GET", path, undefined, undefined);
    }
    /**
     * Add a 3PID to your homeserver account and optionally bind it to an identity
     * server as well. An identity server is required as part of the `creds` object.
     *
     * This API is deprecated, and you should instead use `addThreePidOnly`
     * for homeservers that support it.
     *
     * @param {Object} creds
     * @param {boolean} bind
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: on success
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addThreePid(creds, bind, callback) {
        const path = "/account/3pid";
        const data = {
            'threePidCreds': creds,
            'bind': bind,
        };
        return this.http.authedRequest(callback, "POST", path, null, data);
    }
    /**
     * Add a 3PID to your homeserver account. This API does not use an identity
     * server, as the homeserver is expected to handle 3PID ownership validation.
     *
     * You can check whether a homeserver supports this API via
     * `doesServerSupportSeparateAddAndBind`.
     *
     * @param {Object} data A object with 3PID validation data from having called
     * `account/3pid/<medium>/requestToken` on the homeserver.
     * @return {Promise} Resolves: on success
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addThreePidOnly(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = "/account/3pid/add";
            const prefix = (yield this.isVersionSupported("r0.6.0")) ?
                http_api_1.PREFIX_R0 : http_api_1.PREFIX_UNSTABLE;
            return this.http.authedRequest(undefined, "POST", path, null, data, { prefix });
        });
    }
    /**
     * Bind a 3PID for discovery onto an identity server via the homeserver. The
     * identity server handles 3PID ownership validation and the homeserver records
     * the new binding to track where all 3PIDs for the account are bound.
     *
     * You can check whether a homeserver supports this API via
     * `doesServerSupportSeparateAddAndBind`.
     *
     * @param {Object} data A object with 3PID validation data from having called
     * `validate/<medium>/requestToken` on the identity server. It should also
     * contain `id_server` and `id_access_token` fields as well.
     * @return {Promise} Resolves: on success
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    bindThreePid(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = "/account/3pid/bind";
            const prefix = (yield this.isVersionSupported("r0.6.0")) ?
                http_api_1.PREFIX_R0 : http_api_1.PREFIX_UNSTABLE;
            return this.http.authedRequest(undefined, "POST", path, null, data, { prefix });
        });
    }
    /**
     * Unbind a 3PID for discovery on an identity server via the homeserver. The
     * homeserver removes its record of the binding to keep an updated record of
     * where all 3PIDs for the account are bound.
     *
     * @param {string} medium The threepid medium (eg. 'email')
     * @param {string} address The threepid address (eg. 'bob@example.com')
     *        this must be as returned by getThreePids.
     * @return {Promise} Resolves: on success
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    unbindThreePid(medium, address) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = "/account/3pid/unbind";
            const data = {
                medium,
                address,
                id_server: this.getIdentityServerUrl(true),
            };
            const prefix = (yield this.isVersionSupported("r0.6.0")) ?
                http_api_1.PREFIX_R0 : http_api_1.PREFIX_UNSTABLE;
            return this.http.authedRequest(undefined, "POST", path, null, data, { prefix });
        });
    }
    /**
     * @param {string} medium The threepid medium (eg. 'email')
     * @param {string} address The threepid address (eg. 'bob@example.com')
     *        this must be as returned by getThreePids.
     * @return {Promise} Resolves: The server response on success
     *     (generally the empty JSON object)
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deleteThreePid(medium, address) {
        const path = "/account/3pid/delete";
        const data = {
            'medium': medium,
            'address': address,
        };
        return this.http.authedRequest(undefined, "POST", path, null, data);
    }
    /**
     * Make a request to change your password.
     * @param {Object} authDict
     * @param {string} newPassword The new desired password.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setPassword(authDict, newPassword, callback) {
        const path = "/account/password";
        const data = {
            'auth': authDict,
            'new_password': newPassword,
        };
        return this.http.authedRequest(callback, "POST", path, null, data);
    }
    /**
     * Gets all devices recorded for the logged-in user
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getDevices() {
        return this.http.authedRequest(undefined, 'GET', "/devices", undefined, undefined);
    }
    /**
     * Gets specific device details for the logged-in user
     * @param {string} deviceId  device to query
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getDevice(deviceId) {
        const path = utils.encodeUri("/devices/$device_id", {
            $device_id: deviceId,
        });
        return this.http.authedRequest(undefined, 'GET', path, undefined, undefined);
    }
    /**
     * Update the given device
     *
     * @param {string} deviceId  device to update
     * @param {Object} body       body of request
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setDeviceDetails(deviceId, body) {
        const path = utils.encodeUri("/devices/$device_id", {
            $device_id: deviceId,
        });
        return this.http.authedRequest(undefined, "PUT", path, undefined, body);
    }
    /**
     * Delete the given device
     *
     * @param {string} deviceId  device to delete
     * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deleteDevice(deviceId, auth) {
        const path = utils.encodeUri("/devices/$device_id", {
            $device_id: deviceId,
        });
        const body = {};
        if (auth) {
            body.auth = auth;
        }
        return this.http.authedRequest(undefined, "DELETE", path, undefined, body);
    }
    /**
     * Delete multiple device
     *
     * @param {string[]} devices IDs of the devices to delete
     * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deleteMultipleDevices(devices, auth) {
        const body = { devices };
        if (auth) {
            body.auth = auth;
        }
        const path = "/delete_devices";
        return this.http.authedRequest(undefined, "POST", path, undefined, body);
    }
    /**
     * Gets all pushers registered for the logged-in user
     *
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Array of objects representing pushers
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getPushers(callback) {
        const path = "/pushers";
        return this.http.authedRequest(callback, "GET", path, undefined, undefined);
    }
    /**
     * Adds a new pusher or updates an existing pusher
     *
     * @param {Object} pusher Object representing a pusher
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: Empty json object on success
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setPusher(pusher, callback) {
        const path = "/pushers/set";
        return this.http.authedRequest(callback, "POST", path, null, pusher);
    }
    /**
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getPushRules(callback) {
        return this.http.authedRequest(callback, "GET", "/pushrules/").then(rules => {
            return pushprocessor_1.PushProcessor.rewriteDefaultRules(rules);
        });
    }
    /**
     * @param {string} scope
     * @param {string} kind
     * @param {string} ruleId
     * @param {Object} body
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addPushRule(scope, kind, ruleId, body, callback) {
        // NB. Scope not uri encoded because devices need the '/'
        const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
            $kind: kind,
            $ruleId: ruleId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, body);
    }
    /**
     * @param {string} scope
     * @param {string} kind
     * @param {string} ruleId
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    deletePushRule(scope, kind, ruleId, callback) {
        // NB. Scope not uri encoded because devices need the '/'
        const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
            $kind: kind,
            $ruleId: ruleId,
        });
        return this.http.authedRequest(callback, "DELETE", path);
    }
    /**
     * Enable or disable a push notification rule.
     * @param {string} scope
     * @param {string} kind
     * @param {string} ruleId
     * @param {boolean} enabled
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setPushRuleEnabled(scope, kind, ruleId, enabled, callback) {
        const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", {
            $kind: kind,
            $ruleId: ruleId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, { "enabled": enabled });
    }
    /**
     * Set the actions for a push notification rule.
     * @param {string} scope
     * @param {string} kind
     * @param {string} ruleId
     * @param {array} actions
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: result object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setPushRuleActions(scope, kind, ruleId, actions, callback) {
        const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", {
            $kind: kind,
            $ruleId: ruleId,
        });
        return this.http.authedRequest(callback, "PUT", path, undefined, { "actions": actions });
    }
    /**
     * Perform a server-side search.
     * @param {Object} opts
     * @param {string} opts.next_batch the batch token to pass in the query string
     * @param {Object} opts.body the JSON object to pass to the request body.
     * @param {module:client.callback} callback Optional.
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    search(opts, // eslint-disable-line camelcase
    callback) {
        const queryParams = {};
        if (opts.next_batch) {
            queryParams.next_batch = opts.next_batch;
        }
        return this.http.authedRequest(callback, "POST", "/search", queryParams, opts.body);
    }
    /**
     * Upload keys
     *
     * @param {Object} content  body of upload request
     *
     * @param {Object=} opts this method no longer takes any opts,
     *  used to take opts.device_id but this was not removed from the spec as a redundant parameter
     *
     * @param {module:client.callback=} callback
     *
     * @return {Promise} Resolves: result object. Rejects: with
     *     an error response ({@link module:http-api.MatrixError}).
     */
    uploadKeysRequest(content, opts, callback) {
        return this.http.authedRequest(callback, "POST", "/keys/upload", undefined, content);
    }
    uploadKeySignatures(content) {
        return this.http.authedRequest(undefined, "POST", '/keys/signatures/upload', undefined, content, {
            prefix: http_api_1.PREFIX_UNSTABLE,
        });
    }
    /**
     * Download device keys
     *
     * @param {string[]} userIds  list of users to get keys for
     *
     * @param {Object=} opts
     *
     * @param {string=} opts.token   sync token to pass in the query request, to help
     *   the HS give the most recent results
     *
     * @return {Promise} Resolves: result object. Rejects: with
     *     an error response ({@link module:http-api.MatrixError}).
     */
    downloadKeysForUsers(userIds, opts) {
        if (utils.isFunction(opts)) {
            // opts used to be 'callback'.
            throw new Error('downloadKeysForUsers no longer accepts a callback parameter');
        }
        opts = opts || {};
        const content = {
            device_keys: {},
        };
        if ('token' in opts) {
            content.token = opts.token;
        }
        userIds.forEach((u) => {
            content.device_keys[u] = [];
        });
        return this.http.authedRequest(undefined, "POST", "/keys/query", undefined, content);
    }
    /**
     * Claim one-time keys
     *
     * @param {string[]} devices  a list of [userId, deviceId] pairs
     *
     * @param {string} [keyAlgorithm = signed_curve25519]  desired key type
     *
     * @param {number} [timeout] the time (in milliseconds) to wait for keys from remote
     *     servers
     *
     * @return {Promise} Resolves: result object. Rejects: with
     *     an error response ({@link module:http-api.MatrixError}).
     */
    claimOneTimeKeys(devices, keyAlgorithm = "signed_curve25519", timeout) {
        const queries = {};
        if (keyAlgorithm === undefined) {
            keyAlgorithm = "signed_curve25519";
        }
        for (let i = 0; i < devices.length; ++i) {
            const userId = devices[i][0];
            const deviceId = devices[i][1];
            const query = queries[userId] || {};
            queries[userId] = query;
            query[deviceId] = keyAlgorithm;
        }
        const content = { one_time_keys: queries };
        if (timeout) {
            content.timeout = timeout;
        }
        const path = "/keys/claim";
        return this.http.authedRequest(undefined, "POST", path, undefined, content);
    }
    /**
     * Ask the server for a list of users who have changed their device lists
     * between a pair of sync tokens
     *
     * @param {string} oldToken
     * @param {string} newToken
     *
     * @return {Promise} Resolves: result object. Rejects: with
     *     an error response ({@link module:http-api.MatrixError}).
     */
    getKeyChanges(oldToken, newToken) {
        const qps = {
            from: oldToken,
            to: newToken,
        };
        const path = "/keys/changes";
        return this.http.authedRequest(undefined, "GET", path, qps, undefined);
    }
    uploadDeviceSigningKeys(auth, keys) {
        const data = Object.assign({}, keys);
        if (auth)
            Object.assign(data, { auth });
        return this.http.authedRequest(undefined, "POST", "/keys/device_signing/upload", undefined, data, {
            prefix: http_api_1.PREFIX_UNSTABLE,
        });
    }
    /**
     * Register with an Identity Server using the OpenID token from the user's
     * Homeserver, which can be retrieved via
     * {@link module:client~MatrixClient#getOpenIdToken}.
     *
     * Note that the `/account/register` endpoint (as well as IS authentication in
     * general) was added as part of the v2 API version.
     *
     * @param {object} hsOpenIdToken
     * @return {Promise} Resolves: with object containing an Identity
     * Server access token.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    registerWithIdentityServer(hsOpenIdToken) {
        if (!this.idBaseUrl) {
            throw new Error("No Identity Server base URL set");
        }
        const uri = this.idBaseUrl + http_api_1.PREFIX_IDENTITY_V2 + "/account/register";
        return this.http.requestOtherUrl(undefined, "POST", uri, null, hsOpenIdToken);
    }
    /**
     * Requests an email verification token directly from an identity server.
     *
     * This API is used as part of binding an email for discovery on an identity
     * server. The validation data that results should be passed to the
     * `bindThreePid` method to complete the binding process.
     *
     * @param {string} email The email address to request a token for
     * @param {string} clientSecret A secret binary string generated by the client.
     *                 It is recommended this be around 16 ASCII characters.
     * @param {number} sendAttempt If an identity server sees a duplicate request
     *                 with the same sendAttempt, it will not send another email.
     *                 To request another email to be sent, use a larger value for
     *                 the sendAttempt param as was used in the previous request.
     * @param {string} nextLink Optional If specified, the client will be redirected
     *                 to this link after validation.
     * @param {module:client.callback} callback Optional.
     * @param {string} identityAccessToken The `access_token` field of the identity
     * server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     * @throws Error if no identity server is set
     */
    requestEmailToken(email, clientSecret, sendAttempt, nextLink, callback, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = {
                client_secret: clientSecret,
                email: email,
                send_attempt: sendAttempt,
                next_link: nextLink,
            };
            return yield this.http.idServerRequest(callback, "POST", "/validate/email/requestToken", params, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
        });
    }
    /**
     * Requests a MSISDN verification token directly from an identity server.
     *
     * This API is used as part of binding a MSISDN for discovery on an identity
     * server. The validation data that results should be passed to the
     * `bindThreePid` method to complete the binding process.
     *
     * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in
     *                 which phoneNumber should be parsed relative to.
     * @param {string} phoneNumber The phone number, in national or international
     *                 format
     * @param {string} clientSecret A secret binary string generated by the client.
     *                 It is recommended this be around 16 ASCII characters.
     * @param {number} sendAttempt If an identity server sees a duplicate request
     *                 with the same sendAttempt, it will not send another SMS.
     *                 To request another SMS to be sent, use a larger value for
     *                 the sendAttempt param as was used in the previous request.
     * @param {string} nextLink Optional If specified, the client will be redirected
     *                 to this link after validation.
     * @param {module:client.callback} callback Optional.
     * @param {string} identityAccessToken The `access_token` field of the Identity
     * Server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: TODO
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     * @throws Error if no identity server is set
     */
    requestMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink, callback, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = {
                client_secret: clientSecret,
                country: phoneCountry,
                phone_number: phoneNumber,
                send_attempt: sendAttempt,
                next_link: nextLink,
            };
            return yield this.http.idServerRequest(callback, "POST", "/validate/msisdn/requestToken", params, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
        });
    }
    /**
     * Submits a MSISDN token to the identity server
     *
     * This is used when submitting the code sent by SMS to a phone number.
     * The ID server has an equivalent API for email but the js-sdk does
     * not expose this, since email is normally validated by the user clicking
     * a link rather than entering a code.
     *
     * @param {string} sid The sid given in the response to requestToken
     * @param {string} clientSecret A secret binary string generated by the client.
     *                 This must be the same value submitted in the requestToken call.
     * @param {string} msisdnToken The MSISDN token, as enetered by the user.
     * @param {string} identityAccessToken The `access_token` field of the Identity
     * Server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: Object, currently with no parameters.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     * @throws Error if No ID server is set
     */
    submitMsisdnToken(sid, clientSecret, msisdnToken, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = {
                sid: sid,
                client_secret: clientSecret,
                token: msisdnToken,
            };
            return yield this.http.idServerRequest(undefined, "POST", "/validate/msisdn/submitToken", params, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
        });
    }
    /**
     * Submits a MSISDN token to an arbitrary URL.
     *
     * This is used when submitting the code sent by SMS to a phone number in the
     * newer 3PID flow where the homeserver validates 3PID ownership (as part of
     * `requestAdd3pidMsisdnToken`). The homeserver response may include a
     * `submit_url` to specify where the token should be sent, and this helper can
     * be used to pass the token to this URL.
     *
     * @param {string} url The URL to submit the token to
     * @param {string} sid The sid given in the response to requestToken
     * @param {string} clientSecret A secret binary string generated by the client.
     *                 This must be the same value submitted in the requestToken call.
     * @param {string} msisdnToken The MSISDN token, as enetered by the user.
     *
     * @return {Promise} Resolves: Object, currently with no parameters.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    submitMsisdnTokenOtherUrl(url, sid, clientSecret, msisdnToken) {
        const params = {
            sid: sid,
            client_secret: clientSecret,
            token: msisdnToken,
        };
        return this.http.requestOtherUrl(undefined, "POST", url, undefined, params);
    }
    /**
     * Gets the V2 hashing information from the identity server. Primarily useful for
     * lookups.
     * @param {string} identityAccessToken The access token for the identity server.
     * @returns {Promise<object>} The hashing information for the identity server.
     */
    getIdentityHashDetails(identityAccessToken) {
        return this.http.idServerRequest(undefined, "GET", "/hash_details", null, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
    }
    /**
     * Performs a hashed lookup of addresses against the identity server. This is
     * only supported on identity servers which have at least the version 2 API.
     * @param {Array<Array<string,string>>} addressPairs An array of 2 element arrays.
     * The first element of each pair is the address, the second is the 3PID medium.
     * Eg: ["email@example.org", "email"]
     * @param {string} identityAccessToken The access token for the identity server.
     * @returns {Promise<Array<{address, mxid}>>} A collection of address mappings to
     * found MXIDs. Results where no user could be found will not be listed.
     */
    identityHashedLookup(addressPairs, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = {
            // addresses: ["email@example.org", "10005550000"],
            // algorithm: "sha256",
            // pepper: "abc123"
            };
            // Get hash information first before trying to do a lookup
            const hashes = yield this.getIdentityHashDetails(identityAccessToken);
            if (!hashes || !hashes['lookup_pepper'] || !hashes['algorithms']) {
                throw new Error("Unsupported identity server: bad response");
            }
            params['pepper'] = hashes['lookup_pepper'];
            const localMapping = {
            // hashed identifier => plain text address
            // For use in this function's return format
            };
            // When picking an algorithm, we pick the hashed over no hashes
            if (hashes['algorithms'].includes('sha256')) {
                // Abuse the olm hashing
                const olmutil = new global.Olm.Utility();
                params["addresses"] = addressPairs.map(p => {
                    const addr = p[0].toLowerCase(); // lowercase to get consistent hashes
                    const med = p[1].toLowerCase();
                    const hashed = olmutil.sha256(`${addr} ${med} ${params['pepper']}`)
                        .replace(/\+/g, '-').replace(/\//g, '_'); // URL-safe base64
                    // Map the hash to a known (case-sensitive) address. We use the case
                    // sensitive version because the caller might be expecting that.
                    localMapping[hashed] = p[0];
                    return hashed;
                });
                params["algorithm"] = "sha256";
            }
            else if (hashes['algorithms'].includes('none')) {
                params["addresses"] = addressPairs.map(p => {
                    const addr = p[0].toLowerCase(); // lowercase to get consistent hashes
                    const med = p[1].toLowerCase();
                    const unhashed = `${addr} ${med}`;
                    // Map the unhashed values to a known (case-sensitive) address. We use
                    // the case sensitive version because the caller might be expecting that.
                    localMapping[unhashed] = p[0];
                    return unhashed;
                });
                params["algorithm"] = "none";
            }
            else {
                throw new Error("Unsupported identity server: unknown hash algorithm");
            }
            const response = yield this.http.idServerRequest(undefined, "POST", "/lookup", params, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
            if (!response || !response['mappings'])
                return []; // no results
            const foundAddresses = [ /* {address: "plain@example.org", mxid} */];
            for (const hashed of Object.keys(response['mappings'])) {
                const mxid = response['mappings'][hashed];
                const plainAddress = localMapping[hashed];
                if (!plainAddress) {
                    throw new Error("Identity server returned more results than expected");
                }
                foundAddresses.push({ address: plainAddress, mxid });
            }
            return foundAddresses;
        });
    }
    /**
     * Looks up the public Matrix ID mapping for a given 3rd party
     * identifier from the Identity Server
     *
     * @param {string} medium The medium of the threepid, eg. 'email'
     * @param {string} address The textual address of the threepid
     * @param {module:client.callback} callback Optional.
     * @param {string} identityAccessToken The `access_token` field of the Identity
     * Server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: A threepid mapping
     *                                 object or the empty object if no mapping
     *                                 exists
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    lookupThreePid(medium, address, callback, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            // Note: we're using the V2 API by calling this function, but our
            // function contract requires a V1 response. We therefore have to
            // convert it manually.
            const response = yield this.identityHashedLookup([[address, medium]], identityAccessToken);
            const result = response.find(p => p.address === address);
            if (!result) {
                if (callback)
                    callback(null, {});
                return {};
            }
            const mapping = {
                address,
                medium,
                mxid: result.mxid,
            };
            if (callback)
                callback(null, mapping);
            return mapping;
        });
    }
    /**
     * Looks up the public Matrix ID mappings for multiple 3PIDs.
     *
     * @param {Array.<Array.<string>>} query Array of arrays containing
     * [medium, address]
     * @param {string} identityAccessToken The `access_token` field of the Identity
     * Server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: Lookup results from IS.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    bulkLookupThreePids(query, identityAccessToken) {
        return __awaiter(this, void 0, void 0, function* () {
            // Note: we're using the V2 API by calling this function, but our
            // function contract requires a V1 response. We therefore have to
            // convert it manually.
            const response = yield this.identityHashedLookup(
            // We have to reverse the query order to get [address, medium] pairs
            query.map(p => [p[1], p[0]]), identityAccessToken);
            const v1results = [];
            for (const mapping of response) {
                const originalQuery = query.find(p => p[1] === mapping.address);
                if (!originalQuery) {
                    throw new Error("Identity sever returned unexpected results");
                }
                v1results.push([
                    originalQuery[0],
                    mapping.address,
                    mapping.mxid,
                ]);
            }
            return { threepids: v1results };
        });
    }
    /**
     * Get account info from the Identity Server. This is useful as a neutral check
     * to verify that other APIs are likely to approve access by testing that the
     * token is valid, terms have been agreed, etc.
     *
     * @param {string} identityAccessToken The `access_token` field of the Identity
     * Server `/account/register` response (see {@link registerWithIdentityServer}).
     *
     * @return {Promise} Resolves: an object with account info.
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getIdentityAccount(identityAccessToken) {
        return this.http.idServerRequest(undefined, "GET", "/account", undefined, http_api_1.PREFIX_IDENTITY_V2, identityAccessToken);
    }
    /**
     * Send an event to a specific list of devices
     *
     * @param {string} eventType  type of event to send
     * @param {Object.<string, Object<string, Object>>} contentMap
     *    content to send. Map from user_id to device_id to content object.
     * @param {string=} txnId     transaction id. One will be made up if not
     *    supplied.
     * @return {Promise} Resolves to the result object
     */
    sendToDevice(eventType, contentMap, txnId) {
        const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
            $eventType: eventType,
            $txnId: txnId ? txnId : this.makeTxnId(),
        });
        const body = {
            messages: contentMap,
        };
        const targets = Object.keys(contentMap).reduce((obj, key) => {
            obj[key] = Object.keys(contentMap[key]);
            return obj;
        }, {});
        logger_1.logger.log(`PUT ${path}`, targets);
        return this.http.authedRequest(undefined, "PUT", path, undefined, body);
    }
    /**
     * Get the third party protocols that can be reached using
     * this HS
     * @return {Promise} Resolves to the result object
     */
    getThirdpartyProtocols() {
        return this.http.authedRequest(undefined, "GET", "/thirdparty/protocols", undefined, undefined).then((response) => {
            // sanity check
            if (!response || typeof (response) !== 'object') {
                throw new Error(`/thirdparty/protocols did not return an object: ${response}`);
            }
            return response;
        });
    }
    /**
     * Get information on how a specific place on a third party protocol
     * may be reached.
     * @param {string} protocol The protocol given in getThirdpartyProtocols()
     * @param {object} params Protocol-specific parameters, as given in the
     *                        response to getThirdpartyProtocols()
     * @return {Promise} Resolves to the result object
     */
    getThirdpartyLocation(protocol, params) {
        const path = utils.encodeUri("/thirdparty/location/$protocol", {
            $protocol: protocol,
        });
        return this.http.authedRequest(undefined, "GET", path, params, undefined);
    }
    /**
     * Get information on how a specific user on a third party protocol
     * may be reached.
     * @param {string} protocol The protocol given in getThirdpartyProtocols()
     * @param {object} params Protocol-specific parameters, as given in the
     *                        response to getThirdpartyProtocols()
     * @return {Promise} Resolves to the result object
     */
    getThirdpartyUser(protocol, params) {
        const path = utils.encodeUri("/thirdparty/user/$protocol", {
            $protocol: protocol,
        });
        return this.http.authedRequest(undefined, "GET", path, params, undefined);
    }
    getTerms(serviceType, baseUrl) {
        const url = this.termsUrlForService(serviceType, baseUrl);
        return this.http.requestOtherUrl(undefined, 'GET', url);
    }
    agreeToTerms(serviceType, baseUrl, accessToken, termsUrls) {
        const url = this.termsUrlForService(serviceType, baseUrl);
        const headers = {
            Authorization: "Bearer " + accessToken,
        };
        return this.http.requestOtherUrl(undefined, 'POST', url, null, { user_accepts: termsUrls }, { headers });
    }
    /**
     * Reports an event as inappropriate to the server, which may then notify the appropriate people.
     * @param {string} roomId The room in which the event being reported is located.
     * @param {string} eventId The event to report.
     * @param {number} score The score to rate this content as where -100 is most offensive and 0 is inoffensive.
     * @param {string} reason The reason the content is being reported. May be blank.
     * @returns {Promise} Resolves to an empty object if successful
     */
    reportEvent(roomId, eventId, score, reason) {
        const path = utils.encodeUri("/rooms/$roomId/report/$eventId", {
            $roomId: roomId,
            $eventId: eventId,
        });
        return this.http.authedRequest(undefined, "POST", path, null, { score, reason });
    }
    /**
     * Fetches or paginates a summary of a space as defined by MSC2946
     * @param {string} roomId The ID of the space-room to use as the root of the summary.
     * @param {number?} maxRoomsPerSpace The maximum number of rooms to return per subspace.
     * @param {boolean?} suggestedOnly Whether to only return rooms with suggested=true.
     * @param {boolean?} autoJoinOnly Whether to only return rooms with auto_join=true.
     * @param {number?} limit The maximum number of rooms to return in total.
     * @param {string?} batch The opaque token to paginate a previous summary request.
     * @returns {Promise} the response, with next_batch, rooms, events fields.
     */
    getSpaceSummary(roomId, maxRoomsPerSpace, suggestedOnly, autoJoinOnly, limit, batch) {
        const path = utils.encodeUri("/rooms/$roomId/spaces", {
            $roomId: roomId,
        });
        return this.http.authedRequest(undefined, "POST", path, null, {
            max_rooms_per_space: maxRoomsPerSpace,
            suggested_only: suggestedOnly,
            auto_join_only: autoJoinOnly,
            limit,
            batch,
        }, {
            prefix: "/_matrix/client/unstable/org.matrix.msc2946",
        });
    }
    /**
     * Creates a new file tree space with the given name. The client will pick
     * defaults for how it expects to be able to support the remaining API offered
     * by the returned class.
     *
     * Note that this is UNSTABLE and may have breaking changes without notice.
     * @param {string} name The name of the tree space.
     * @returns {Promise<MSC3089TreeSpace>} Resolves to the created space.
     */
    unstableCreateFileTree(name) {
        return __awaiter(this, void 0, void 0, function* () {
            const { room_id: roomId } = yield this.createRoom({
                name: name,
                preset: partials_1.Preset.PrivateChat,
                power_level_content_override: Object.assign(Object.assign({}, MSC3089TreeSpace_1.DEFAULT_TREE_POWER_LEVELS_TEMPLATE), { users: {
                        [this.getUserId()]: 100,
                    } }),
                creation_content: {
                    [event_2.RoomCreateTypeField]: event_2.RoomType.Space,
                },
                initial_state: [
                    {
                        type: event_2.UNSTABLE_MSC3088_PURPOSE.name,
                        state_key: event_2.UNSTABLE_MSC3089_TREE_SUBTYPE.name,
                        content: {
                            [event_2.UNSTABLE_MSC3088_ENABLED.name]: true,
                        },
                    },
                    {
                        type: event_2.EventType.RoomEncryption,
                        state_key: "",
                        content: {
                            algorithm: olmlib.MEGOLM_ALGORITHM,
                        },
                    },
                ],
            });
            return new MSC3089TreeSpace_1.MSC3089TreeSpace(this, roomId);
        });
    }
    /**
     * Gets a reference to a tree space, if the room ID given is a tree space. If the room
     * does not appear to be a tree space then null is returned.
     *
     * Note that this is UNSTABLE and may have breaking changes without notice.
     * @param {string} roomId The room ID to get a tree space reference for.
     * @returns {MSC3089TreeSpace} The tree space, or null if not a tree space.
     */
    unstableGetFileTreeSpace(roomId) {
        var _a, _b;
        const room = this.getRoom(roomId);
        if (!room)
            return null;
        const createEvent = room.currentState.getStateEvents(event_2.EventType.RoomCreate, "");
        const purposeEvent = room.currentState.getStateEvents(event_2.UNSTABLE_MSC3088_PURPOSE.name, event_2.UNSTABLE_MSC3089_TREE_SUBTYPE.name);
        if (!createEvent)
            throw new Error("Expected single room create event");
        if (!((_a = purposeEvent === null || purposeEvent === void 0 ? void 0 : purposeEvent.getContent()) === null || _a === void 0 ? void 0 : _a[event_2.UNSTABLE_MSC3088_ENABLED.name]))
            return null;
        if (((_b = createEvent.getContent()) === null || _b === void 0 ? void 0 : _b[event_2.RoomCreateTypeField]) !== event_2.RoomType.Space)
            return null;
        return new MSC3089TreeSpace_1.MSC3089TreeSpace(this, roomId);
    }
    // TODO: Remove this warning, alongside the functions
    // See https://github.com/vector-im/element-web/issues/17532
    // ======================================================
    // **                ANCIENT APIS BELOW                **
    // ======================================================
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Group summary object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getGroupSummary(groupId) {
        const path = utils.encodeUri("/groups/$groupId/summary", { $groupId: groupId });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Group profile object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getGroupProfile(groupId) {
        const path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {string} groupId
     * @param {Object} profile The group profile object
     * @param {string=} profile.name Name of the group
     * @param {string=} profile.avatar_url MXC avatar URL
     * @param {string=} profile.short_description A short description of the room
     * @param {string=} profile.long_description A longer HTML description of the room
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setGroupProfile(groupId, profile) {
        const path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
        return this.http.authedRequest(undefined, "POST", path, undefined, profile);
    }
    /**
     * @param {string} groupId
     * @param {object} policy The join policy for the group. Must include at
     *     least a 'type' field which is 'open' if anyone can join the group
     *     the group without prior approval, or 'invite' if an invite is
     *     required to join.
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setGroupJoinPolicy(groupId, policy) {
        const path = utils.encodeUri("/groups/$groupId/settings/m.join_policy", { $groupId: groupId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {
            'm.join_policy': policy,
        });
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Group users list object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getGroupUsers(groupId) {
        const path = utils.encodeUri("/groups/$groupId/users", { $groupId: groupId });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Group users list object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getGroupInvitedUsers(groupId) {
        const path = utils.encodeUri("/groups/$groupId/invited_users", { $groupId: groupId });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Group rooms list object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getGroupRooms(groupId) {
        const path = utils.encodeUri("/groups/$groupId/rooms", { $groupId: groupId });
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {string} groupId
     * @param {string} userId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    inviteUserToGroup(groupId, userId) {
        const path = utils.encodeUri("/groups/$groupId/admin/users/invite/$userId", { $groupId: groupId, $userId: userId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} userId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    removeUserFromGroup(groupId, userId) {
        const path = utils.encodeUri("/groups/$groupId/admin/users/remove/$userId", { $groupId: groupId, $userId: userId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} userId
     * @param {string} roleId Optional.
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addUserToGroupSummary(groupId, userId, roleId) {
        const path = utils.encodeUri(roleId ?
            "/groups/$groupId/summary/$roleId/users/$userId" :
            "/groups/$groupId/summary/users/$userId", { $groupId: groupId, $roleId: roleId, $userId: userId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} userId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    removeUserFromGroupSummary(groupId, userId) {
        const path = utils.encodeUri("/groups/$groupId/summary/users/$userId", { $groupId: groupId, $userId: userId });
        return this.http.authedRequest(undefined, "DELETE", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} roomId
     * @param {string} categoryId Optional.
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addRoomToGroupSummary(groupId, roomId, categoryId) {
        const path = utils.encodeUri(categoryId ?
            "/groups/$groupId/summary/$categoryId/rooms/$roomId" :
            "/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $categoryId: categoryId, $roomId: roomId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} roomId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    removeRoomFromGroupSummary(groupId, roomId) {
        const path = utils.encodeUri("/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
        return this.http.authedRequest(undefined, "DELETE", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {string} roomId
     * @param {boolean} isPublic Whether the room-group association is visible to non-members
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    addRoomToGroup(groupId, roomId, isPublic) {
        if (isPublic === undefined) {
            isPublic = true;
        }
        const path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, { "m.visibility": { type: isPublic ? "public" : "private" } });
    }
    /**
     * Configure the visibility of a room-group association.
     * @param {string} groupId
     * @param {string} roomId
     * @param {boolean} isPublic Whether the room-group association is visible to non-members
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    updateGroupRoomVisibility(groupId, roomId, isPublic) {
        // NB: The /config API is generic but there's not much point in exposing this yet as synapse
        //     is the only server to implement this. In future we should consider an API that allows
        //     arbitrary configuration, i.e. "config/$configKey".
        const path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId/config/m.visibility", { $groupId: groupId, $roomId: roomId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, { type: isPublic ? "public" : "private" });
    }
    /**
     * @param {string} groupId
     * @param {string} roomId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    removeRoomFromGroup(groupId, roomId) {
        const path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
        return this.http.authedRequest(undefined, "DELETE", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @param {Object} opts Additional options to send alongside the acceptance.
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    acceptGroupInvite(groupId, opts = null) {
        const path = utils.encodeUri("/groups/$groupId/self/accept_invite", { $groupId: groupId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, opts || {});
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    joinGroup(groupId) {
        const path = utils.encodeUri("/groups/$groupId/self/join", { $groupId: groupId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @param {string} groupId
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    leaveGroup(groupId) {
        const path = utils.encodeUri("/groups/$groupId/self/leave", { $groupId: groupId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {});
    }
    /**
     * @return {Promise} Resolves: The groups to which the user is joined
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getJoinedGroups() {
        const path = utils.encodeUri("/joined_groups", {});
        return this.http.authedRequest(undefined, "GET", path);
    }
    /**
     * @param {Object} content Request content
     * @param {string} content.localpart The local part of the desired group ID
     * @param {Object} content.profile Group profile object
     * @return {Promise} Resolves: Object with key group_id: id of the created group
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    createGroup(content) {
        const path = utils.encodeUri("/create_group", {});
        return this.http.authedRequest(undefined, "POST", path, undefined, content);
    }
    /**
     * @param {string[]} userIds List of user IDs
     * @return {Promise} Resolves: Object as exmaple below
     *
     *     {
     *         "users": {
     *             "@bob:example.com": {
     *                 "+example:example.com"
     *             }
     *         }
     *     }
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    getPublicisedGroups(userIds) {
        const path = utils.encodeUri("/publicised_groups", {});
        return this.http.authedRequest(undefined, "POST", path, undefined, { user_ids: userIds });
    }
    /**
     * @param {string} groupId
     * @param {boolean} isPublic Whether the user's membership of this group is made public
     * @return {Promise} Resolves: Empty object
     * @return {module:http-api.MatrixError} Rejects: with an error response.
     */
    setGroupPublicity(groupId, isPublic) {
        const path = utils.encodeUri("/groups/$groupId/self/update_publicity", { $groupId: groupId });
        return this.http.authedRequest(undefined, "PUT", path, undefined, {
            publicise: isPublic,
        });
    }
}
exports.MatrixClient = MatrixClient;
MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY = 'RESTORE_BACKUP_ERROR_BAD_KEY';
/**
 * Fires whenever the SDK receives a new event.
 * <p>
 * This is only fired for live events received via /sync - it is not fired for
 * events received over context, search, or pagination APIs.
 *
 * @event module:client~MatrixClient#"event"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @example
 * matrixClient.on("event", function(event){
 *   var sender = event.getSender();
 * });
 */
/**
 * Fires whenever the SDK receives a new to-device event.
 * @event module:client~MatrixClient#"toDeviceEvent"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @example
 * matrixClient.on("toDeviceEvent", function(event){
 *   var sender = event.getSender();
 * });
 */
/**
 * Fires whenever the SDK's syncing state is updated. The state can be one of:
 * <ul>
 *
 * <li>PREPARED: The client has synced with the server at least once and is
 * ready for methods to be called on it. This will be immediately followed by
 * a state of SYNCING. <i>This is the equivalent of "syncComplete" in the
 * previous API.</i></li>
 *
 * <li>CATCHUP: The client has detected the connection to the server might be
 * available again and will now try to do a sync again. As this sync might take
 * a long time (depending how long ago was last synced, and general server
 * performance) the client is put in this mode so the UI can reflect trying
 * to catch up with the server after losing connection.</li>
 *
 * <li>SYNCING : The client is currently polling for new events from the server.
 * This will be called <i>after</i> processing latest events from a sync.</li>
 *
 * <li>ERROR : The client has had a problem syncing with the server. If this is
 * called <i>before</i> PREPARED then there was a problem performing the initial
 * sync. If this is called <i>after</i> PREPARED then there was a problem polling
 * the server for updates. This may be called multiple times even if the state is
 * already ERROR. <i>This is the equivalent of "syncError" in the previous
 * API.</i></li>
 *
 * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that
 * should be considered erroneous.
 * </li>
 *
 * <li>STOPPED: The client has stopped syncing with server due to stopClient
 * being called.
 * </li>
 * </ul>
 * State transition diagram:
 * <pre>
 *                                          +---->STOPPED
 *                                          |
 *              +----->PREPARED -------> SYNCING <--+
 *              |                        ^  |  ^    |
 *              |      CATCHUP ----------+  |  |    |
 *              |        ^                  V  |    |
 *   null ------+        |  +------- RECONNECTING   |
 *              |        V  V                       |
 *              +------->ERROR ---------------------+
 *
 * NB: 'null' will never be emitted by this event.
 *
 * </pre>
 * Transitions:
 * <ul>
 *
 * <li><code>null -> PREPARED</code> : Occurs when the initial sync is completed
 * first time. This involves setting up filters and obtaining push rules.
 *
 * <li><code>null -> ERROR</code> : Occurs when the initial sync failed first time.
 *
 * <li><code>ERROR -> PREPARED</code> : Occurs when the initial sync succeeds
 * after previously failing.
 *
 * <li><code>PREPARED -> SYNCING</code> : Occurs immediately after transitioning
 * to PREPARED. Starts listening for live updates rather than catching up.
 *
 * <li><code>SYNCING -> RECONNECTING</code> : Occurs when the live update fails.
 *
 * <li><code>RECONNECTING -> RECONNECTING</code> : Can occur if the update calls
 * continue to fail, but the keepalive calls (to /versions) succeed.
 *
 * <li><code>RECONNECTING -> ERROR</code> : Occurs when the keepalive call also fails
 *
 * <li><code>ERROR -> SYNCING</code> : Occurs when the client has performed a
 * live update after having previously failed.
 *
 * <li><code>ERROR -> ERROR</code> : Occurs when the client has failed to keepalive
 * for a second time or more.</li>
 *
 * <li><code>SYNCING -> SYNCING</code> : Occurs when the client has performed a live
 * update. This is called <i>after</i> processing.</li>
 *
 * <li><code>* -> STOPPED</code> : Occurs once the client has stopped syncing or
 * trying to sync after stopClient has been called.</li>
 * </ul>
 *
 * @event module:client~MatrixClient#"sync"
 *
 * @param {string} state An enum representing the syncing state. One of "PREPARED",
 * "SYNCING", "ERROR", "STOPPED".
 *
 * @param {?string} prevState An enum representing the previous syncing state.
 * One of "PREPARED", "SYNCING", "ERROR", "STOPPED" <b>or null</b>.
 *
 * @param {?Object} data Data about this transition.
 *
 * @param {MatrixError} data.error The matrix error if <code>state=ERROR</code>.
 *
 * @param {String} data.oldSyncToken The 'since' token passed to /sync.
 *    <code>null</code> for the first successful sync since this client was
 *    started. Only present if <code>state=PREPARED</code> or
 *    <code>state=SYNCING</code>.
 *
 * @param {String} data.nextSyncToken The 'next_batch' result from /sync, which
 *    will become the 'since' token for the next call to /sync. Only present if
 *    <code>state=PREPARED</code> or <code>state=SYNCING</code>.
 *
 * @param {boolean} data.catchingUp True if we are working our way through a
 *    backlog of events after connecting. Only present if <code>state=SYNCING</code>.
 *
 * @example
 * matrixClient.on("sync", function(state, prevState, data) {
 *   switch (state) {
 *     case "ERROR":
 *       // update UI to say "Connection Lost"
 *       break;
 *     case "SYNCING":
 *       // update UI to remove any "Connection Lost" message
 *       break;
 *     case "PREPARED":
 *       // the client instance is ready to be queried.
 *       var rooms = matrixClient.getRooms();
 *       break;
 *   }
 * });
 */
/**
 * Fires whenever the sdk learns about a new group. <strong>This event
 * is experimental and may change.</strong>
 * @event module:client~MatrixClient#"Group"
 * @param {Group} group The newly created, fully populated group.
 * @example
 * matrixClient.on("Group", function(group){
 *   var groupId = group.groupId;
 * });
 */
/**
 * Fires whenever a new Room is added. This will fire when you are invited to a
 * room, as well as when you join a room. <strong>This event is experimental and
 * may change.</strong>
 * @event module:client~MatrixClient#"Room"
 * @param {Room} room The newly created, fully populated room.
 * @example
 * matrixClient.on("Room", function(room){
 *   var roomId = room.roomId;
 * });
 */
/**
 * Fires whenever a Room is removed. This will fire when you forget a room.
 * <strong>This event is experimental and may change.</strong>
 * @event module:client~MatrixClient#"deleteRoom"
 * @param {string} roomId The deleted room ID.
 * @example
 * matrixClient.on("deleteRoom", function(roomId){
 *   // update UI from getRooms()
 * });
 */
/**
 * Fires whenever an incoming call arrives.
 * @event module:client~MatrixClient#"Call.incoming"
 * @param {module:webrtc/call~MatrixCall} call The incoming call.
 * @example
 * matrixClient.on("Call.incoming", function(call){
 *   call.answer(); // auto-answer
 * });
 */
/**
 * Fires whenever the login session the JS SDK is using is no
 * longer valid and the user must log in again.
 * NB. This only fires when action is required from the user, not
 * when then login session can be renewed by using a refresh token.
 * @event module:client~MatrixClient#"Session.logged_out"
 * @example
 * matrixClient.on("Session.logged_out", function(errorObj){
 *   // show the login screen
 * });
 */
/**
 * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response
 * to a HTTP request.
 * @event module:client~MatrixClient#"no_consent"
 * @example
 * matrixClient.on("no_consent", function(message, contentUri) {
 *     console.info(message + ' Go to ' + contentUri);
 * });
 */
/**
 * Fires when a device is marked as verified/unverified/blocked/unblocked by
 * {@link module:client~MatrixClient#setDeviceVerified|MatrixClient.setDeviceVerified} or
 * {@link module:client~MatrixClient#setDeviceBlocked|MatrixClient.setDeviceBlocked}.
 *
 * @event module:client~MatrixClient#"deviceVerificationChanged"
 * @param {string} userId the owner of the verified device
 * @param {string} deviceId the id of the verified device
 * @param {module:crypto/deviceinfo} deviceInfo updated device information
 */
/**
 * Fires when the trust status of a user changes
 * If userId is the userId of the logged in user, this indicated a change
 * in the trust status of the cross-signing data on the account.
 *
 * The cross-signing API is currently UNSTABLE and may change without notice.
 *
 * @event module:client~MatrixClient#"userTrustStatusChanged"
 * @param {string} userId the userId of the user in question
 * @param {UserTrustLevel} trustLevel The new trust level of the user
 */
/**
 * Fires when the user's cross-signing keys have changed or cross-signing
 * has been enabled/disabled. The client can use getStoredCrossSigningForUser
 * with the user ID of the logged in user to check if cross-signing is
 * enabled on the account. If enabled, it can test whether the current key
 * is trusted using with checkUserTrust with the user ID of the logged
 * in user. The checkOwnCrossSigningTrust function may be used to reconcile
 * the trust in the account key.
 *
 * The cross-signing API is currently UNSTABLE and may change without notice.
 *
 * @event module:client~MatrixClient#"crossSigning.keysChanged"
 */
/**
 * Fires whenever new user-scoped account_data is added.
 * @event module:client~MatrixClient#"accountData"
 * @param {MatrixEvent} event The event describing the account_data just added
 * @param {MatrixEvent} event The previous account data, if known.
 * @example
 * matrixClient.on("accountData", function(event, oldEvent){
 *   myAccountData[event.type] = event.content;
 * });
 */
/**
 * Fires whenever the stored devices for a user have changed
 * @event module:client~MatrixClient#"crypto.devicesUpdated"
 * @param {String[]} users A list of user IDs that were updated
 * @param {boolean} initialFetch If true, the store was empty (apart
 *     from our own device) and has been seeded.
 */
/**
 * Fires whenever the stored devices for a user will be updated
 * @event module:client~MatrixClient#"crypto.willUpdateDevices"
 * @param {String[]} users A list of user IDs that will be updated
 * @param {boolean} initialFetch If true, the store is empty (apart
 *     from our own device) and is being seeded.
 */
/**
 * Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled()
 * @event module:client~MatrixClient#"crypto.keyBackupStatus"
 * @param {boolean} enabled true if key backup has been enabled, otherwise false
 * @example
 * matrixClient.on("crypto.keyBackupStatus", function(enabled){
 *   if (enabled) {
 *     [...]
 *   }
 * });
 */
/**
 * Fires when we want to suggest to the user that they restore their megolm keys
 * from backup or by cross-signing the device.
 *
 * @event module:client~MatrixClient#"crypto.suggestKeyRestore"
 */
/**
 * Fires when a key verification is requested.
 * @event module:client~MatrixClient#"crypto.verification.request"
 * @param {object} data
 * @param {MatrixEvent} data.event the original verification request message
 * @param {Array} data.methods the verification methods that can be used
 * @param {Number} data.timeout the amount of milliseconds that should be waited
 *                 before cancelling the request automatically.
 * @param {Function} data.beginKeyVerification a function to call if a key
 *     verification should be performed.  The function takes one argument: the
 *     name of the key verification method (taken from data.methods) to use.
 * @param {Function} data.cancel a function to call if the key verification is
 *     rejected.
 */
/**
 * Fires when a key verification is requested with an unknown method.
 * @event module:client~MatrixClient#"crypto.verification.request.unknown"
 * @param {string} userId the user ID who requested the key verification
 * @param {Function} cancel a function that will send a cancellation message to
 *     reject the key verification.
 */
/**
 * Fires when a secret request has been cancelled.  If the client is prompting
 * the user to ask whether they want to share a secret, the prompt can be
 * dismissed.
 *
 * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
 *
 * @event module:client~MatrixClient#"crypto.secrets.requestCancelled"
 * @param {object} data
 * @param {string} data.user_id The user ID of the client that had requested the secret.
 * @param {string} data.device_id The device ID of the client that had requested the
 *     secret.
 * @param {string} data.request_id The ID of the original request.
 */
/**
 * Fires when the client .well-known info is fetched.
 *
 * @event module:client~MatrixClient#"WellKnown.client"
 * @param {object} data The JSON object returned by the server
 */

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./@types/event":58,"./@types/partials":59,"./ReEmitter":61,"./autodiscovery":62,"./content-helpers":65,"./content-repo":66,"./crypto":83,"./crypto/RoomList":72,"./crypto/api":79,"./crypto/backup":80,"./crypto/dehydration":81,"./crypto/key_passphrase":84,"./crypto/olmlib":85,"./crypto/recoverykey":86,"./event-mapper":100,"./filter":102,"./http-api":103,"./logger":106,"./matrix":107,"./models/MSC3089TreeSpace":109,"./models/event":113,"./models/event-timeline":112,"./models/search-result":120,"./models/user":121,"./pushprocessor":122,"./randomstring":123,"./service-types":126,"./store/stub":132,"./sync":135,"./sync.api":134,"./utils":137,"./webrtc/call":138,"./webrtc/callEventHandler":139,"events":36,"url":56}],65:[function(require,module,exports){
"use strict";
/*
Copyright 2018 New Vector Ltd
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeEmoteMessage = exports.makeNotice = exports.makeTextMessage = exports.makeHtmlEmote = exports.makeHtmlNotice = exports.makeHtmlMessage = void 0;
/** @module ContentHelpers */
/**
 * Generates the content for a HTML Message event
 * @param {string} body the plaintext body of the message
 * @param {string} htmlBody the HTML representation of the message
 * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}
 */
function makeHtmlMessage(body, htmlBody) {
    return {
        msgtype: "m.text",
        format: "org.matrix.custom.html",
        body: body,
        formatted_body: htmlBody,
    };
}
exports.makeHtmlMessage = makeHtmlMessage;
/**
 * Generates the content for a HTML Notice event
 * @param {string} body the plaintext body of the notice
 * @param {string} htmlBody the HTML representation of the notice
 * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}
 */
function makeHtmlNotice(body, htmlBody) {
    return {
        msgtype: "m.notice",
        format: "org.matrix.custom.html",
        body: body,
        formatted_body: htmlBody,
    };
}
exports.makeHtmlNotice = makeHtmlNotice;
/**
 * Generates the content for a HTML Emote event
 * @param {string} body the plaintext body of the emote
 * @param {string} htmlBody the HTML representation of the emote
 * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}
 */
function makeHtmlEmote(body, htmlBody) {
    return {
        msgtype: "m.emote",
        format: "org.matrix.custom.html",
        body: body,
        formatted_body: htmlBody,
    };
}
exports.makeHtmlEmote = makeHtmlEmote;
/**
 * Generates the content for a Plaintext Message event
 * @param {string} body the plaintext body of the emote
 * @returns {{msgtype: string, body: string}}
 */
function makeTextMessage(body) {
    return {
        msgtype: "m.text",
        body: body,
    };
}
exports.makeTextMessage = makeTextMessage;
/**
 * Generates the content for a Plaintext Notice event
 * @param {string} body the plaintext body of the notice
 * @returns {{msgtype: string, body: string}}
 */
function makeNotice(body) {
    return {
        msgtype: "m.notice",
        body: body,
    };
}
exports.makeNotice = makeNotice;
/**
 * Generates the content for a Plaintext Emote event
 * @param {string} body the plaintext body of the emote
 * @returns {{msgtype: string, body: string}}
 */
function makeEmoteMessage(body) {
    return {
        msgtype: "m.emote",
        body: body,
    };
}
exports.makeEmoteMessage = makeEmoteMessage;

},{}],66:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
 * @module content-repo
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHttpUriForMxc = void 0;
const utils = __importStar(require("./utils"));
/**
 * Get the HTTP URL for an MXC URI.
 * @param {string} baseUrl The base homeserver url which has a content repo.
 * @param {string} mxc The mxc:// URI.
 * @param {Number} width The desired width of the thumbnail.
 * @param {Number} height The desired height of the thumbnail.
 * @param {string} resizeMethod The thumbnail resize method to use, either
 * "crop" or "scale".
 * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs
 * directly. Fetching such URLs will leak information about the user to
 * anyone they share a room with. If false, will return the emptry string
 * for such URLs.
 * @return {string} The complete URL to the content.
 */
function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks = false) {
    if (typeof mxc !== "string" || !mxc) {
        return '';
    }
    if (mxc.indexOf("mxc://") !== 0) {
        if (allowDirectLinks) {
            return mxc;
        }
        else {
            return '';
        }
    }
    let serverAndMediaId = mxc.slice(6); // strips mxc://
    let prefix = "/_matrix/media/r0/download/";
    const params = {};
    if (width) {
        params["width"] = Math.round(width);
    }
    if (height) {
        params["height"] = Math.round(height);
    }
    if (resizeMethod) {
        params["method"] = resizeMethod;
    }
    if (Object.keys(params).length > 0) {
        // these are thumbnailing params so they probably want the
        // thumbnailing API...
        prefix = "/_matrix/media/r0/thumbnail/";
    }
    const fragmentOffset = serverAndMediaId.indexOf("#");
    let fragment = "";
    if (fragmentOffset >= 0) {
        fragment = serverAndMediaId.substr(fragmentOffset);
        serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset);
    }
    const urlParams = (Object.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params)));
    return baseUrl + prefix + serverAndMediaId + urlParams + fragment;
}
exports.getHttpUriForMxc = getHttpUriForMxc;

},{"./utils":137}],67:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";
/*
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestKeysDuringVerification = exports.createCryptoStoreCacheCallbacks = exports.DeviceTrustLevel = exports.UserTrustLevel = exports.CrossSigningLevel = exports.CrossSigningInfo = void 0;
/**
 * Cross signing methods
 * @module crypto/CrossSigning
 */
const events_1 = require("events");
const olmlib_1 = require("./olmlib");
const logger_1 = require("../logger");
const indexeddb_crypto_store_1 = require("../crypto/store/indexeddb-crypto-store");
const aes_1 = require("./aes");
const KEY_REQUEST_TIMEOUT_MS = 1000 * 60;
function publicKeyFromKeyInfo(keyInfo) {
    // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
    // We assume only a single key, and we want the bare form without type
    // prefix, so we select the values.
    return Object.values(keyInfo.keys)[0];
}
class CrossSigningInfo extends events_1.EventEmitter {
    /**
     * Information about a user's cross-signing keys
     *
     * @class
     *
     * @param {string} userId the user that the information is about
     * @param {object} callbacks Callbacks used to interact with the app
     *     Requires getCrossSigningKey and saveCrossSigningKeys
     * @param {object} cacheCallbacks Callbacks used to interact with the cache
     */
    constructor(userId, callbacks = {}, cacheCallbacks = {}) {
        super();
        this.userId = userId;
        this.callbacks = callbacks;
        this.cacheCallbacks = cacheCallbacks;
        this.keys = {};
        this.firstUse = true;
        // This tracks whether we've ever verified this user with any identity.
        // When you verify a user, any devices online at the time that receive
        // the verifying signature via the homeserver will latch this to true
        // and can use it in the future to detect cases where the user has
        // become unverified later for any reason.
        this.crossSigningVerifiedBefore = false;
    }
    static fromStorage(obj, userId) {
        const res = new CrossSigningInfo(userId);
        for (const prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                res[prop] = obj[prop];
            }
        }
        return res;
    }
    toStorage() {
        return {
            keys: this.keys,
            firstUse: this.firstUse,
            crossSigningVerifiedBefore: this.crossSigningVerifiedBefore,
        };
    }
    /**
     * Calls the app callback to ask for a private key
     *
     * @param {string} type The key type ("master", "self_signing", or "user_signing")
     * @param {string} expectedPubkey The matching public key or undefined to use
     *     the stored public key for the given key type.
     * @returns {Array} An array with [ public key, Olm.PkSigning ]
     */
    getCrossSigningKey(type, expectedPubkey) {
        return __awaiter(this, void 0, void 0, function* () {
            const shouldCache = ["master", "self_signing", "user_signing"].indexOf(type) >= 0;
            if (!this.callbacks.getCrossSigningKey) {
                throw new Error("No getCrossSigningKey callback supplied");
            }
            if (expectedPubkey === undefined) {
                expectedPubkey = this.getId(type);
            }
            function validateKey(key) {
                if (!key)
                    return;
                const signing = new global.Olm.PkSigning();
                const gotPubkey = signing.init_with_seed(key);
                if (gotPubkey === expectedPubkey) {
                    return [gotPubkey, signing];
                }
                signing.free();
            }
            let privkey;
            if (this.cacheCallbacks.getCrossSigningKeyCache && shouldCache) {
                privkey = yield this.cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey);
            }
            const cacheresult = validateKey(privkey);
            if (cacheresult) {
                return cacheresult;
            }
            privkey = yield this.callbacks.getCrossSigningKey(type, expectedPubkey);
            const result = validateKey(privkey);
            if (result) {
                if (this.cacheCallbacks.storeCrossSigningKeyCache && shouldCache) {
                    yield this.cacheCallbacks.storeCrossSigningKeyCache(type, privkey);
                }
                return result;
            }
            /* No keysource even returned a key */
            if (!privkey) {
                throw new Error("getCrossSigningKey callback for " + type + " returned falsey");
            }
            /* We got some keys from the keysource, but none of them were valid */
            throw new Error("Key type " + type + " from getCrossSigningKey callback did not match");
        });
    }
    /**
     * Check whether the private keys exist in secret storage.
     * XXX: This could be static, be we often seem to have an instance when we
     * want to know this anyway...
     *
     * @param {SecretStorage} secretStorage The secret store using account data
     * @returns {object} map of key name to key info the secret is encrypted
     *     with, or null if it is not present or not encrypted with a trusted
     *     key
     */
    isStoredInSecretStorage(secretStorage) {
        return __awaiter(this, void 0, void 0, function* () {
            // check what SSSS keys have encrypted the master key (if any)
            const stored = (yield secretStorage.isStored("m.cross_signing.master", false)) || {};
            // then check which of those SSSS keys have also encrypted the SSK and USK
            function intersect(s) {
                for (const k of Object.keys(stored)) {
                    if (!s[k]) {
                        delete stored[k];
                    }
                }
            }
            for (const type of ["self_signing", "user_signing"]) {
                intersect((yield secretStorage.isStored(`m.cross_signing.${type}`, false)) || {});
            }
            return Object.keys(stored).length ? stored : null;
        });
    }
    /**
     * Store private keys in secret storage for use by other devices. This is
     * typically called in conjunction with the creation of new cross-signing
     * keys.
     *
     * @param {Map} keys The keys to store
     * @param {SecretStorage} secretStorage The secret store using account data
     */
    static storeInSecretStorage(keys, secretStorage) {
        return __awaiter(this, void 0, void 0, function* () {
            for (const [type, privateKey] of keys) {
                const encodedKey = olmlib_1.encodeBase64(privateKey);
                yield secretStorage.store(`m.cross_signing.${type}`, encodedKey);
            }
        });
    }
    /**
     * Get private keys from secret storage created by some other device. This
     * also passes the private keys to the app-specific callback.
     *
     * @param {string} type The type of key to get.  One of "master",
     * "self_signing", or "user_signing".
     * @param {SecretStorage} secretStorage The secret store using account data
     * @return {Uint8Array} The private key
     */
    static getFromSecretStorage(type, secretStorage) {
        return __awaiter(this, void 0, void 0, function* () {
            const encodedKey = yield secretStorage.get(`m.cross_signing.${type}`);
            if (!encodedKey) {
                return null;
            }
            return olmlib_1.decodeBase64(encodedKey);
        });
    }
    /**
     * Check whether the private keys exist in the local key cache.
     *
     * @param {string} [type] The type of key to get. One of "master",
     * "self_signing", or "user_signing". Optional, will check all by default.
     * @returns {boolean} True if all keys are stored in the local cache.
     */
    isStoredInKeyCache(type) {
        return __awaiter(this, void 0, void 0, function* () {
            const cacheCallbacks = this.cacheCallbacks;
            if (!cacheCallbacks)
                return false;
            const types = type ? [type] : ["master", "self_signing", "user_signing"];
            for (const t of types) {
                if (!(yield cacheCallbacks.getCrossSigningKeyCache(t))) {
                    return false;
                }
            }
            return true;
        });
    }
    /**
     * Get cross-signing private keys from the local cache.
     *
     * @returns {Map} A map from key type (string) to private key (Uint8Array)
     */
    getCrossSigningKeysFromCache() {
        return __awaiter(this, void 0, void 0, function* () {
            const keys = new Map();
            const cacheCallbacks = this.cacheCallbacks;
            if (!cacheCallbacks)
                return keys;
            for (const type of ["master", "self_signing", "user_signing"]) {
                const privKey = yield cacheCallbacks.getCrossSigningKeyCache(type);
                if (!privKey) {
                    continue;
                }
                keys.set(type, privKey);
            }
            return keys;
        });
    }
    /**
     * Get the ID used to identify the user. This can also be used to test for
     * the existence of a given key type.
     *
     * @param {string} type The type of key to get the ID of.  One of "master",
     * "self_signing", or "user_signing".  Defaults to "master".
     *
     * @return {string} the ID
     */
    getId(type = "master") {
        if (!this.keys[type])
            return null;
        const keyInfo = this.keys[type];
        return publicKeyFromKeyInfo(keyInfo);
    }
    /**
     * Create new cross-signing keys for the given key types. The public keys
     * will be held in this class, while the private keys are passed off to the
     * `saveCrossSigningKeys` application callback.
     *
     * @param {CrossSigningLevel} level The key types to reset
     */
    resetKeys(level) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.callbacks.saveCrossSigningKeys) {
                throw new Error("No saveCrossSigningKeys callback supplied");
            }
            // If we're resetting the master key, we reset all keys
            if (level === undefined ||
                level & CrossSigningLevel.MASTER ||
                !this.keys.master) {
                level = (CrossSigningLevel.MASTER |
                    CrossSigningLevel.USER_SIGNING |
                    CrossSigningLevel.SELF_SIGNING);
            }
            else if (level === 0) {
                return;
            }
            const privateKeys = {};
            const keys = {}; // TODO types
            let masterSigning;
            let masterPub;
            try {
                if (level & CrossSigningLevel.MASTER) {
                    masterSigning = new global.Olm.PkSigning();
                    privateKeys.master = masterSigning.generate_seed();
                    masterPub = masterSigning.init_with_seed(privateKeys.master);
                    keys.master = {
                        user_id: this.userId,
                        usage: ['master'],
                        keys: {
                            ['ed25519:' + masterPub]: masterPub,
                        },
                    };
                }
                else {
                    [masterPub, masterSigning] = yield this.getCrossSigningKey("master");
                }
                if (level & CrossSigningLevel.SELF_SIGNING) {
                    const sskSigning = new global.Olm.PkSigning();
                    try {
                        privateKeys.self_signing = sskSigning.generate_seed();
                        const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);
                        keys.self_signing = {
                            user_id: this.userId,
                            usage: ['self_signing'],
                            keys: {
                                ['ed25519:' + sskPub]: sskPub,
                            },
                        };
                        olmlib_1.pkSign(keys.self_signing, masterSigning, this.userId, masterPub);
                    }
                    finally {
                        sskSigning.free();
                    }
                }
                if (level & CrossSigningLevel.USER_SIGNING) {
                    const uskSigning = new global.Olm.PkSigning();
                    try {
                        privateKeys.user_signing = uskSigning.generate_seed();
                        const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);
                        keys.user_signing = {
                            user_id: this.userId,
                            usage: ['user_signing'],
                            keys: {
                                ['ed25519:' + uskPub]: uskPub,
                            },
                        };
                        olmlib_1.pkSign(keys.user_signing, masterSigning, this.userId, masterPub);
                    }
                    finally {
                        uskSigning.free();
                    }
                }
                Object.assign(this.keys, keys);
                this.callbacks.saveCrossSigningKeys(privateKeys);
            }
            finally {
                if (masterSigning) {
                    masterSigning.free();
                }
            }
        });
    }
    /**
     * unsets the keys, used when another session has reset the keys, to disable cross-signing
     */
    clearKeys() {
        this.keys = {};
    }
    setKeys(keys) {
        const signingKeys = {};
        if (keys.master) {
            if (keys.master.user_id !== this.userId) {
                const error = "Mismatched user ID " + keys.master.user_id +
                    " in master key from " + this.userId;
                logger_1.logger.error(error);
                throw new Error(error);
            }
            if (!this.keys.master) {
                // this is the first key we've seen, so first-use is true
                this.firstUse = true;
            }
            else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) {
                // this is a different key, so first-use is false
                this.firstUse = false;
            } // otherwise, same key, so no change
            signingKeys.master = keys.master;
        }
        else if (this.keys.master) {
            signingKeys.master = this.keys.master;
        }
        else {
            throw new Error("Tried to set cross-signing keys without a master key");
        }
        const masterKey = publicKeyFromKeyInfo(signingKeys.master);
        // verify signatures
        if (keys.user_signing) {
            if (keys.user_signing.user_id !== this.userId) {
                const error = "Mismatched user ID " + keys.master.user_id +
                    " in user_signing key from " + this.userId;
                logger_1.logger.error(error);
                throw new Error(error);
            }
            try {
                olmlib_1.pkVerify(keys.user_signing, masterKey, this.userId);
            }
            catch (e) {
                logger_1.logger.error("invalid signature on user-signing key");
                // FIXME: what do we want to do here?
                throw e;
            }
        }
        if (keys.self_signing) {
            if (keys.self_signing.user_id !== this.userId) {
                const error = "Mismatched user ID " + keys.master.user_id +
                    " in self_signing key from " + this.userId;
                logger_1.logger.error(error);
                throw new Error(error);
            }
            try {
                olmlib_1.pkVerify(keys.self_signing, masterKey, this.userId);
            }
            catch (e) {
                logger_1.logger.error("invalid signature on self-signing key");
                // FIXME: what do we want to do here?
                throw e;
            }
        }
        // if everything checks out, then save the keys
        if (keys.master) {
            this.keys.master = keys.master;
            // if the master key is set, then the old self-signing and
            // user-signing keys are obsolete
            this.keys.self_signing = null;
            this.keys.user_signing = null;
        }
        if (keys.self_signing) {
            this.keys.self_signing = keys.self_signing;
        }
        if (keys.user_signing) {
            this.keys.user_signing = keys.user_signing;
        }
    }
    updateCrossSigningVerifiedBefore(isCrossSigningVerified) {
        // It is critical that this value latches forward from false to true but
        // never back to false to avoid a downgrade attack.
        if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) {
            this.crossSigningVerifiedBefore = true;
        }
    }
    signObject(data, type) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.keys[type]) {
                throw new Error("Attempted to sign with " + type + " key but no such key present");
            }
            const [pubkey, signing] = yield this.getCrossSigningKey(type);
            try {
                olmlib_1.pkSign(data, signing, this.userId, pubkey);
                return data;
            }
            finally {
                signing.free();
            }
        });
    }
    signUser(key) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.keys.user_signing) {
                logger_1.logger.info("No user signing key: not signing user");
                return;
            }
            return this.signObject(key.keys.master, "user_signing");
        });
    }
    signDevice(userId, device) {
        return __awaiter(this, void 0, void 0, function* () {
            if (userId !== this.userId) {
                throw new Error(`Trying to sign ${userId}'s device; can only sign our own device`);
            }
            if (!this.keys.self_signing) {
                logger_1.logger.info("No self signing key: not signing device");
                return;
            }
            return this.signObject({
                algorithms: device.algorithms,
                keys: device.keys,
                device_id: device.deviceId,
                user_id: userId,
            }, "self_signing");
        });
    }
    /**
     * Check whether a given user is trusted.
     *
     * @param {CrossSigningInfo} userCrossSigning Cross signing info for user
     *
     * @returns {UserTrustLevel}
     */
    checkUserTrust(userCrossSigning) {
        // if we're checking our own key, then it's trusted if the master key
        // and self-signing key match
        if (this.userId === userCrossSigning.userId
            && this.getId() && this.getId() === userCrossSigning.getId()
            && this.getId("self_signing")
            && this.getId("self_signing") === userCrossSigning.getId("self_signing")) {
            return new UserTrustLevel(true, true, this.firstUse);
        }
        if (!this.keys.user_signing) {
            // If there's no user signing key, they can't possibly be verified.
            // They may be TOFU trusted though.
            return new UserTrustLevel(false, false, userCrossSigning.firstUse);
        }
        let userTrusted;
        const userMaster = userCrossSigning.keys.master;
        const uskId = this.getId('user_signing');
        try {
            olmlib_1.pkVerify(userMaster, uskId, this.userId);
            userTrusted = true;
        }
        catch (e) {
            userTrusted = false;
        }
        return new UserTrustLevel(userTrusted, userCrossSigning.crossSigningVerifiedBefore, userCrossSigning.firstUse);
    }
    /**
     * Check whether a given device is trusted.
     *
     * @param {CrossSigningInfo} userCrossSigning Cross signing info for user
     * @param {module:crypto/deviceinfo} device The device to check
     * @param {boolean} localTrust Whether the device is trusted locally
     * @param {boolean} trustCrossSignedDevices Whether we trust cross signed devices
     *
     * @returns {DeviceTrustLevel}
     */
    checkDeviceTrust(userCrossSigning, device, localTrust, trustCrossSignedDevices) {
        const userTrust = this.checkUserTrust(userCrossSigning);
        const userSSK = userCrossSigning.keys.self_signing;
        if (!userSSK) {
            // if the user has no self-signing key then we cannot make any
            // trust assertions about this device from cross-signing
            return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);
        }
        const deviceObj = deviceToObject(device, userCrossSigning.userId);
        try {
            // if we can verify the user's SSK from their master key...
            olmlib_1.pkVerify(userSSK, userCrossSigning.getId(), userCrossSigning.userId);
            // ...and this device's key from their SSK...
            olmlib_1.pkVerify(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId);
            // ...then we trust this device as much as far as we trust the user
            return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices);
        }
        catch (e) {
            return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);
        }
    }
    /**
     * @returns {object} Cache callbacks
     */
    getCacheCallbacks() {
        return this.cacheCallbacks;
    }
}
exports.CrossSigningInfo = CrossSigningInfo;
function deviceToObject(device, userId) {
    return {
        algorithms: device.algorithms,
        keys: device.keys,
        device_id: device.deviceId,
        user_id: userId,
        signatures: device.signatures,
    };
}
var CrossSigningLevel;
(function (CrossSigningLevel) {
    CrossSigningLevel[CrossSigningLevel["MASTER"] = 4] = "MASTER";
    CrossSigningLevel[CrossSigningLevel["USER_SIGNING"] = 2] = "USER_SIGNING";
    CrossSigningLevel[CrossSigningLevel["SELF_SIGNING"] = 1] = "SELF_SIGNING";
})(CrossSigningLevel = exports.CrossSigningLevel || (exports.CrossSigningLevel = {}));
/**
 * Represents the ways in which we trust a user
 */
class UserTrustLevel {
    constructor(crossSigningVerified, crossSigningVerifiedBefore, tofu) {
        this.crossSigningVerified = crossSigningVerified;
        this.crossSigningVerifiedBefore = crossSigningVerifiedBefore;
        this.tofu = tofu;
    }
    /**
     * @returns {boolean} true if this user is verified via any means
     */
    isVerified() {
        return this.isCrossSigningVerified();
    }
    /**
     * @returns {boolean} true if this user is verified via cross signing
     */
    isCrossSigningVerified() {
        return this.crossSigningVerified;
    }
    /**
     * @returns {boolean} true if we ever verified this user before (at least for
     * the history of verifications observed by this device).
     */
    wasCrossSigningVerified() {
        return this.crossSigningVerifiedBefore;
    }
    /**
     * @returns {boolean} true if this user's key is trusted on first use
     */
    isTofu() {
        return this.tofu;
    }
}
exports.UserTrustLevel = UserTrustLevel;
/**
 * Represents the ways in which we trust a device
 */
class DeviceTrustLevel {
    constructor(crossSigningVerified, tofu, localVerified, trustCrossSignedDevices) {
        this.crossSigningVerified = crossSigningVerified;
        this.tofu = tofu;
        this.localVerified = localVerified;
        this.trustCrossSignedDevices = trustCrossSignedDevices;
    }
    static fromUserTrustLevel(userTrustLevel, localVerified, trustCrossSignedDevices) {
        return new DeviceTrustLevel(userTrustLevel.isCrossSigningVerified(), userTrustLevel.isTofu(), localVerified, trustCrossSignedDevices);
    }
    /**
     * @returns {boolean} true if this device is verified via any means
     */
    isVerified() {
        return Boolean(this.isLocallyVerified() || (this.trustCrossSignedDevices && this.isCrossSigningVerified()));
    }
    /**
     * @returns {boolean} true if this device is verified via cross signing
     */
    isCrossSigningVerified() {
        return this.crossSigningVerified;
    }
    /**
     * @returns {boolean} true if this device is verified locally
     */
    isLocallyVerified() {
        return this.localVerified;
    }
    /**
     * @returns {boolean} true if this device is trusted from a user's key
     * that is trusted on first use
     */
    isTofu() {
        return this.tofu;
    }
}
exports.DeviceTrustLevel = DeviceTrustLevel;
function createCryptoStoreCacheCallbacks(store, olmDevice) {
    return {
        getCrossSigningKeyCache: function (type, _expectedPublicKey) {
            return __awaiter(this, void 0, void 0, function* () {
                const key = yield new Promise((resolve) => {
                    return store.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                        store.getSecretStorePrivateKey(txn, resolve, type);
                    });
                });
                if (key && key.ciphertext) {
                    const pickleKey = Buffer.from(olmDevice._pickleKey);
                    const decrypted = yield aes_1.decryptAES(key, pickleKey, type);
                    return olmlib_1.decodeBase64(decrypted);
                }
                else {
                    return key;
                }
            });
        },
        storeCrossSigningKeyCache: function (type, key) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!(key instanceof Uint8Array)) {
                    throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${key}`);
                }
                const pickleKey = Buffer.from(olmDevice._pickleKey);
                const encryptedKey = yield aes_1.encryptAES(olmlib_1.encodeBase64(key), pickleKey, type);
                return store.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                    store.storeSecretStorePrivateKey(txn, type, encryptedKey);
                });
            });
        },
    };
}
exports.createCryptoStoreCacheCallbacks = createCryptoStoreCacheCallbacks;
/**
 * Request cross-signing keys from another device during verification.
 *
 * @param {MatrixClient} baseApis base Matrix API interface
 * @param {string} userId The user ID being verified
 * @param {string} deviceId The device ID being verified
 */
function requestKeysDuringVerification(baseApis, userId, deviceId) {
    return __awaiter(this, void 0, void 0, function* () {
        // If this is a self-verification, ask the other party for keys
        if (baseApis.getUserId() !== userId) {
            return;
        }
        logger_1.logger.log("Cross-signing: Self-verification done; requesting keys");
        // This happens asynchronously, and we're not concerned about waiting for
        // it.  We return here in order to test.
        return new Promise((resolve, reject) => {
            const client = baseApis;
            const original = client.crypto.crossSigningInfo;
            // We already have all of the infrastructure we need to validate and
            // cache cross-signing keys, so instead of replicating that, here we set
            // up callbacks that request them from the other device and call
            // CrossSigningInfo.getCrossSigningKey() to validate/cache
            const crossSigning = new CrossSigningInfo(original.userId, { getCrossSigningKey: (type) => __awaiter(this, void 0, void 0, function* () {
                    logger_1.logger.debug("Cross-signing: requesting secret", type, deviceId);
                    const { promise } = client.requestSecret(`m.cross_signing.${type}`, [deviceId]);
                    const result = yield promise;
                    const decoded = olmlib_1.decodeBase64(result);
                    return Uint8Array.from(decoded);
                }) }, original.getCacheCallbacks());
            crossSigning.keys = original.keys;
            // XXX: get all keys out if we get one key out
            // https://github.com/vector-im/element-web/issues/12604
            // then change here to reject on the timeout
            // Requests can be ignored, so don't wait around forever
            const timeout = new Promise((resolve, reject) => {
                setTimeout(resolve, KEY_REQUEST_TIMEOUT_MS, new Error("Timeout"));
            });
            // also request and cache the key backup key
            const backupKeyPromise = (() => __awaiter(this, void 0, void 0, function* () {
                const cachedKey = yield client.crypto.getSessionBackupPrivateKey();
                if (!cachedKey) {
                    logger_1.logger.info("No cached backup key found. Requesting...");
                    const secretReq = client.requestSecret('m.megolm_backup.v1', [deviceId]);
                    const base64Key = yield secretReq.promise;
                    logger_1.logger.info("Got key backup key, decoding...");
                    const decodedKey = olmlib_1.decodeBase64(base64Key);
                    logger_1.logger.info("Decoded backup key, storing...");
                    client.crypto.storeSessionBackupPrivateKey(Uint8Array.from(decodedKey));
                    logger_1.logger.info("Backup key stored. Starting backup restore...");
                    const backupInfo = yield client.getKeyBackupVersion();
                    // no need to await for this - just let it go in the bg
                    client.restoreKeyBackupWithCache(undefined, undefined, backupInfo).then(() => {
                        logger_1.logger.info("Backup restored.");
                    });
                }
            }))();
            // We call getCrossSigningKey() for its side-effects
            return Promise.race([
                Promise.all([
                    crossSigning.getCrossSigningKey("master"),
                    crossSigning.getCrossSigningKey("self_signing"),
                    crossSigning.getCrossSigningKey("user_signing"),
                    backupKeyPromise,
                ]),
                timeout,
            ]).then(resolve, reject);
        }).catch((e) => {
            logger_1.logger.warn("Cross-signing: failure while requesting keys:", e);
        });
    });
}
exports.requestKeysDuringVerification = requestKeysDuringVerification;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"../crypto/store/indexeddb-crypto-store":88,"../logger":106,"./aes":74,"./olmlib":85,"buffer":34,"events":36}],68:[function(require,module,exports){
"use strict";
/*
Copyright 2017 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeviceList = void 0;
/**
 * @module crypto/DeviceList
 *
 * Manages the list of other users' devices
 */
const events_1 = require("events");
const logger_1 = require("../logger");
const deviceinfo_1 = require("./deviceinfo");
const CrossSigning_1 = require("./CrossSigning");
const olmlib = __importStar(require("./olmlib"));
const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store");
const utils_1 = require("../utils");
/* State transition diagram for DeviceList.deviceTrackingStatus
 *
 *                                |
 *     stopTrackingDeviceList     V
 *   +---------------------> NOT_TRACKED
 *   |                            |
 *   +<--------------------+      | startTrackingDeviceList
 *   |                     |      V
 *   |   +-------------> PENDING_DOWNLOAD <--------------------+-+
 *   |   |                      ^ |                            | |
 *   |   | restart     download | |  start download            | | invalidateUserDeviceList
 *   |   | client        failed | |                            | |
 *   |   |                      | V                            | |
 *   |   +------------ DOWNLOAD_IN_PROGRESS -------------------+ |
 *   |                    |       |                              |
 *   +<-------------------+       |  download successful         |
 *   ^                            V                              |
 *   +----------------------- UP_TO_DATE ------------------------+
 */
// constants for DeviceList.deviceTrackingStatus
var TrackingStatus;
(function (TrackingStatus) {
    TrackingStatus[TrackingStatus["NotTracked"] = 0] = "NotTracked";
    TrackingStatus[TrackingStatus["PendingDownload"] = 1] = "PendingDownload";
    TrackingStatus[TrackingStatus["DownloadInProgress"] = 2] = "DownloadInProgress";
    TrackingStatus[TrackingStatus["UpToDate"] = 3] = "UpToDate";
})(TrackingStatus || (TrackingStatus = {}));
/**
 * @alias module:crypto/DeviceList
 */
class DeviceList extends events_1.EventEmitter {
    constructor(baseApis, cryptoStore, olmDevice, 
    // Maximum number of user IDs per request to prevent server overload (#1619)
    keyDownloadChunkSize = 250) {
        super();
        this.cryptoStore = cryptoStore;
        this.keyDownloadChunkSize = keyDownloadChunkSize;
        // userId -> {
        //     deviceId -> {
        //         [device info]
        //     }
        // }
        this.devices = {};
        // userId -> {
        //     [key info]
        // }
        this.crossSigningInfo = {};
        // map of identity keys to the user who owns it
        this.userByIdentityKey = {};
        // which users we are tracking device status for.
        // userId -> TRACKING_STATUS_*
        this.deviceTrackingStatus = {}; // loaded from storage in load()
        // The 'next_batch' sync token at the point the data was written,
        // ie. a token representing the point immediately after the
        // moment represented by the snapshot in the db.
        this.syncToken = null;
        // userId -> promise
        this.keyDownloadsInProgressByUser = {};
        // Set whenever changes are made other than setting the sync token
        this.dirty = false;
        // Promise resolved when device data is saved
        this.savePromise = null;
        // Function that resolves the save promise
        this.resolveSavePromise = null;
        // The time the save is scheduled for
        this.savePromiseTime = null;
        // The timer used to delay the save
        this.saveTimer = null;
        // True if we have fetched data from the server or loaded a non-empty
        // set of device data from the store
        this.hasFetched = null;
        this.serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, this);
    }
    /**
     * Load the device tracking state from storage
     */
    load() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.cryptoStore.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {
                this.cryptoStore.getEndToEndDeviceData(txn, (deviceData) => {
                    this.hasFetched = Boolean(deviceData && deviceData.devices);
                    this.devices = deviceData ? deviceData.devices : {},
                        this.crossSigningInfo = deviceData ?
                            deviceData.crossSigningInfo || {} : {};
                    this.deviceTrackingStatus = deviceData ?
                        deviceData.trackingStatus : {};
                    this.syncToken = deviceData ? deviceData.syncToken : null;
                    this.userByIdentityKey = {};
                    for (const user of Object.keys(this.devices)) {
                        const userDevices = this.devices[user];
                        for (const device of Object.keys(userDevices)) {
                            const idKey = userDevices[device].keys['curve25519:' + device];
                            if (idKey !== undefined) {
                                this.userByIdentityKey[idKey] = user;
                            }
                        }
                    }
                });
            });
            for (const u of Object.keys(this.deviceTrackingStatus)) {
                // if a download was in progress when we got shut down, it isn't any more.
                if (this.deviceTrackingStatus[u] == TrackingStatus.DownloadInProgress) {
                    this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;
                }
            }
        });
    }
    stop() {
        if (this.saveTimer !== null) {
            clearTimeout(this.saveTimer);
        }
    }
    /**
     * Save the device tracking state to storage, if any changes are
     * pending other than updating the sync token
     *
     * The actual save will be delayed by a short amount of time to
     * aggregate multiple writes to the database.
     *
     * @param {number} delay Time in ms before which the save actually happens.
     *     By default, the save is delayed for a short period in order to batch
     *     multiple writes, but this behaviour can be disabled by passing 0.
     *
     * @return {Promise<boolean>} true if the data was saved, false if
     *     it was not (eg. because no changes were pending). The promise
     *     will only resolve once the data is saved, so may take some time
     *     to resolve.
     */
    saveIfDirty(delay = 500) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.dirty)
                return Promise.resolve(false);
            // Delay saves for a bit so we can aggregate multiple saves that happen
            // in quick succession (eg. when a whole room's devices are marked as known)
            const targetTime = Date.now() + delay;
            if (this.savePromiseTime && targetTime < this.savePromiseTime) {
                // There's a save scheduled but for after we would like: cancel
                // it & schedule one for the time we want
                clearTimeout(this.saveTimer);
                this.saveTimer = null;
                this.savePromiseTime = null;
                // (but keep the save promise since whatever called save before
                // will still want to know when the save is done)
            }
            let savePromise = this.savePromise;
            if (savePromise === null) {
                savePromise = new Promise((resolve, reject) => {
                    this.resolveSavePromise = resolve;
                });
                this.savePromise = savePromise;
            }
            if (this.saveTimer === null) {
                const resolveSavePromise = this.resolveSavePromise;
                this.savePromiseTime = targetTime;
                this.saveTimer = setTimeout(() => {
                    logger_1.logger.log('Saving device tracking data', this.syncToken);
                    // null out savePromise now (after the delay but before the write),
                    // otherwise we could return the existing promise when the save has
                    // actually already happened.
                    this.savePromiseTime = null;
                    this.saveTimer = null;
                    this.savePromise = null;
                    this.resolveSavePromise = null;
                    this.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {
                        this.cryptoStore.storeEndToEndDeviceData({
                            devices: this.devices,
                            crossSigningInfo: this.crossSigningInfo,
                            trackingStatus: this.deviceTrackingStatus,
                            syncToken: this.syncToken,
                        }, txn);
                    }).then(() => {
                        // The device list is considered dirty until the write completes.
                        this.dirty = false;
                        resolveSavePromise(true);
                    }, err => {
                        logger_1.logger.error('Failed to save device tracking data', this.syncToken);
                        logger_1.logger.error(err);
                    });
                }, delay);
            }
            return savePromise;
        });
    }
    /**
     * Gets the sync token last set with setSyncToken
     *
     * @return {string} The sync token
     */
    getSyncToken() {
        return this.syncToken;
    }
    /**
     * Sets the sync token that the app will pass as the 'since' to the /sync
     * endpoint next time it syncs.
     * The sync token must always be set after any changes made as a result of
     * data in that sync since setting the sync token to a newer one will mean
     * those changed will not be synced from the server if a new client starts
     * up with that data.
     *
     * @param {string} st The sync token
     */
    setSyncToken(st) {
        this.syncToken = st;
    }
    /**
     * Ensures up to date keys for a list of users are stored in the session store,
     * downloading and storing them if they're not (or if forceDownload is
     * true).
     * @param {Array} userIds The users to fetch.
     * @param {boolean} forceDownload Always download the keys even if cached.
     *
     * @return {Promise} A promise which resolves to a map userId->deviceId->{@link
     * module:crypto/deviceinfo|DeviceInfo}.
     */
    downloadKeys(userIds, forceDownload) {
        const usersToDownload = [];
        const promises = [];
        userIds.forEach((u) => {
            const trackingStatus = this.deviceTrackingStatus[u];
            if (this.keyDownloadsInProgressByUser[u]) {
                // already a key download in progress/queued for this user; its results
                // will be good enough for us.
                logger_1.logger.log(`downloadKeys: already have a download in progress for ` +
                    `${u}: awaiting its result`);
                promises.push(this.keyDownloadsInProgressByUser[u]);
            }
            else if (forceDownload || trackingStatus != TrackingStatus.UpToDate) {
                usersToDownload.push(u);
            }
        });
        if (usersToDownload.length != 0) {
            logger_1.logger.log("downloadKeys: downloading for", usersToDownload);
            const downloadPromise = this.doKeyDownload(usersToDownload);
            promises.push(downloadPromise);
        }
        if (promises.length === 0) {
            logger_1.logger.log("downloadKeys: already have all necessary keys");
        }
        return Promise.all(promises).then(() => {
            return this.getDevicesFromStore(userIds);
        });
    }
    /**
     * Get the stored device keys for a list of user ids
     *
     * @param {string[]} userIds the list of users to list keys for.
     *
     * @return {Object} userId->deviceId->{@link module:crypto/deviceinfo|DeviceInfo}.
     */
    getDevicesFromStore(userIds) {
        const stored = {};
        userIds.map((u) => {
            stored[u] = {};
            const devices = this.getStoredDevicesForUser(u) || [];
            devices.map(function (dev) {
                stored[u][dev.deviceId] = dev;
            });
        });
        return stored;
    }
    /**
     * Returns a list of all user IDs the DeviceList knows about
     *
     * @return {array} All known user IDs
     */
    getKnownUserIds() {
        return Object.keys(this.devices);
    }
    /**
     * Get the stored device keys for a user id
     *
     * @param {string} userId the user to list keys for.
     *
     * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't
     * managed to get a list of devices for this user yet.
     */
    getStoredDevicesForUser(userId) {
        const devs = this.devices[userId];
        if (!devs) {
            return null;
        }
        const res = [];
        for (const deviceId in devs) {
            if (devs.hasOwnProperty(deviceId)) {
                res.push(deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId));
            }
        }
        return res;
    }
    /**
     * Get the stored device data for a user, in raw object form
     *
     * @param {string} userId the user to get data for
     *
     * @return {Object} deviceId->{object} devices, or undefined if
     * there is no data for this user.
     */
    getRawStoredDevicesForUser(userId) {
        return this.devices[userId];
    }
    getStoredCrossSigningForUser(userId) {
        if (!this.crossSigningInfo[userId])
            return null;
        return CrossSigning_1.CrossSigningInfo.fromStorage(this.crossSigningInfo[userId], userId);
    }
    storeCrossSigningForUser(userId, info) {
        this.crossSigningInfo[userId] = info;
        this.dirty = true;
    }
    /**
     * Get the stored keys for a single device
     *
     * @param {string} userId
     * @param {string} deviceId
     *
     * @return {module:crypto/deviceinfo?} device, or undefined
     * if we don't know about this device
     */
    getStoredDevice(userId, deviceId) {
        const devs = this.devices[userId];
        if (!devs || !devs[deviceId]) {
            return undefined;
        }
        return deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId);
    }
    /**
     * Get a user ID by one of their device's curve25519 identity key
     *
     * @param {string} algorithm  encryption algorithm
     * @param {string} senderKey  curve25519 key to match
     *
     * @return {string} user ID
     */
    getUserByIdentityKey(algorithm, senderKey) {
        if (algorithm !== olmlib.OLM_ALGORITHM &&
            algorithm !== olmlib.MEGOLM_ALGORITHM) {
            // we only deal in olm keys
            return null;
        }
        return this.userByIdentityKey[senderKey];
    }
    /**
     * Find a device by curve25519 identity key
     *
     * @param {string} algorithm  encryption algorithm
     * @param {string} senderKey  curve25519 key to match
     *
     * @return {module:crypto/deviceinfo?}
     */
    getDeviceByIdentityKey(algorithm, senderKey) {
        const userId = this.getUserByIdentityKey(algorithm, senderKey);
        if (!userId) {
            return null;
        }
        const devices = this.devices[userId];
        if (!devices) {
            return null;
        }
        for (const deviceId in devices) {
            if (!devices.hasOwnProperty(deviceId)) {
                continue;
            }
            const device = devices[deviceId];
            for (const keyId in device.keys) {
                if (!device.keys.hasOwnProperty(keyId)) {
                    continue;
                }
                if (keyId.indexOf("curve25519:") !== 0) {
                    continue;
                }
                const deviceKey = device.keys[keyId];
                if (deviceKey == senderKey) {
                    return deviceinfo_1.DeviceInfo.fromStorage(device, deviceId);
                }
            }
        }
        // doesn't match a known device
        return null;
    }
    /**
     * Replaces the list of devices for a user with the given device list
     *
     * @param {string} userId The user ID
     * @param {Object} devices New device info for user
     */
    storeDevicesForUser(userId, devices) {
        this.setRawStoredDevicesForUser(userId, devices);
        this.dirty = true;
    }
    /**
     * flag the given user for device-list tracking, if they are not already.
     *
     * This will mean that a subsequent call to refreshOutdatedDeviceLists()
     * will download the device list for the user, and that subsequent calls to
     * invalidateUserDeviceList will trigger more updates.
     *
     * @param {String} userId
     */
    startTrackingDeviceList(userId) {
        // sanity-check the userId. This is mostly paranoia, but if synapse
        // can't parse the userId we give it as an mxid, it 500s the whole
        // request and we can never update the device lists again (because
        // the broken userId is always 'invalid' and always included in any
        // refresh request).
        // By checking it is at least a string, we can eliminate a class of
        // silly errors.
        if (typeof userId !== 'string') {
            throw new Error('userId must be a string; was ' + userId);
        }
        if (!this.deviceTrackingStatus[userId]) {
            logger_1.logger.log('Now tracking device list for ' + userId);
            this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;
            // we don't yet persist the tracking status, since there may be a lot
            // of calls; we save all data together once the sync is done
            this.dirty = true;
        }
    }
    /**
     * Mark the given user as no longer being tracked for device-list updates.
     *
     * This won't affect any in-progress downloads, which will still go on to
     * complete; it will just mean that we don't think that we have an up-to-date
     * list for future calls to downloadKeys.
     *
     * @param {String} userId
     */
    stopTrackingDeviceList(userId) {
        if (this.deviceTrackingStatus[userId]) {
            logger_1.logger.log('No longer tracking device list for ' + userId);
            this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;
            // we don't yet persist the tracking status, since there may be a lot
            // of calls; we save all data together once the sync is done
            this.dirty = true;
        }
    }
    /**
     * Set all users we're currently tracking to untracked
     *
     * This will flag each user whose devices we are tracking as in need of an
     * update.
     */
    stopTrackingAllDeviceLists() {
        for (const userId of Object.keys(this.deviceTrackingStatus)) {
            this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;
        }
        this.dirty = true;
    }
    /**
     * Mark the cached device list for the given user outdated.
     *
     * If we are not tracking this user's devices, we'll do nothing. Otherwise
     * we flag the user as needing an update.
     *
     * This doesn't actually set off an update, so that several users can be
     * batched together. Call refreshOutdatedDeviceLists() for that.
     *
     * @param {String} userId
     */
    invalidateUserDeviceList(userId) {
        if (this.deviceTrackingStatus[userId]) {
            logger_1.logger.log("Marking device list outdated for", userId);
            this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;
            // we don't yet persist the tracking status, since there may be a lot
            // of calls; we save all data together once the sync is done
            this.dirty = true;
        }
    }
    /**
     * If we have users who have outdated device lists, start key downloads for them
     *
     * @returns {Promise} which completes when the download completes; normally there
     *    is no need to wait for this (it's mostly for the unit tests).
     */
    refreshOutdatedDeviceLists() {
        this.saveIfDirty();
        const usersToDownload = [];
        for (const userId of Object.keys(this.deviceTrackingStatus)) {
            const stat = this.deviceTrackingStatus[userId];
            if (stat == TrackingStatus.PendingDownload) {
                usersToDownload.push(userId);
            }
        }
        return this.doKeyDownload(usersToDownload);
    }
    /**
     * Set the stored device data for a user, in raw object form
     * Used only by internal class DeviceListUpdateSerialiser
     *
     * @param {string} userId the user to get data for
     *
     * @param {Object} devices deviceId->{object} the new devices
     */
    setRawStoredDevicesForUser(userId, devices) {
        // remove old devices from userByIdentityKey
        if (this.devices[userId] !== undefined) {
            for (const [deviceId, dev] of Object.entries(this.devices[userId])) {
                const identityKey = dev.keys['curve25519:' + deviceId];
                delete this.userByIdentityKey[identityKey];
            }
        }
        this.devices[userId] = devices;
        // add new devices into userByIdentityKey
        for (const [deviceId, dev] of Object.entries(devices)) {
            const identityKey = dev.keys['curve25519:' + deviceId];
            this.userByIdentityKey[identityKey] = userId;
        }
    }
    setRawStoredCrossSigningForUser(userId, info) {
        this.crossSigningInfo[userId] = info;
    }
    /**
     * Fire off download update requests for the given users, and update the
     * device list tracking status for them, and the
     * keyDownloadsInProgressByUser map for them.
     *
     * @param {String[]} users  list of userIds
     *
     * @return {Promise} resolves when all the users listed have
     *     been updated. rejects if there was a problem updating any of the
     *     users.
     */
    doKeyDownload(users) {
        if (users.length === 0) {
            // nothing to do
            return Promise.resolve();
        }
        const prom = this.serialiser.updateDevicesForUsers(users, this.syncToken).then(() => {
            finished(true);
        }, (e) => {
            logger_1.logger.error('Error downloading keys for ' + users + ":", e);
            finished(false);
            throw e;
        });
        users.forEach((u) => {
            this.keyDownloadsInProgressByUser[u] = prom;
            const stat = this.deviceTrackingStatus[u];
            if (stat == TrackingStatus.PendingDownload) {
                this.deviceTrackingStatus[u] = TrackingStatus.DownloadInProgress;
            }
        });
        const finished = (success) => {
            this.emit("crypto.willUpdateDevices", users, !this.hasFetched);
            users.forEach((u) => {
                this.dirty = true;
                // we may have queued up another download request for this user
                // since we started this request. If that happens, we should
                // ignore the completion of the first one.
                if (this.keyDownloadsInProgressByUser[u] !== prom) {
                    logger_1.logger.log('Another update in the queue for', u, '- not marking up-to-date');
                    return;
                }
                delete this.keyDownloadsInProgressByUser[u];
                const stat = this.deviceTrackingStatus[u];
                if (stat == TrackingStatus.DownloadInProgress) {
                    if (success) {
                        // we didn't get any new invalidations since this download started:
                        // this user's device list is now up to date.
                        this.deviceTrackingStatus[u] = TrackingStatus.UpToDate;
                        logger_1.logger.log("Device list for", u, "now up to date");
                    }
                    else {
                        this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;
                    }
                }
            });
            this.saveIfDirty();
            this.emit("crypto.devicesUpdated", users, !this.hasFetched);
            this.hasFetched = true;
        };
        return prom;
    }
}
exports.DeviceList = DeviceList;
/**
 * Serialises updates to device lists
 *
 * Ensures that results from /keys/query are not overwritten if a second call
 * completes *before* an earlier one.
 *
 * It currently does this by ensuring only one call to /keys/query happens at a
 * time (and queuing other requests up).
 */
class DeviceListUpdateSerialiser {
    /*
     * @param {object} baseApis Base API object
     * @param {object} olmDevice The Olm Device
     * @param {object} deviceList The device list object, the device list to be updated
     */
    constructor(baseApis, olmDevice, deviceList) {
        this.baseApis = baseApis;
        this.olmDevice = olmDevice;
        this.deviceList = deviceList;
        this.downloadInProgress = false;
        // users which are queued for download
        // userId -> true
        this.keyDownloadsQueuedByUser = {};
        // deferred which is resolved when the queued users are downloaded.
        // non-null indicates that we have users queued for download.
        this.queuedQueryDeferred = null;
        this.syncToken = null; // The sync token we send with the requests
    }
    /**
     * Make a key query request for the given users
     *
     * @param {String[]} users list of user ids
     *
     * @param {String} syncToken sync token to pass in the query request, to
     *     help the HS give the most recent results
     *
     * @return {Promise} resolves when all the users listed have
     *     been updated. rejects if there was a problem updating any of the
     *     users.
     */
    updateDevicesForUsers(users, syncToken) {
        users.forEach((u) => {
            this.keyDownloadsQueuedByUser[u] = true;
        });
        if (!this.queuedQueryDeferred) {
            this.queuedQueryDeferred = utils_1.defer();
        }
        // We always take the new sync token and just use the latest one we've
        // been given, since it just needs to be at least as recent as the
        // sync response the device invalidation message arrived in
        this.syncToken = syncToken;
        if (this.downloadInProgress) {
            // just queue up these users
            logger_1.logger.log('Queued key download for', users);
            return this.queuedQueryDeferred.promise;
        }
        // start a new download.
        return this.doQueuedQueries();
    }
    doQueuedQueries() {
        if (this.downloadInProgress) {
            throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");
        }
        const downloadUsers = Object.keys(this.keyDownloadsQueuedByUser);
        this.keyDownloadsQueuedByUser = {};
        const deferred = this.queuedQueryDeferred;
        this.queuedQueryDeferred = null;
        logger_1.logger.log('Starting key download for', downloadUsers);
        this.downloadInProgress = true;
        const opts = {};
        if (this.syncToken) {
            opts.token = this.syncToken;
        }
        const factories = [];
        for (let i = 0; i < downloadUsers.length; i += this.deviceList.keyDownloadChunkSize) {
            const userSlice = downloadUsers.slice(i, i + this.deviceList.keyDownloadChunkSize);
            factories.push(() => this.baseApis.downloadKeysForUsers(userSlice, opts));
        }
        utils_1.chunkPromises(factories, 3).then((responses) => __awaiter(this, void 0, void 0, function* () {
            const dk = Object.assign({}, ...(responses.map(res => res.device_keys || {})));
            const masterKeys = Object.assign({}, ...(responses.map(res => res.master_keys || {})));
            const ssks = Object.assign({}, ...(responses.map(res => res.self_signing_keys || {})));
            const usks = Object.assign({}, ...(responses.map(res => res.user_signing_keys || {})));
            // yield to other things that want to execute in between users, to
            // avoid wedging the CPU
            // (https://github.com/vector-im/element-web/issues/3158)
            //
            // of course we ought to do this in a web worker or similar, but
            // this serves as an easy solution for now.
            for (const userId of downloadUsers) {
                yield utils_1.sleep(5);
                try {
                    yield this.processQueryResponseForUser(userId, dk[userId], {
                        master: masterKeys[userId],
                        self_signing: ssks[userId],
                        user_signing: usks[userId],
                    });
                }
                catch (e) {
                    // log the error but continue, so that one bad key
                    // doesn't kill the whole process
                    logger_1.logger.error(`Error processing keys for ${userId}:`, e);
                }
            }
        })).then(() => {
            logger_1.logger.log('Completed key download for ' + downloadUsers);
            this.downloadInProgress = false;
            deferred.resolve();
            // if we have queued users, fire off another request.
            if (this.queuedQueryDeferred) {
                this.doQueuedQueries();
            }
        }, (e) => {
            logger_1.logger.warn('Error downloading keys for ' + downloadUsers + ':', e);
            this.downloadInProgress = false;
            deferred.reject(e);
        });
        return deferred.promise;
    }
    processQueryResponseForUser(userId, dkResponse, crossSigningResponse) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log('got device keys for ' + userId + ':', dkResponse);
            logger_1.logger.log('got cross-signing keys for ' + userId + ':', crossSigningResponse);
            {
                // map from deviceid -> deviceinfo for this user
                const userStore = {};
                const devs = this.deviceList.getRawStoredDevicesForUser(userId);
                if (devs) {
                    Object.keys(devs).forEach((deviceId) => {
                        const d = deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId);
                        userStore[deviceId] = d;
                    });
                }
                yield updateStoredDeviceKeysForUser(this.olmDevice, userId, userStore, dkResponse || {}, this.baseApis.getUserId(), this.baseApis.deviceId);
                // put the updates into the object that will be returned as our results
                const storage = {};
                Object.keys(userStore).forEach((deviceId) => {
                    storage[deviceId] = userStore[deviceId].toStorage();
                });
                this.deviceList.setRawStoredDevicesForUser(userId, storage);
            }
            // now do the same for the cross-signing keys
            {
                // FIXME: should we be ignoring empty cross-signing responses, or
                // should we be dropping the keys?
                if (crossSigningResponse
                    && (crossSigningResponse.master || crossSigningResponse.self_signing
                        || crossSigningResponse.user_signing)) {
                    const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId)
                        || new CrossSigning_1.CrossSigningInfo(userId);
                    crossSigning.setKeys(crossSigningResponse);
                    this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage());
                    // NB. Unlike most events in the js-sdk, this one is internal to the
                    // js-sdk and is not re-emitted
                    this.deviceList.emit('userCrossSigningUpdated', userId);
                }
            }
        });
    }
}
function updateStoredDeviceKeysForUser(olmDevice, userId, userStore, userResult, localUserId, localDeviceId) {
    return __awaiter(this, void 0, void 0, function* () {
        let updated = false;
        // remove any devices in the store which aren't in the response
        for (const deviceId in userStore) {
            if (!userStore.hasOwnProperty(deviceId)) {
                continue;
            }
            if (!(deviceId in userResult)) {
                if (userId === localUserId && deviceId === localDeviceId) {
                    logger_1.logger.warn(`Local device ${deviceId} missing from sync, skipping removal`);
                    continue;
                }
                logger_1.logger.log("Device " + userId + ":" + deviceId +
                    " has been removed");
                delete userStore[deviceId];
                updated = true;
            }
        }
        for (const deviceId in userResult) {
            if (!userResult.hasOwnProperty(deviceId)) {
                continue;
            }
            const deviceResult = userResult[deviceId];
            // check that the user_id and device_id in the response object are
            // correct
            if (deviceResult.user_id !== userId) {
                logger_1.logger.warn("Mismatched user_id " + deviceResult.user_id +
                    " in keys from " + userId + ":" + deviceId);
                continue;
            }
            if (deviceResult.device_id !== deviceId) {
                logger_1.logger.warn("Mismatched device_id " + deviceResult.device_id +
                    " in keys from " + userId + ":" + deviceId);
                continue;
            }
            if (yield storeDeviceKeys(olmDevice, userStore, deviceResult)) {
                updated = true;
            }
        }
        return updated;
    });
}
/*
 * Process a device in a /query response, and add it to the userStore
 *
 * returns (a promise for) true if a change was made, else false
 */
function storeDeviceKeys(olmDevice, userStore, deviceResult) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!deviceResult.keys) {
            // no keys?
            return false;
        }
        const deviceId = deviceResult.device_id;
        const userId = deviceResult.user_id;
        const signKeyId = "ed25519:" + deviceId;
        const signKey = deviceResult.keys[signKeyId];
        if (!signKey) {
            logger_1.logger.warn("Device " + userId + ":" + deviceId + " has no ed25519 key");
            return false;
        }
        const unsigned = deviceResult.unsigned || {};
        const signatures = deviceResult.signatures || {};
        try {
            yield olmlib.verifySignature(olmDevice, deviceResult, userId, deviceId, signKey);
        }
        catch (e) {
            logger_1.logger.warn("Unable to verify signature on device " + userId + ":" + deviceId + ":" + e);
            return false;
        }
        // DeviceInfo
        let deviceStore;
        if (deviceId in userStore) {
            // already have this device.
            deviceStore = userStore[deviceId];
            if (deviceStore.getFingerprint() != signKey) {
                // this should only happen if the list has been MITMed; we are
                // best off sticking with the original keys.
                //
                // Should we warn the user about it somehow?
                logger_1.logger.warn("Ed25519 key for device " + userId + ":" +
                    deviceId + " has changed");
                return false;
            }
        }
        else {
            userStore[deviceId] = deviceStore = new deviceinfo_1.DeviceInfo(deviceId);
        }
        deviceStore.keys = deviceResult.keys || {};
        deviceStore.algorithms = deviceResult.algorithms || [];
        deviceStore.unsigned = unsigned;
        deviceStore.signatures = signatures;
        return true;
    });
}

},{"../logger":106,"../utils":137,"./CrossSigning":67,"./deviceinfo":82,"./olmlib":85,"./store/indexeddb-crypto-store":88,"events":36}],69:[function(require,module,exports){
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptionSetupOperation = exports.EncryptionSetupBuilder = void 0;
const logger_1 = require("../logger");
const event_1 = require("../models/event");
const events_1 = require("events");
const CrossSigning_1 = require("./CrossSigning");
const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store");
const http_api_1 = require("../http-api");
/**
 * Builds an EncryptionSetupOperation by calling any of the add.. methods.
 * Once done, `buildOperation()` can be called which allows to apply to operation.
 *
 * This is used as a helper by Crypto to keep track of all the network requests
 * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)
 * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them
 * more than once.
 */
class EncryptionSetupBuilder {
    /**
     * @param {Object.<String, MatrixEvent>} accountData pre-existing account data, will only be read, not written.
     * @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet
     */
    constructor(accountData, delegateCryptoCallbacks) {
        this.crossSigningKeys = null;
        this.keySignatures = null;
        this.keyBackupInfo = null;
        this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);
        this.crossSigningCallbacks = new CrossSigningCallbacks();
        this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);
    }
    /**
     * Adds new cross-signing public keys
     *
     * @param {function} authUpload Function called to await an interactive auth
     * flow when uploading device signing keys.
     * Args:
     *     {function} A function that makes the request requiring auth. Receives
     *     the auth data as an object. Can be called multiple times, first with
     *     an empty authDict, to obtain the flows.
     * @param {Object} keys the new keys
     */
    addCrossSigningKeys(authUpload, keys) {
        this.crossSigningKeys = { authUpload, keys };
    }
    /**
     * Adds the key backup info to be updated on the server
     *
     * Used either to create a new key backup, or add signatures
     * from the new MSK.
     *
     * @param {Object} keyBackupInfo as received from/sent to the server
     */
    addSessionBackup(keyBackupInfo) {
        this.keyBackupInfo = keyBackupInfo;
    }
    /**
     * Adds the session backup private key to be updated in the local cache
     *
     * Used after fixing the format of the key
     *
     * @param {Uint8Array} privateKey
     */
    addSessionBackupPrivateKeyToCache(privateKey) {
        this.sessionBackupPrivateKey = privateKey;
    }
    /**
     * Add signatures from a given user and device/x-sign key
     * Used to sign the new cross-signing key with the device key
     *
     * @param {String} userId
     * @param {String} deviceId
     * @param {Object} signature
     */
    addKeySignature(userId, deviceId, signature) {
        if (!this.keySignatures) {
            this.keySignatures = {};
        }
        const userSignatures = this.keySignatures[userId] || {};
        this.keySignatures[userId] = userSignatures;
        userSignatures[deviceId] = signature;
    }
    /**
     * @param {String} type
     * @param {Object} content
     * @return {Promise}
     */
    setAccountData(type, content) {
        return this.accountDataClientAdapter.setAccountData(type, content);
    }
    /**
     * builds the operation containing all the parts that have been added to the builder
     * @return {EncryptionSetupOperation}
     */
    buildOperation() {
        const accountData = this.accountDataClientAdapter.values;
        return new EncryptionSetupOperation(accountData, this.crossSigningKeys, this.keyBackupInfo, this.keySignatures);
    }
    /**
     * Stores the created keys locally.
     *
     * This does not yet store the operation in a way that it can be restored,
     * but that is the idea in the future.
     *
     * @param  {Crypto} crypto
     * @return {Promise}
     */
    persist(crypto) {
        return __awaiter(this, void 0, void 0, function* () {
            // store private keys in cache
            if (this.crossSigningKeys) {
                const cacheCallbacks = CrossSigning_1.createCryptoStoreCacheCallbacks(crypto.cryptoStore, crypto.olmDevice);
                for (const type of ["master", "self_signing", "user_signing"]) {
                    logger_1.logger.log(`Cache ${type} cross-signing private key locally`);
                    const privateKey = this.crossSigningCallbacks.privateKeys.get(type);
                    yield cacheCallbacks.storeCrossSigningKeyCache(type, privateKey);
                }
                // store own cross-sign pubkeys as trusted
                yield crypto.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                    crypto.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningKeys.keys);
                });
            }
            // store session backup key in cache
            if (this.sessionBackupPrivateKey) {
                yield crypto.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey);
            }
        });
    }
}
exports.EncryptionSetupBuilder = EncryptionSetupBuilder;
/**
 * Can be created from EncryptionSetupBuilder, or
 * (in a follow-up PR, not implemented yet) restored from storage, to retry.
 *
 * It does not have knowledge of any private keys, unlike the builder.
 */
class EncryptionSetupOperation {
    /**
     * @param  {Map<String, Object>} accountData
     * @param  {Object} crossSigningKeys
     * @param  {Object} keyBackupInfo
     * @param  {Object} keySignatures
     */
    constructor(accountData, crossSigningKeys, keyBackupInfo, keySignatures) {
        this.accountData = accountData;
        this.crossSigningKeys = crossSigningKeys;
        this.keyBackupInfo = keyBackupInfo;
        this.keySignatures = keySignatures;
    }
    /**
     * Runs the (remaining part of, in the future) operation by sending requests to the server.
     * @param {Crypto} crypto
     */
    apply(crypto) {
        return __awaiter(this, void 0, void 0, function* () {
            const baseApis = crypto.baseApis;
            // upload cross-signing keys
            if (this.crossSigningKeys) {
                const keys = {};
                for (const [name, key] of Object.entries(this.crossSigningKeys.keys)) {
                    keys[name + "_key"] = key;
                }
                // We must only call `uploadDeviceSigningKeys` from inside this auth
                // helper to ensure we properly handle auth errors.
                yield this.crossSigningKeys.authUpload(authDict => {
                    return baseApis.uploadDeviceSigningKeys(authDict, keys);
                });
                // pass the new keys to the main instance of our own CrossSigningInfo.
                crypto.crossSigningInfo.setKeys(this.crossSigningKeys.keys);
            }
            // set account data
            if (this.accountData) {
                for (const [type, content] of this.accountData) {
                    yield baseApis.setAccountData(type, content);
                }
            }
            // upload first cross-signing signatures with the new key
            // (e.g. signing our own device)
            if (this.keySignatures) {
                yield baseApis.uploadKeySignatures(this.keySignatures);
            }
            // need to create/update key backup info
            if (this.keyBackupInfo) {
                if (this.keyBackupInfo.version) {
                    // session backup signature
                    // The backup is trusted because the user provided the private key.
                    // Sign the backup with the cross signing key so the key backup can
                    // be trusted via cross-signing.
                    yield baseApis.http.authedRequest(undefined, "PUT", "/room_keys/version/" + this.keyBackupInfo.version, undefined, {
                        algorithm: this.keyBackupInfo.algorithm,
                        auth_data: this.keyBackupInfo.auth_data,
                    }, { prefix: http_api_1.PREFIX_UNSTABLE });
                }
                else {
                    // add new key backup
                    yield baseApis.http.authedRequest(undefined, "POST", "/room_keys/version", undefined, this.keyBackupInfo, { prefix: http_api_1.PREFIX_UNSTABLE });
                }
            }
        });
    }
}
exports.EncryptionSetupOperation = EncryptionSetupOperation;
/**
 * Catches account data set by SecretStorage during bootstrapping by
 * implementing the methods related to account data in MatrixClient
 */
class AccountDataClientAdapter extends events_1.EventEmitter {
    /**
     * @param  {Object.<String, MatrixEvent>} existingValues existing account data
     */
    constructor(existingValues) {
        super();
        this.existingValues = existingValues;
        this.values = new Map();
    }
    /**
     * @param  {String} type
     * @return {Promise<Object>} the content of the account data
     */
    getAccountDataFromServer(type) {
        return Promise.resolve(this.getAccountData(type));
    }
    /**
     * @param  {String} type
     * @return {Object} the content of the account data
     */
    getAccountData(type) {
        const modifiedValue = this.values.get(type);
        if (modifiedValue) {
            return modifiedValue;
        }
        const existingValue = this.existingValues[type];
        if (existingValue) {
            return existingValue.getContent();
        }
        return null;
    }
    /**
     * @param {String} type
     * @param {Object} content
     * @return {Promise}
     */
    setAccountData(type, content) {
        const lastEvent = this.values.get(type);
        this.values.set(type, content);
        // ensure accountData is emitted on the next tick,
        // as SecretStorage listens for it while calling this method
        // and it seems to rely on this.
        return Promise.resolve().then(() => {
            const event = new event_1.MatrixEvent({ type, content });
            this.emit("accountData", event, lastEvent);
        });
    }
}
/**
 * Catches the private cross-signing keys set during bootstrapping
 * by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks.
 * See CrossSigningInfo constructor
 */
class CrossSigningCallbacks {
    constructor() {
        this.privateKeys = new Map();
    }
    // cache callbacks
    getCrossSigningKeyCache(type, expectedPublicKey) {
        return this.getCrossSigningKey(type, expectedPublicKey);
    }
    storeCrossSigningKeyCache(type, key) {
        this.privateKeys.set(type, key);
        return Promise.resolve();
    }
    // non-cache callbacks
    getCrossSigningKey(type, expectedPubkey) {
        return Promise.resolve(this.privateKeys.get(type));
    }
    saveCrossSigningKeys(privateKeys) {
        for (const [type, privateKey] of Object.entries(privateKeys)) {
            this.privateKeys.set(type, privateKey);
        }
    }
}
/**
 * Catches the 4S private key set during bootstrapping by implementing
 * the SecretStorage crypto callbacks
 */
class SSSSCryptoCallbacks {
    constructor(delegateCryptoCallbacks) {
        this.delegateCryptoCallbacks = delegateCryptoCallbacks;
        this.privateKeys = new Map();
    }
    getSecretStorageKey({ keys }, name) {
        return __awaiter(this, void 0, void 0, function* () {
            for (const keyId of Object.keys(keys)) {
                const privateKey = this.privateKeys.get(keyId);
                if (privateKey) {
                    return [keyId, privateKey];
                }
            }
            // if we don't have the key cached yet, ask
            // for it to the general crypto callbacks and cache it
            if (this.delegateCryptoCallbacks) {
                const result = yield this.delegateCryptoCallbacks.
                    getSecretStorageKey({ keys }, name);
                if (result) {
                    const [keyId, privateKey] = result;
                    this.privateKeys.set(keyId, privateKey);
                }
                return result;
            }
        });
    }
    addPrivateKey(keyId, keyInfo, privKey) {
        var _a, _b;
        this.privateKeys.set(keyId, privKey);
        // Also pass along to application to cache if it wishes
        (_b = (_a = this.delegateCryptoCallbacks) === null || _a === void 0 ? void 0 : _a.cacheSecretStorageKey) === null || _b === void 0 ? void 0 : _b.call(_a, keyId, keyInfo, privKey);
    }
}

},{"../http-api":103,"../logger":106,"../models/event":113,"./CrossSigning":67,"./store/indexeddb-crypto-store":88,"events":36}],70:[function(require,module,exports){
(function (global){(function (){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OlmDevice = OlmDevice;
exports.WITHHELD_MESSAGES = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _logger = require("../logger");

var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store");

var algorithms = _interopRequireWildcard(require("./algorithms"));

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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) { function e(_x63) { return _e.apply(this, arguments); } e.toString = function () { return _e.toString(); }; return e; }(function (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 = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { function e(_x64) { return _e2.apply(this, arguments); } e.toString = function () { return _e2.toString(); }; return e; }(function (e) { didErr = true; err = e; }), f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _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); }

function _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; }

// The maximum size of an event is 65K, and we base64 the content, so this is a
// reasonable approximation to the biggest plaintext we can encrypt.
var MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4;

function checkPayloadLength(payloadString) {
  if (payloadString === undefined) {
    throw new Error("payloadString undefined");
  }

  if (payloadString.length > MAX_PLAINTEXT_LENGTH) {
    // might as well fail early here rather than letting the olm library throw
    // a cryptic memory allocation error.
    //
    // Note that even if we manage to do the encryption, the message send may fail,
    // because by the time we've wrapped the ciphertext in the event object, it may
    // exceed 65K. But at least we won't just fail with "abort()" in that case.
    var err = new Error("Message too long (" + payloadString.length + " bytes). " + "The maximum for an encrypted message is " + MAX_PLAINTEXT_LENGTH + " bytes."); // TODO: [TypeScript] We should have our own error types

    err.data = {
      errcode: "M_TOO_LARGE",
      error: "Payload too large for encrypted message"
    };
    throw err;
  }
}
/**
 * The type of object we use for importing and exporting megolm session data.
 *
 * @typedef {Object} module:crypto/OlmDevice.MegolmSessionData
 * @property {String} sender_key  Sender's Curve25519 device key
 * @property {String[]} forwarding_curve25519_key_chain Devices which forwarded
 *     this session to us (normally empty).
 * @property {Object<string, string>} sender_claimed_keys Other keys the sender claims.
 * @property {String} room_id     Room this session is used in
 * @property {String} session_id  Unique id for the session
 * @property {String} session_key Base64'ed key data
 */

/**
 * Manages the olm cryptography functions. Each OlmDevice has a single
 * OlmAccount and a number of OlmSessions.
 *
 * Accounts and sessions are kept pickled in the cryptoStore.
 *
 * @constructor
 * @alias module:crypto/OlmDevice
 *
 * @param {Object} cryptoStore A store for crypto data
 *
 * @property {string} deviceCurve25519Key   Curve25519 key for the account
 * @property {string} deviceEd25519Key      Ed25519 key for the account
 */


function OlmDevice(cryptoStore) {
  this._cryptoStore = cryptoStore;
  this._pickleKey = "DEFAULT_KEY"; // don't know these until we load the account from storage in init()

  this.deviceCurve25519Key = null;
  this.deviceEd25519Key = null;
  this._maxOneTimeKeys = null; // we don't bother stashing outboundgroupsessions in the cryptoStore -
  // instead we keep them here.

  this._outboundGroupSessionStore = {}; // Store a set of decrypted message indexes for each group session.
  // This partially mitigates a replay attack where a MITM resends a group
  // message into the room.
  //
  // When we decrypt a message and the message index matches a previously
  // decrypted message, one possible cause of that is that we are decrypting
  // the same event, and may not indicate an actual replay attack.  For
  // example, this could happen if we receive events, forget about them, and
  // then re-fetch them when we backfill.  So we store the event ID and
  // timestamp corresponding to each message index when we first decrypt it,
  // and compare these against the event ID and timestamp every time we use
  // that same index.  If they match, then we're probably decrypting the same
  // event and we don't consider it a replay attack.
  //
  // Keys are strings of form "<senderKey>|<session_id>|<message_index>"
  // Values are objects of the form "{id: <event id>, timestamp: <ts>}"

  this._inboundGroupSessionMessageIndexes = {}; // Keep track of sessions that we're starting, so that we don't start
  // multiple sessions for the same device at the same time.

  this._sessionsInProgress = {}; // Used by olm to serialise prekey message decryptions

  this._olmPrekeyPromise = Promise.resolve();
}
/**
 * Initialise the OlmAccount. This must be called before any other operations
 * on the OlmDevice.
 *
 * Data from an exported Olm device can be provided
 * in order to re-create this device.
 *
 * Attempts to load the OlmAccount from the crypto store, or creates one if none is
 * found.
 *
 * Reads the device keys from the OlmAccount object.
 *
 * @param {object} opts
 * @param {object} opts.fromExportedDevice (Optional) data from exported device
 *     that must be re-created.
 *     If present, opts.pickleKey is ignored
 *     (exported data already provides a pickle key)
 * @param {object} opts.pickleKey (Optional) pickle key to set instead of default one
 */


OlmDevice.prototype.init = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
  var opts,
      e2eKeys,
      account,
      pickleKey,
      fromExportedDevice,
      _args = arguments;
  return _regenerator["default"].wrap(function _callee$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
          account = new global.Olm.Account();
          pickleKey = opts.pickleKey, fromExportedDevice = opts.fromExportedDevice;
          _context.prev = 3;

          if (!fromExportedDevice) {
            _context.next = 11;
            break;
          }

          if (pickleKey) {
            _logger.logger.warn('ignoring opts.pickleKey' + ' because opts.fromExportedDevice is present.');
          }

          this._pickleKey = fromExportedDevice.pickleKey;
          _context.next = 9;
          return _initialiseFromExportedDevice(fromExportedDevice, this._cryptoStore, this._pickleKey, account);

        case 9:
          _context.next = 14;
          break;

        case 11:
          if (pickleKey) {
            this._pickleKey = pickleKey;
          }

          _context.next = 14;
          return _initialiseAccount(this._cryptoStore, this._pickleKey, account);

        case 14:
          e2eKeys = JSON.parse(account.identity_keys());
          this._maxOneTimeKeys = account.max_number_of_one_time_keys();

        case 16:
          _context.prev = 16;
          account.free();
          return _context.finish(16);

        case 19:
          this.deviceCurve25519Key = e2eKeys.curve25519;
          this.deviceEd25519Key = e2eKeys.ed25519;

        case 21:
        case "end":
          return _context.stop();
      }
    }
  }, _callee, this, [[3,, 16, 19]]);
}));
/**
 * Populates the crypto store using data that was exported from an existing device.
 * Note that for now only the “account” and “sessions” stores are populated;
 * Other stores will be as with a new device.
 *
 * @param {Object} exportedData Data exported from another device
 *     through the “export” method.
 * @param {module:crypto/store/base~CryptoStore} cryptoStore storage for the crypto layer
 * @param {string} pickleKey the key that was used to pickle the exported data
 * @param {Olm.Account} account an olm account to initialize
 */

function _initialiseFromExportedDevice(_x, _x2, _x3, _x4) {
  return _initialiseFromExportedDevice2.apply(this, arguments);
}

function _initialiseFromExportedDevice2() {
  _initialiseFromExportedDevice2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee25(exportedData, cryptoStore, pickleKey, account) {
    return _regenerator["default"].wrap(function _callee25$(_context25) {
      while (1) {
        switch (_context25.prev = _context25.next) {
          case 0:
            _context25.next = 2;
            return cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              cryptoStore.storeAccount(txn, exportedData.pickledAccount);
              exportedData.sessions.forEach(function (session) {
                var deviceKey = session.deviceKey,
                    sessionId = session.sessionId;
                var sessionInfo = {
                  session: session.session,
                  lastReceivedMessageTs: session.lastReceivedMessageTs
                };
                cryptoStore.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn);
              });
            });

          case 2:
            account.unpickle(pickleKey, exportedData.pickledAccount);

          case 3:
          case "end":
            return _context25.stop();
        }
      }
    }, _callee25);
  }));
  return _initialiseFromExportedDevice2.apply(this, arguments);
}

function _initialiseAccount(_x5, _x6, _x7) {
  return _initialiseAccount2.apply(this, arguments);
}
/**
 * @return {array} The version of Olm.
 */


function _initialiseAccount2() {
  _initialiseAccount2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee26(cryptoStore, pickleKey, account) {
    return _regenerator["default"].wrap(function _callee26$(_context26) {
      while (1) {
        switch (_context26.prev = _context26.next) {
          case 0:
            _context26.next = 2;
            return cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
              cryptoStore.getAccount(txn, function (pickledAccount) {
                if (pickledAccount !== null) {
                  account.unpickle(pickleKey, pickledAccount);
                } else {
                  account.create();
                  pickledAccount = account.pickle(pickleKey);
                  cryptoStore.storeAccount(txn, pickledAccount);
                }
              });
            });

          case 2:
          case "end":
            return _context26.stop();
        }
      }
    }, _callee26);
  }));
  return _initialiseAccount2.apply(this, arguments);
}

OlmDevice.getOlmVersion = function () {
  return global.Olm.get_library_version();
};
/**
 * extract our OlmAccount from the crypto store and call the given function
 * with the account object
 * The `account` object is useable only within the callback passed to this
 * function and will be freed as soon the callback returns. It is *not*
 * useable for the rest of the lifetime of the transaction.
 * This function requires a live transaction object from cryptoStore.doTxn()
 * and therefore may only be called in a doTxn() callback.
 *
 * @param {*} txn Opaque transaction object from cryptoStore.doTxn()
 * @param {function} func
 * @private
 */


OlmDevice.prototype._getAccount = function (txn, func) {
  var _this = this;

  this._cryptoStore.getAccount(txn, function (pickledAccount) {
    var account = new global.Olm.Account();

    try {
      account.unpickle(_this._pickleKey, pickledAccount);
      func(account);
    } finally {
      account.free();
    }
  });
};
/*
 * Saves an account to the crypto store.
 * This function requires a live transaction object from cryptoStore.doTxn()
 * and therefore may only be called in a doTxn() callback.
 *
 * @param {*} txn Opaque transaction object from cryptoStore.doTxn()
 * @param {object} Olm.Account object
 * @private
 */


OlmDevice.prototype._storeAccount = function (txn, account) {
  this._cryptoStore.storeAccount(txn, account.pickle(this._pickleKey));
};
/**
 * Export data for re-creating the Olm device later.
 * TODO export data other than just account and (P2P) sessions.
 *
 * @return {Promise<object>} The exported data
*/


OlmDevice.prototype["export"] = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
  var _this2 = this;

  var result;
  return _regenerator["default"].wrap(function _callee2$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          result = {
            pickleKey: this._pickleKey
          };
          _context2.next = 3;
          return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
            _this2._cryptoStore.getAccount(txn, function (pickledAccount) {
              result.pickledAccount = pickledAccount;
            });

            result.sessions = []; // Note that the pickledSession object we get in the callback
            // is not exactly the same thing you get in method _getSession
            // see documentation of IndexedDBCryptoStore.getAllEndToEndSessions

            _this2._cryptoStore.getAllEndToEndSessions(txn, function (pickledSession) {
              result.sessions.push(pickledSession);
            });
          });

        case 3:
          return _context2.abrupt("return", result);

        case 4:
        case "end":
          return _context2.stop();
      }
    }
  }, _callee2, this);
}));
/**
 * extract an OlmSession from the session store and call the given function
 * The session is useable only within the callback passed to this
 * function and will be freed as soon the callback returns. It is *not*
 * useable for the rest of the lifetime of the transaction.
 *
 * @param {string} deviceKey
 * @param {string} sessionId
 * @param {*} txn Opaque transaction object from cryptoStore.doTxn()
 * @param {function} func
 * @private
 */

OlmDevice.prototype._getSession = function (deviceKey, sessionId, txn, func) {
  var _this3 = this;

  this._cryptoStore.getEndToEndSession(deviceKey, sessionId, txn, function (sessionInfo) {
    _this3._unpickleSession(sessionInfo, func);
  });
};
/**
 * Creates a session object from a session pickle and executes the given
 * function with it. The session object is destroyed once the function
 * returns.
 *
 * @param {object} sessionInfo
 * @param {function} func
 * @private
 */


OlmDevice.prototype._unpickleSession = function (sessionInfo, func) {
  var session = new global.Olm.Session();

  try {
    session.unpickle(this._pickleKey, sessionInfo.session);
    var unpickledSessInfo = Object.assign({}, sessionInfo, {
      session: session
    });
    func(unpickledSessInfo);
  } finally {
    session.free();
  }
};
/**
 * store our OlmSession in the session store
 *
 * @param {string} deviceKey
 * @param {object} sessionInfo {session: OlmSession, lastReceivedMessageTs: int}
 * @param {*} txn Opaque transaction object from cryptoStore.doTxn()
 * @private
 */


OlmDevice.prototype._saveSession = function (deviceKey, sessionInfo, txn) {
  var sessionId = sessionInfo.session.session_id();
  var pickledSessionInfo = Object.assign(sessionInfo, {
    session: sessionInfo.session.pickle(this._pickleKey)
  });

  this._cryptoStore.storeEndToEndSession(deviceKey, sessionId, pickledSessionInfo, txn);
};
/**
 * get an OlmUtility and call the given function
 *
 * @param {function} func
 * @return {object} result of func
 * @private
 */


OlmDevice.prototype._getUtility = function (func) {
  var utility = new global.Olm.Utility();

  try {
    return func(utility);
  } finally {
    utility.free();
  }
};
/**
 * Signs a message with the ed25519 key for this account.
 *
 * @param {string} message  message to be signed
 * @return {Promise<string>} base64-encoded signature
 */


OlmDevice.prototype.sign = /*#__PURE__*/function () {
  var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(message) {
    var _this4 = this;

    var result;
    return _regenerator["default"].wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
              _this4._getAccount(txn, function (account) {
                result = account.sign(message);
              });
            });

          case 2:
            return _context3.abrupt("return", result);

          case 3:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, this);
  }));

  return function (_x8) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * Get the current (unused, unpublished) one-time keys for this account.
 *
 * @return {object} one time keys; an object with the single property
 * <tt>curve25519</tt>, which is itself an object mapping key id to Curve25519
 * key.
 */


OlmDevice.prototype.getOneTimeKeys = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
  var _this5 = this;

  var result;
  return _regenerator["default"].wrap(function _callee4$(_context4) {
    while (1) {
      switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 2;
          return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
            _this5._getAccount(txn, function (account) {
              result = JSON.parse(account.one_time_keys());
            });
          });

        case 2:
          return _context4.abrupt("return", result);

        case 3:
        case "end":
          return _context4.stop();
      }
    }
  }, _callee4, this);
}));
/**
 * Get the maximum number of one-time keys we can store.
 *
 * @return {number} number of keys
 */

OlmDevice.prototype.maxNumberOfOneTimeKeys = function () {
  return this._maxOneTimeKeys;
};
/**
 * Marks all of the one-time keys as published.
 */


OlmDevice.prototype.markKeysAsPublished = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
  var _this6 = this;

  return _regenerator["default"].wrap(function _callee5$(_context5) {
    while (1) {
      switch (_context5.prev = _context5.next) {
        case 0:
          _context5.next = 2;
          return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
            _this6._getAccount(txn, function (account) {
              account.mark_keys_as_published();

              _this6._storeAccount(txn, account);
            });
          });

        case 2:
        case "end":
          return _context5.stop();
      }
    }
  }, _callee5, this);
}));
/**
 * Generate some new one-time keys
 *
 * @param {number} numKeys number of keys to generate
 * @return {Promise} Resolved once the account is saved back having generated the keys
 */

OlmDevice.prototype.generateOneTimeKeys = function (numKeys) {
  var _this7 = this;

  return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
    _this7._getAccount(txn, function (account) {
      account.generate_one_time_keys(numKeys);

      _this7._storeAccount(txn, account);
    });
  });
};
/**
 * Generate a new fallback keys
 *
 * @return {Promise} Resolved once the account is saved back having generated the key
 */


OlmDevice.prototype.generateFallbackKey = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
  var _this8 = this;

  return _regenerator["default"].wrap(function _callee6$(_context6) {
    while (1) {
      switch (_context6.prev = _context6.next) {
        case 0:
          _context6.next = 2;
          return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
            _this8._getAccount(txn, function (account) {
              account.generate_fallback_key();

              _this8._storeAccount(txn, account);
            });
          });

        case 2:
        case "end":
          return _context6.stop();
      }
    }
  }, _callee6, this);
}));
OlmDevice.prototype.getFallbackKey = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() {
  var _this9 = this;

  var result;
  return _regenerator["default"].wrap(function _callee7$(_context7) {
    while (1) {
      switch (_context7.prev = _context7.next) {
        case 0:
          _context7.next = 2;
          return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) {
            _this9._getAccount(txn, function (account) {
              result = JSON.parse(account.fallback_key());
            });
          });

        case 2:
          return _context7.abrupt("return", result);

        case 3:
        case "end":
          return _context7.stop();
      }
    }
  }, _callee7, this);
}));
/**
 * Generate a new outbound session
 *
 * The new session will be stored in the cryptoStore.
 *
 * @param {string} theirIdentityKey remote user's Curve25519 identity key
 * @param {string} theirOneTimeKey  remote user's one-time Curve25519 key
 * @return {string} sessionId for the outbound session.
 */

OlmDevice.prototype.createOutboundSession = /*#__PURE__*/function () {
  var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(theirIdentityKey, theirOneTimeKey) {
    var _this10 = this;

    var newSessionId;
    return _regenerator["default"].wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.next = 2;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this10._getAccount(txn, function (account) {
                var session = new global.Olm.Session();

                try {
                  session.create_outbound(account, theirIdentityKey, theirOneTimeKey);
                  newSessionId = session.session_id();

                  _this10._storeAccount(txn, account);

                  var sessionInfo = {
                    session: session,
                    // Pretend we've received a message at this point, otherwise
                    // if we try to send a message to the device, it won't use
                    // this session
                    lastReceivedMessageTs: Date.now()
                  };

                  _this10._saveSession(theirIdentityKey, sessionInfo, txn);
                } finally {
                  session.free();
                }
              });
            }, _logger.logger.withPrefix("[createOutboundSession]"));

          case 2:
            return _context8.abrupt("return", newSessionId);

          case 3:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee8, this);
  }));

  return function (_x9, _x10) {
    return _ref8.apply(this, arguments);
  };
}();
/**
 * Generate a new inbound session, given an incoming message
 *
 * @param {string} theirDeviceIdentityKey remote user's Curve25519 identity key
 * @param {number} messageType  messageType field from the received message (must be 0)
 * @param {string} ciphertext base64-encoded body from the received message
 *
 * @return {{payload: string, session_id: string}} decrypted payload, and
 *     session id of new session
 *
 * @raises {Error} if the received message was not valid (for instance, it
 *     didn't use a valid one-time key).
 */


OlmDevice.prototype.createInboundSession = /*#__PURE__*/function () {
  var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(theirDeviceIdentityKey, messageType, ciphertext) {
    var _this11 = this;

    var result;
    return _regenerator["default"].wrap(function _callee9$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            if (!(messageType !== 0)) {
              _context9.next = 2;
              break;
            }

            throw new Error("Need messageType == 0 to create inbound session");

          case 2:
            _context9.next = 4;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this11._getAccount(txn, function (account) {
                var session = new global.Olm.Session();

                try {
                  session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);
                  account.remove_one_time_keys(session);

                  _this11._storeAccount(txn, account);

                  var payloadString = session.decrypt(messageType, ciphertext);
                  var sessionInfo = {
                    session: session,
                    // this counts as a received message: set last received message time
                    // to now
                    lastReceivedMessageTs: Date.now()
                  };

                  _this11._saveSession(theirDeviceIdentityKey, sessionInfo, txn);

                  result = {
                    payload: payloadString,
                    session_id: session.session_id()
                  };
                } finally {
                  session.free();
                }
              });
            }, _logger.logger.withPrefix("[createInboundSession]"));

          case 4:
            return _context9.abrupt("return", result);

          case 5:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee9, this);
  }));

  return function (_x11, _x12, _x13) {
    return _ref9.apply(this, arguments);
  };
}();
/**
 * Get a list of known session IDs for the given device
 *
 * @param {string} theirDeviceIdentityKey Curve25519 identity key for the
 *     remote device
 * @return {Promise<string[]>}  a list of known session ids for the device
 */


OlmDevice.prototype.getSessionIdsForDevice = /*#__PURE__*/function () {
  var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(theirDeviceIdentityKey) {
    var _this12 = this;

    var log, sessionIds;
    return _regenerator["default"].wrap(function _callee10$(_context10) {
      while (1) {
        switch (_context10.prev = _context10.next) {
          case 0:
            log = _logger.logger.withPrefix("[getSessionIdsForDevice]");

            if (!this._sessionsInProgress[theirDeviceIdentityKey]) {
              _context10.next = 10;
              break;
            }

            log.debug("Waiting for Olm session for ".concat(theirDeviceIdentityKey, " to be created"));
            _context10.prev = 3;
            _context10.next = 6;
            return this._sessionsInProgress[theirDeviceIdentityKey];

          case 6:
            _context10.next = 10;
            break;

          case 8:
            _context10.prev = 8;
            _context10.t0 = _context10["catch"](3);

          case 10:
            _context10.next = 12;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this12._cryptoStore.getEndToEndSessions(theirDeviceIdentityKey, txn, function (sessions) {
                sessionIds = Object.keys(sessions);
              });
            }, log);

          case 12:
            return _context10.abrupt("return", sessionIds);

          case 13:
          case "end":
            return _context10.stop();
        }
      }
    }, _callee10, this, [[3, 8]]);
  }));

  return function (_x14) {
    return _ref10.apply(this, arguments);
  };
}();
/**
 * Get the right olm session id for encrypting messages to the given identity key
 *
 * @param {string} theirDeviceIdentityKey Curve25519 identity key for the
 *     remote device
 * @param {boolean} nowait Don't wait for an in-progress session to complete.
 *     This should only be set to true of the calling function is the function
 *     that marked the session as being in-progress.
 * @param {Logger} [log] A possibly customised log
 * @return {Promise<?string>}  session id, or null if no established session
 */


OlmDevice.prototype.getSessionIdForDevice = /*#__PURE__*/function () {
  var _ref11 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(theirDeviceIdentityKey, nowait, log) {
    var sessionInfos, idxOfBest, i, thisSessInfo, thisLastReceived, bestSessInfo, bestLastReceived;
    return _regenerator["default"].wrap(function _callee11$(_context11) {
      while (1) {
        switch (_context11.prev = _context11.next) {
          case 0:
            _context11.next = 2;
            return this.getSessionInfoForDevice(theirDeviceIdentityKey, nowait, log);

          case 2:
            sessionInfos = _context11.sent;

            if (!(sessionInfos.length === 0)) {
              _context11.next = 5;
              break;
            }

            return _context11.abrupt("return", null);

          case 5:
            // Use the session that has most recently received a message
            idxOfBest = 0;

            for (i = 1; i < sessionInfos.length; i++) {
              thisSessInfo = sessionInfos[i];
              thisLastReceived = thisSessInfo.lastReceivedMessageTs === undefined ? 0 : thisSessInfo.lastReceivedMessageTs;
              bestSessInfo = sessionInfos[idxOfBest];
              bestLastReceived = bestSessInfo.lastReceivedMessageTs === undefined ? 0 : bestSessInfo.lastReceivedMessageTs;

              if (thisLastReceived > bestLastReceived || thisLastReceived === bestLastReceived && thisSessInfo.sessionId < bestSessInfo.sessionId) {
                idxOfBest = i;
              }
            }

            return _context11.abrupt("return", sessionInfos[idxOfBest].sessionId);

          case 8:
          case "end":
            return _context11.stop();
        }
      }
    }, _callee11, this);
  }));

  return function (_x15, _x16, _x17) {
    return _ref11.apply(this, arguments);
  };
}();
/**
 * Get information on the active Olm sessions for a device.
 * <p>
 * Returns an array, with an entry for each active session. The first entry in
 * the result will be the one used for outgoing messages. Each entry contains
 * the keys 'hasReceivedMessage' (true if the session has received an incoming
 * message and is therefore past the pre-key stage), and 'sessionId'.
 *
 * @param {string} deviceIdentityKey Curve25519 identity key for the device
 * @param {boolean} nowait Don't wait for an in-progress session to complete.
 *     This should only be set to true of the calling function is the function
 *     that marked the session as being in-progress.
 * @param {Logger} [log] A possibly customised log
 * @return {Array.<{sessionId: string, hasReceivedMessage: Boolean}>}
 */


OlmDevice.prototype.getSessionInfoForDevice = /*#__PURE__*/function () {
  var _ref12 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(deviceIdentityKey, nowait) {
    var _this13 = this;

    var log,
        info,
        _args12 = arguments;
    return _regenerator["default"].wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            log = _args12.length > 2 && _args12[2] !== undefined ? _args12[2] : _logger.logger;
            log = log.withPrefix("[getSessionInfoForDevice]");

            if (!(this._sessionsInProgress[deviceIdentityKey] && !nowait)) {
              _context12.next = 11;
              break;
            }

            log.debug("Waiting for Olm session for ".concat(deviceIdentityKey, " to be created"));
            _context12.prev = 4;
            _context12.next = 7;
            return this._sessionsInProgress[deviceIdentityKey];

          case 7:
            _context12.next = 11;
            break;

          case 9:
            _context12.prev = 9;
            _context12.t0 = _context12["catch"](4);

          case 11:
            info = [];
            _context12.next = 14;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this13._cryptoStore.getEndToEndSessions(deviceIdentityKey, txn, function (sessions) {
                var sessionIds = Object.keys(sessions).sort();

                var _iterator = _createForOfIteratorHelper(sessionIds),
                    _step;

                try {
                  var _loop = function _loop() {
                    var sessionId = _step.value;

                    _this13._unpickleSession(sessions[sessionId], function (sessInfo) {
                      info.push({
                        lastReceivedMessageTs: sessInfo.lastReceivedMessageTs,
                        hasReceivedMessage: sessInfo.session.has_received_message(),
                        sessionId: sessionId
                      });
                    });
                  };

                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    _loop();
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }
              });
            }, log);

          case 14:
            return _context12.abrupt("return", info);

          case 15:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee12, this, [[4, 9]]);
  }));

  return function (_x18, _x19) {
    return _ref12.apply(this, arguments);
  };
}();
/**
 * Encrypt an outgoing message using an existing session
 *
 * @param {string} theirDeviceIdentityKey Curve25519 identity key for the
 *     remote device
 * @param {string} sessionId  the id of the active session
 * @param {string} payloadString  payload to be encrypted and sent
 *
 * @return {Promise<string>} ciphertext
 */


OlmDevice.prototype.encryptMessage = /*#__PURE__*/function () {
  var _ref13 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(theirDeviceIdentityKey, sessionId, payloadString) {
    var _this14 = this;

    var res;
    return _regenerator["default"].wrap(function _callee13$(_context13) {
      while (1) {
        switch (_context13.prev = _context13.next) {
          case 0:
            checkPayloadLength(payloadString);
            _context13.next = 3;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this14._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) {
                var sessionDesc = sessionInfo.session.describe();

                _logger.logger.log("encryptMessage: Olm Session ID " + sessionId + " to " + theirDeviceIdentityKey + ": " + sessionDesc);

                res = sessionInfo.session.encrypt(payloadString);

                _this14._saveSession(theirDeviceIdentityKey, sessionInfo, txn);
              });
            }, _logger.logger.withPrefix("[encryptMessage]"));

          case 3:
            return _context13.abrupt("return", res);

          case 4:
          case "end":
            return _context13.stop();
        }
      }
    }, _callee13, this);
  }));

  return function (_x20, _x21, _x22) {
    return _ref13.apply(this, arguments);
  };
}();
/**
 * Decrypt an incoming message using an existing session
 *
 * @param {string} theirDeviceIdentityKey Curve25519 identity key for the
 *     remote device
 * @param {string} sessionId  the id of the active session
 * @param {number} messageType  messageType field from the received message
 * @param {string} ciphertext base64-encoded body from the received message
 *
 * @return {Promise<string>} decrypted payload.
 */


OlmDevice.prototype.decryptMessage = /*#__PURE__*/function () {
  var _ref14 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(theirDeviceIdentityKey, sessionId, messageType, ciphertext) {
    var _this15 = this;

    var payloadString;
    return _regenerator["default"].wrap(function _callee14$(_context14) {
      while (1) {
        switch (_context14.prev = _context14.next) {
          case 0:
            _context14.next = 2;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this15._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) {
                var sessionDesc = sessionInfo.session.describe();

                _logger.logger.log("decryptMessage: Olm Session ID " + sessionId + " from " + theirDeviceIdentityKey + ": " + sessionDesc);

                payloadString = sessionInfo.session.decrypt(messageType, ciphertext);
                sessionInfo.lastReceivedMessageTs = Date.now();

                _this15._saveSession(theirDeviceIdentityKey, sessionInfo, txn);
              });
            }, _logger.logger.withPrefix("[decryptMessage]"));

          case 2:
            return _context14.abrupt("return", payloadString);

          case 3:
          case "end":
            return _context14.stop();
        }
      }
    }, _callee14, this);
  }));

  return function (_x23, _x24, _x25, _x26) {
    return _ref14.apply(this, arguments);
  };
}();
/**
 * Determine if an incoming messages is a prekey message matching an existing session
 *
 * @param {string} theirDeviceIdentityKey Curve25519 identity key for the
 *     remote device
 * @param {string} sessionId  the id of the active session
 * @param {number} messageType  messageType field from the received message
 * @param {string} ciphertext base64-encoded body from the received message
 *
 * @return {Promise<boolean>} true if the received message is a prekey message which matches
 *    the given session.
 */


OlmDevice.prototype.matchesSession = /*#__PURE__*/function () {
  var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(theirDeviceIdentityKey, sessionId, messageType, ciphertext) {
    var _this16 = this;

    var matches;
    return _regenerator["default"].wrap(function _callee15$(_context15) {
      while (1) {
        switch (_context15.prev = _context15.next) {
          case 0:
            if (!(messageType !== 0)) {
              _context15.next = 2;
              break;
            }

            return _context15.abrupt("return", false);

          case 2:
            _context15.next = 4;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) {
              _this16._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) {
                matches = sessionInfo.session.matches_inbound(ciphertext);
              });
            }, _logger.logger.withPrefix("[matchesSession]"));

          case 4:
            return _context15.abrupt("return", matches);

          case 5:
          case "end":
            return _context15.stop();
        }
      }
    }, _callee15, this);
  }));

  return function (_x27, _x28, _x29, _x30) {
    return _ref15.apply(this, arguments);
  };
}();

OlmDevice.prototype.recordSessionProblem = /*#__PURE__*/function () {
  var _ref16 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(deviceKey, type, fixed) {
    return _regenerator["default"].wrap(function _callee16$(_context16) {
      while (1) {
        switch (_context16.prev = _context16.next) {
          case 0:
            _context16.next = 2;
            return this._cryptoStore.storeEndToEndSessionProblem(deviceKey, type, fixed);

          case 2:
          case "end":
            return _context16.stop();
        }
      }
    }, _callee16, this);
  }));

  return function (_x31, _x32, _x33) {
    return _ref16.apply(this, arguments);
  };
}();

OlmDevice.prototype.sessionMayHaveProblems = /*#__PURE__*/function () {
  var _ref17 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(deviceKey, timestamp) {
    return _regenerator["default"].wrap(function _callee17$(_context17) {
      while (1) {
        switch (_context17.prev = _context17.next) {
          case 0:
            _context17.next = 2;
            return this._cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp);

          case 2:
            return _context17.abrupt("return", _context17.sent);

          case 3:
          case "end":
            return _context17.stop();
        }
      }
    }, _callee17, this);
  }));

  return function (_x34, _x35) {
    return _ref17.apply(this, arguments);
  };
}();

OlmDevice.prototype.filterOutNotifiedErrorDevices = /*#__PURE__*/function () {
  var _ref18 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(devices) {
    return _regenerator["default"].wrap(function _callee18$(_context18) {
      while (1) {
        switch (_context18.prev = _context18.next) {
          case 0:
            _context18.next = 2;
            return this._cryptoStore.filterOutNotifiedErrorDevices(devices);

          case 2:
            return _context18.abrupt("return", _context18.sent);

          case 3:
          case "end":
            return _context18.stop();
        }
      }
    }, _callee18, this);
  }));

  return function (_x36) {
    return _ref18.apply(this, arguments);
  };
}(); // Outbound group session
// ======================

/**
 * store an OutboundGroupSession in _outboundGroupSessionStore
 *
 * @param {Olm.OutboundGroupSession} session
 * @private
 */


OlmDevice.prototype._saveOutboundGroupSession = function (session) {
  var pickledSession = session.pickle(this._pickleKey);
  this._outboundGroupSessionStore[session.session_id()] = pickledSession;
};
/**
 * extract an OutboundGroupSession from _outboundGroupSessionStore and call the
 * given function
 *
 * @param {string} sessionId
 * @param {function} func
 * @return {object} result of func
 * @private
 */


OlmDevice.prototype._getOutboundGroupSession = function (sessionId, func) {
  var pickled = this._outboundGroupSessionStore[sessionId];

  if (pickled === undefined) {
    throw new Error("Unknown outbound group session " + sessionId);
  }

  var session = new global.Olm.OutboundGroupSession();

  try {
    session.unpickle(this._pickleKey, pickled);
    return func(session);
  } finally {
    session.free();
  }
};
/**
 * Generate a new outbound group session
 *
 * @return {string} sessionId for the outbound session.
 */


OlmDevice.prototype.createOutboundGroupSession = function () {
  var session = new global.Olm.OutboundGroupSession();

  try {
    session.create();

    this._saveOutboundGroupSession(session);

    return session.session_id();
  } finally {
    session.free();
  }
};
/**
 * Encrypt an outgoing message with an outbound group session
 *
 * @param {string} sessionId  the id of the outboundgroupsession
 * @param {string} payloadString  payload to be encrypted and sent
 *
 * @return {string} ciphertext
 */


OlmDevice.prototype.encryptGroupMessage = function (sessionId, payloadString) {
  var self = this;

  _logger.logger.log("encrypting msg with megolm session ".concat(sessionId));

  checkPayloadLength(payloadString);
  return this._getOutboundGroupSession(sessionId, function (session) {
    var res = session.encrypt(payloadString);

    self._saveOutboundGroupSession(session);

    return res;
  });
};
/**
 * Get the session keys for an outbound group session
 *
 * @param {string} sessionId  the id of the outbound group session
 *
 * @return {{chain_index: number, key: string}} current chain index, and
 *     base64-encoded secret key.
 */


OlmDevice.prototype.getOutboundGroupSessionKey = function (sessionId) {
  return this._getOutboundGroupSession(sessionId, function (session) {
    return {
      chain_index: session.message_index(),
      key: session.session_key()
    };
  });
}; // Inbound group session
// =====================

/**
 * data stored in the session store about an inbound group session
 *
 * @typedef {Object} InboundGroupSessionData
 * @property {string} room_Id
 * @property {string} session   pickled Olm.InboundGroupSession
 * @property {Object<string, string>} keysClaimed
 * @property {Array<string>} forwardingCurve25519KeyChain  Devices involved in forwarding
 *     this session to us (normally empty).
 */

/**
 * Unpickle a session from a sessionData object and invoke the given function.
 * The session is valid only until func returns.
 *
 * @param {Object} sessionData Object describing the session.
 * @param {function(Olm.InboundGroupSession)} func Invoked with the unpickled session
 * @return {*} result of func
 */


OlmDevice.prototype._unpickleInboundGroupSession = function (sessionData, func) {
  var session = new global.Olm.InboundGroupSession();

  try {
    session.unpickle(this._pickleKey, sessionData.session);
    return func(session);
  } finally {
    session.free();
  }
};
/**
 * extract an InboundGroupSession from the crypto store and call the given function
 *
 * @param {string} roomId The room ID to extract the session for, or null to fetch
 *     sessions for any room.
 * @param {string} senderKey
 * @param {string} sessionId
 * @param {*} txn Opaque transaction object from cryptoStore.doTxn()
 * @param {function(Olm.InboundGroupSession, InboundGroupSessionData)} func
 *   function to call.
 *
 * @private
 */


OlmDevice.prototype._getInboundGroupSession = function (roomId, senderKey, sessionId, txn, func) {
  var _this17 = this;

  this._cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, function (sessionData, withheld) {
    if (sessionData === null) {
      func(null, null, withheld);
      return;
    } // if we were given a room ID, check that the it matches the original one for the session. This stops
    // the HS pretending a message was targeting a different room.


    if (roomId !== null && roomId !== sessionData.room_id) {
      throw new Error("Mismatched room_id for inbound group session (expected " + sessionData.room_id + ", was " + roomId + ")");
    }

    _this17._unpickleInboundGroupSession(sessionData, function (session) {
      func(session, sessionData, withheld);
    });
  });
};
/**
 * Add an inbound group session to the session store
 *
 * @param {string} roomId     room in which this session will be used
 * @param {string} senderKey  base64-encoded curve25519 key of the sender
 * @param {Array<string>} forwardingCurve25519KeyChain  Devices involved in forwarding
 *     this session to us.
 * @param {string} sessionId  session identifier
 * @param {string} sessionKey base64-encoded secret key
 * @param {Object<string, string>} keysClaimed Other keys the sender claims.
 * @param {boolean} exportFormat true if the megolm keys are in export format
 *    (ie, they lack an ed25519 signature)
 * @param {Object} [extraSessionData={}] any other data to be include with the session
 */


OlmDevice.prototype.addInboundGroupSession = /*#__PURE__*/function () {
  var _ref19 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(roomId, senderKey, forwardingCurve25519KeyChain, sessionId, sessionKey, keysClaimed, exportFormat) {
    var _this18 = this;

    var extraSessionData,
        _args19 = arguments;
    return _regenerator["default"].wrap(function _callee19$(_context19) {
      while (1) {
        switch (_context19.prev = _context19.next) {
          case 0:
            extraSessionData = _args19.length > 7 && _args19[7] !== undefined ? _args19[7] : {};
            _context19.next = 3;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS], function (txn) {
              /* if we already have this session, consider updating it */
              _this18._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (existingSession, existingSessionData) {
                // new session.
                var session = new global.Olm.InboundGroupSession();

                try {
                  if (exportFormat) {
                    session.import_session(sessionKey);
                  } else {
                    session.create(sessionKey);
                  }

                  if (sessionId != session.session_id()) {
                    throw new Error("Mismatched group session ID from senderKey: " + senderKey);
                  }

                  if (existingSession) {
                    _logger.logger.log("Update for megolm session " + senderKey + "/" + sessionId);

                    if (existingSession.first_known_index() <= session.first_known_index() && !(existingSession.first_known_index() == session.first_known_index() && !extraSessionData.untrusted && existingSessionData.untrusted)) {
                      // existing session has lower index (i.e. can
                      // decrypt more), or they have the same index and
                      // the new sessions trust does not win over the old
                      // sessions trust, so keep it
                      _logger.logger.log("Keeping existing megolm session ".concat(sessionId));

                      return;
                    }
                  }

                  _logger.logger.info("Storing megolm session " + senderKey + "/" + sessionId + " with first index " + session.first_known_index());

                  var sessionData = Object.assign({}, extraSessionData, {
                    room_id: roomId,
                    session: session.pickle(_this18._pickleKey),
                    keysClaimed: keysClaimed,
                    forwardingCurve25519KeyChain: forwardingCurve25519KeyChain
                  });

                  _this18._cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn);

                  if (!existingSession && extraSessionData.sharedHistory) {
                    _this18._cryptoStore.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn);
                  }
                } finally {
                  session.free();
                }
              });
            }, _logger.logger.withPrefix("[addInboundGroupSession]"));

          case 3:
          case "end":
            return _context19.stop();
        }
      }
    }, _callee19, this);
  }));

  return function (_x37, _x38, _x39, _x40, _x41, _x42, _x43) {
    return _ref19.apply(this, arguments);
  };
}();
/**
 * Record in the data store why an inbound group session was withheld.
 *
 * @param {string} roomId     room that the session belongs to
 * @param {string} senderKey  base64-encoded curve25519 key of the sender
 * @param {string} sessionId  session identifier
 * @param {string} code       reason code
 * @param {string} reason     human-readable version of `code`
 */


OlmDevice.prototype.addInboundGroupSessionWithheld = /*#__PURE__*/function () {
  var _ref20 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(roomId, senderKey, sessionId, code, reason) {
    var _this19 = this;

    return _regenerator["default"].wrap(function _callee20$(_context20) {
      while (1) {
        switch (_context20.prev = _context20.next) {
          case 0:
            _context20.next = 2;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) {
              _this19._cryptoStore.storeEndToEndInboundGroupSessionWithheld(senderKey, sessionId, {
                room_id: roomId,
                code: code,
                reason: reason
              }, txn);
            });

          case 2:
          case "end":
            return _context20.stop();
        }
      }
    }, _callee20, this);
  }));

  return function (_x44, _x45, _x46, _x47, _x48) {
    return _ref20.apply(this, arguments);
  };
}();

var WITHHELD_MESSAGES = {
  "m.unverified": "The sender has disabled encrypting to unverified devices.",
  "m.blacklisted": "The sender has blocked you.",
  "m.unauthorised": "You are not authorised to read the message.",
  "m.no_olm": "Unable to establish a secure channel."
};
/**
 * Calculate the message to use for the exception when a session key is withheld.
 *
 * @param {object} withheld  An object that describes why the key was withheld.
 *
 * @return {string} the message
 *
 * @private
 */

exports.WITHHELD_MESSAGES = WITHHELD_MESSAGES;

function _calculateWithheldMessage(withheld) {
  if (withheld.code && withheld.code in WITHHELD_MESSAGES) {
    return WITHHELD_MESSAGES[withheld.code];
  } else if (withheld.reason) {
    return withheld.reason;
  } else {
    return "decryption key withheld";
  }
}
/**
 * Decrypt a received message with an inbound group session
 *
 * @param {string} roomId    room in which the message was received
 * @param {string} senderKey base64-encoded curve25519 key of the sender
 * @param {string} sessionId session identifier
 * @param {string} body      base64-encoded body of the encrypted message
 * @param {string} eventId   ID of the event being decrypted
 * @param {Number} timestamp timestamp of the event being decrypted
 *
 * @return {null} the sessionId is unknown
 *
 * @return {Promise<{result: string, senderKey: string,
 *    forwardingCurve25519KeyChain: Array<string>,
 *    keysClaimed: Object<string, string>}>}
 */


OlmDevice.prototype.decryptGroupMessage = /*#__PURE__*/function () {
  var _ref21 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(roomId, senderKey, sessionId, body, eventId, timestamp) {
    var _this20 = this;

    var result, error;
    return _regenerator["default"].wrap(function _callee21$(_context21) {
      while (1) {
        switch (_context21.prev = _context21.next) {
          case 0:
            _context21.next = 2;
            return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) {
              _this20._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (session, sessionData, withheld) {
                if (session === null) {
                  if (withheld) {
                    error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", _calculateWithheldMessage(withheld), {
                      session: senderKey + '|' + sessionId
                    });
                  }

                  result = null;
                  return;
                }

                var res;

                try {
                  res = session.decrypt(body);
                } catch (e) {
                  if (e && e.message === 'OLM.UNKNOWN_MESSAGE_INDEX' && withheld) {
                    error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", _calculateWithheldMessage(withheld), {
                      session: senderKey + '|' + sessionId
                    });
                  } else {
                    error = e;
                  }

                  return;
                }

                var plaintext = res.plaintext;

                if (plaintext === undefined) {
                  // Compatibility for older olm versions.
                  plaintext = res;
                } else {
                  // Check if we have seen this message index before to detect replay attacks.
                  // If the event ID and timestamp are specified, and the match the event ID
                  // and timestamp from the last time we used this message index, then we
                  // don't consider it a replay attack.
                  var messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index;

                  if (messageIndexKey in _this20._inboundGroupSessionMessageIndexes) {
                    var msgInfo = _this20._inboundGroupSessionMessageIndexes[messageIndexKey];

                    if (msgInfo.id !== eventId || msgInfo.timestamp !== timestamp) {
                      error = new Error("Duplicate message index, possible replay attack: " + messageIndexKey);
                      return;
                    }
                  }

                  _this20._inboundGroupSessionMessageIndexes[messageIndexKey] = {
                    id: eventId,
                    timestamp: timestamp
                  };
                }

                sessionData.session = session.pickle(_this20._pickleKey);

                _this20._cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn);

                result = {
                  result: plaintext,
                  keysClaimed: sessionData.keysClaimed || {},
                  senderKey: senderKey,
                  forwardingCurve25519KeyChain: sessionData.forwardingCurve25519KeyChain || [],
                  untrusted: sessionData.untrusted
                };
              });
            }, _logger.logger.withPrefix("[decryptGroupMessage]"));

          case 2:
            if (!error) {
              _context21.next = 4;
              break;
            }

            throw error;

          case 4:
            return _context21.abrupt("return", result);

          case 5:
          case "end":
            return _context21.stop();
        }
      }
    }, _callee21, this);
  }));

  return function (_x49, _x50, _x51, _x52, _x53, _x54) {
    return _ref21.apply(this, arguments);
  };
}();
/**
 * Determine if we have the keys for a given megolm session
 *
 * @param {string} roomId    room in which the message was received
 * @param {string} senderKey base64-encoded curve25519 key of the sender
 * @param {string} sessionId session identifier
 *
 * @returns {Promise<boolean>} true if we have the keys to this session
 */


OlmDevice.prototype.hasInboundSessionKeys = /*#__PURE__*/function () {
  var _ref22 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(roomId, senderKey, sessionId) {
    var _this21 = this;

    var result;
    return _regenerator["default"].wrap(function _callee22$(_context22) {
      while (1) {
        switch (_context22.prev = _context22.next) {
          case 0:
            _context22.next = 2;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) {
              _this21._cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, function (sessionData) {
                if (sessionData === null) {
                  result = false;
                  return;
                }

                if (roomId !== sessionData.room_id) {
                  _logger.logger.warn("requested keys for inbound group session ".concat(senderKey, "|") + "".concat(sessionId, ", with incorrect room_id ") + "(expected ".concat(sessionData.room_id, ", ") + "was ".concat(roomId, ")"));

                  result = false;
                } else {
                  result = true;
                }
              });
            }, _logger.logger.withPrefix("[hasInboundSessionKeys]"));

          case 2:
            return _context22.abrupt("return", result);

          case 3:
          case "end":
            return _context22.stop();
        }
      }
    }, _callee22, this);
  }));

  return function (_x55, _x56, _x57) {
    return _ref22.apply(this, arguments);
  };
}();
/**
 * Extract the keys to a given megolm session, for sharing
 *
 * @param {string} roomId    room in which the message was received
 * @param {string} senderKey base64-encoded curve25519 key of the sender
 * @param {string} sessionId session identifier
 * @param {integer} chainIndex The chain index at which to export the session.
 *     If omitted, export at the first index we know about.
 *
 * @returns {Promise<{chain_index: number, key: string,
 *        forwarding_curve25519_key_chain: Array<string>,
 *        sender_claimed_ed25519_key: string
 *    }>}
 *    details of the session key. The key is a base64-encoded megolm key in
 *    export format.
 *
 * @throws Error If the given chain index could not be obtained from the known
 *     index (ie. the given chain index is before the first we have).
 */


OlmDevice.prototype.getInboundGroupSessionKey = /*#__PURE__*/function () {
  var _ref23 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(roomId, senderKey, sessionId, chainIndex) {
    var _this22 = this;

    var result;
    return _regenerator["default"].wrap(function _callee23$(_context23) {
      while (1) {
        switch (_context23.prev = _context23.next) {
          case 0:
            _context23.next = 2;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) {
              _this22._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (session, sessionData) {
                if (session === null) {
                  result = null;
                  return;
                }

                if (chainIndex === undefined) {
                  chainIndex = session.first_known_index();
                }

                var exportedSession = session.export_session(chainIndex);
                var claimedKeys = sessionData.keysClaimed || {};
                var senderEd25519Key = claimedKeys.ed25519 || null;
                result = {
                  "chain_index": chainIndex,
                  "key": exportedSession,
                  "forwarding_curve25519_key_chain": sessionData.forwardingCurve25519KeyChain || [],
                  "sender_claimed_ed25519_key": senderEd25519Key,
                  "shared_history": sessionData.sharedHistory || false
                };
              });
            }, _logger.logger.withPrefix("[getInboundGroupSessionKey]"));

          case 2:
            return _context23.abrupt("return", result);

          case 3:
          case "end":
            return _context23.stop();
        }
      }
    }, _callee23, this);
  }));

  return function (_x58, _x59, _x60, _x61) {
    return _ref23.apply(this, arguments);
  };
}();
/**
 * Export an inbound group session
 *
 * @param {string} senderKey base64-encoded curve25519 key of the sender
 * @param {string} sessionId session identifier
 * @param {string} sessionData The session object from the store
 * @return {module:crypto/OlmDevice.MegolmSessionData} exported session data
 */


OlmDevice.prototype.exportInboundGroupSession = function (senderKey, sessionId, sessionData) {
  return this._unpickleInboundGroupSession(sessionData, function (session) {
    var messageIndex = session.first_known_index();
    return {
      "sender_key": senderKey,
      "sender_claimed_keys": sessionData.keysClaimed,
      "room_id": sessionData.room_id,
      "session_id": sessionId,
      "session_key": session.export_session(messageIndex),
      "forwarding_curve25519_key_chain": session.forwardingCurve25519KeyChain || [],
      "first_known_index": session.first_known_index(),
      "org.matrix.msc3061.shared_history": sessionData.sharedHistory || false
    };
  });
};

OlmDevice.prototype.getSharedHistoryInboundGroupSessions = /*#__PURE__*/function () {
  var _ref24 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(roomId) {
    var _this23 = this;

    var result;
    return _regenerator["default"].wrap(function _callee24$(_context24) {
      while (1) {
        switch (_context24.prev = _context24.next) {
          case 0:
            _context24.next = 2;
            return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS], function (txn) {
              result = _this23._cryptoStore.getSharedHistoryInboundGroupSessions(roomId, txn);
            }, _logger.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]"));

          case 2:
            return _context24.abrupt("return", result);

          case 3:
          case "end":
            return _context24.stop();
        }
      }
    }, _callee24, this);
  }));

  return function (_x62) {
    return _ref24.apply(this, arguments);
  };
}(); // Utilities
// =========

/**
 * Verify an ed25519 signature.
 *
 * @param {string} key ed25519 key
 * @param {string} message message which was signed
 * @param {string} signature base64-encoded signature to be checked
 *
 * @raises {Error} if there is a problem with the verification. If the key was
 * too small then the message will be "OLM.INVALID_BASE64". If the signature
 * was invalid then the message will be "OLM.BAD_MESSAGE_MAC".
 */


OlmDevice.prototype.verifySignature = function (key, message, signature) {
  this._getUtility(function (util) {
    util.ed25519_verify(key, message, signature);
  });
};

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../logger":106,"./algorithms":76,"./store/indexeddb-crypto-store":88,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],71:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2017 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutgoingRoomKeyRequestManager = exports.RoomKeyRequestState = void 0;
const logger_1 = require("../logger");
const event_1 = require("../@types/event");
/**
 * Internal module. Management of outgoing room key requests.
 *
 * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ
 * for draft documentation on what we're supposed to be implementing here.
 *
 * @module
 */
// delay between deciding we want some keys, and sending out the request, to
// allow for (a) it turning up anyway, (b) grouping requests together
const SEND_KEY_REQUESTS_DELAY_MS = 500;
/** possible states for a room key request
 *
 * The state machine looks like:
 *
 *     |         (cancellation sent)
 *     | .-------------------------------------------------.
 *     | |                                                 |
 *     V V       (cancellation requested)                  |
 *   UNSENT  -----------------------------+                |
 *     |                                  |                |
 *     |                                  |                |
 *     | (send successful)                |  CANCELLATION_PENDING_AND_WILL_RESEND
 *     V                                  |                Λ
 *    SENT                                |                |
 *     |--------------------------------  |  --------------'
 *     |                                  |  (cancellation requested with intent
 *     |                                  |   to resend the original request)
 *     |                                  |
 *     | (cancellation requested)         |
 *     V                                  |
 * CANCELLATION_PENDING                   |
 *     |                                  |
 *     | (cancellation sent)              |
 *     V                                  |
 * (deleted)  <---------------------------+
 *
 * @enum {number}
 */
var RoomKeyRequestState;
(function (RoomKeyRequestState) {
    /** request not yet sent */
    RoomKeyRequestState[RoomKeyRequestState["Unsent"] = 0] = "Unsent";
    /** request sent, awaiting reply */
    RoomKeyRequestState[RoomKeyRequestState["Sent"] = 1] = "Sent";
    /** reply received, cancellation not yet sent */
    RoomKeyRequestState[RoomKeyRequestState["CancellationPending"] = 2] = "CancellationPending";
    /**
     * Cancellation not yet sent and will transition to UNSENT instead of
     * being deleted once the cancellation has been sent.
     */
    RoomKeyRequestState[RoomKeyRequestState["CancellationPendingAndWillResend"] = 3] = "CancellationPendingAndWillResend";
})(RoomKeyRequestState = exports.RoomKeyRequestState || (exports.RoomKeyRequestState = {}));
class OutgoingRoomKeyRequestManager {
    constructor(baseApis, deviceId, cryptoStore) {
        this.baseApis = baseApis;
        this.deviceId = deviceId;
        this.cryptoStore = cryptoStore;
        // handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null
        // if the callback has been set, or if it is still running.
        this.sendOutgoingRoomKeyRequestsTimer = null;
        // sanity check to ensure that we don't end up with two concurrent runs
        // of sendOutgoingRoomKeyRequests
        this.sendOutgoingRoomKeyRequestsRunning = false;
        this.clientRunning = false;
    }
    /**
     * Called when the client is started. Sets background processes running.
     */
    start() {
        this.clientRunning = true;
    }
    /**
     * Called when the client is stopped. Stops any running background processes.
     */
    stop() {
        logger_1.logger.log('stopping OutgoingRoomKeyRequestManager');
        // stop the timer on the next run
        this.clientRunning = false;
    }
    /**
     * Send any requests that have been queued
     */
    sendQueuedRequests() {
        this.startTimer();
    }
    /**
     * Queue up a room key request, if we haven't already queued or sent one.
     *
     * The `requestBody` is compared (with a deep-equality check) against
     * previous queued or sent requests and if it matches, no change is made.
     * Otherwise, a request is added to the pending list, and a job is started
     * in the background to send it.
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     * @param {Array<{userId: string, deviceId: string}>} recipients
     * @param {boolean} resend whether to resend the key request if there is
     *    already one
     *
     * @returns {Promise} resolves when the request has been added to the
     *    pending list (or we have established that a similar request already
     *    exists)
     */
    queueRoomKeyRequest(requestBody, recipients, resend = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const req = yield this.cryptoStore.getOutgoingRoomKeyRequest(requestBody);
            if (!req) {
                yield this.cryptoStore.getOrAddOutgoingRoomKeyRequest({
                    requestBody: requestBody,
                    recipients: recipients,
                    requestId: this.baseApis.makeTxnId(),
                    state: RoomKeyRequestState.Unsent,
                });
            }
            else {
                switch (req.state) {
                    case RoomKeyRequestState.CancellationPendingAndWillResend:
                    case RoomKeyRequestState.Unsent:
                        // nothing to do here, since we're going to send a request anyways
                        return;
                    case RoomKeyRequestState.CancellationPending: {
                        // existing request is about to be cancelled.  If we want to
                        // resend, then change the state so that it resends after
                        // cancelling.  Otherwise, just cancel the cancellation.
                        const state = resend ?
                            RoomKeyRequestState.CancellationPendingAndWillResend :
                            RoomKeyRequestState.Sent;
                        yield this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPending, {
                            state,
                            cancellationTxnId: this.baseApis.makeTxnId(),
                        });
                        break;
                    }
                    case RoomKeyRequestState.Sent: {
                        // a request has already been sent.  If we don't want to
                        // resend, then do nothing.  If we do want to, then cancel the
                        // existing request and send a new one.
                        if (resend) {
                            const state = RoomKeyRequestState.CancellationPendingAndWillResend;
                            const updatedReq = yield this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Sent, {
                                state,
                                cancellationTxnId: this.baseApis.makeTxnId(),
                                // need to use a new transaction ID so that
                                // the request gets sent
                                requestTxnId: this.baseApis.makeTxnId(),
                            });
                            if (!updatedReq) {
                                // updateOutgoingRoomKeyRequest couldn't find the request
                                // in state ROOM_KEY_REQUEST_STATES.SENT, so we must have
                                // raced with another tab to mark the request cancelled.
                                // Try again, to make sure the request is resent.
                                return yield this.queueRoomKeyRequest(requestBody, recipients, resend);
                            }
                            // We don't want to wait for the timer, so we send it
                            // immediately. (We might actually end up racing with the timer,
                            // but that's ok: even if we make the request twice, we'll do it
                            // with the same transaction_id, so only one message will get
                            // sent).
                            //
                            // (We also don't want to wait for the response from the server
                            // here, as it will slow down processing of received keys if we
                            // do.)
                            try {
                                yield this.sendOutgoingRoomKeyRequestCancellation(updatedReq, true);
                            }
                            catch (e) {
                                logger_1.logger.error("Error sending room key request cancellation;"
                                    + " will retry later.", e);
                            }
                            // The request has transitioned from
                            // CANCELLATION_PENDING_AND_WILL_RESEND to UNSENT. We
                            // still need to resend the request which is now UNSENT, so
                            // start the timer if it isn't already started.
                        }
                        break;
                    }
                    default:
                        throw new Error('unhandled state: ' + req.state);
                }
            }
        });
    }
    /**
     * Cancel room key requests, if any match the given requestBody
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *
     * @returns {Promise} resolves when the request has been updated in our
     *    pending list.
     */
    cancelRoomKeyRequest(requestBody) {
        return this.cryptoStore.getOutgoingRoomKeyRequest(requestBody).then((req) => {
            if (!req) {
                // no request was made for this key
                return;
            }
            switch (req.state) {
                case RoomKeyRequestState.CancellationPending:
                case RoomKeyRequestState.CancellationPendingAndWillResend:
                    // nothing to do here
                    return;
                case RoomKeyRequestState.Unsent:
                    // just delete it
                    // FIXME: ghahah we may have attempted to send it, and
                    // not yet got a successful response. So the server
                    // may have seen it, so we still need to send a cancellation
                    // in that case :/
                    logger_1.logger.log('deleting unnecessary room key request for ' +
                        stringifyRequestBody(requestBody));
                    return this.cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent);
                case RoomKeyRequestState.Sent: {
                    // send a cancellation.
                    return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Sent, {
                        state: RoomKeyRequestState.CancellationPending,
                        cancellationTxnId: this.baseApis.makeTxnId(),
                    }).then((updatedReq) => {
                        if (!updatedReq) {
                            // updateOutgoingRoomKeyRequest couldn't find the
                            // request in state ROOM_KEY_REQUEST_STATES.SENT,
                            // so we must have raced with another tab to mark
                            // the request cancelled. There is no point in
                            // sending another cancellation since the other tab
                            // will do it.
                            logger_1.logger.log('Tried to cancel room key request for ' +
                                stringifyRequestBody(requestBody) +
                                ' but it was already cancelled in another tab');
                            return;
                        }
                        // We don't want to wait for the timer, so we send it
                        // immediately. (We might actually end up racing with the timer,
                        // but that's ok: even if we make the request twice, we'll do it
                        // with the same transaction_id, so only one message will get
                        // sent).
                        //
                        // (We also don't want to wait for the response from the server
                        // here, as it will slow down processing of received keys if we
                        // do.)
                        this.sendOutgoingRoomKeyRequestCancellation(updatedReq).catch((e) => {
                            logger_1.logger.error("Error sending room key request cancellation;"
                                + " will retry later.", e);
                            this.startTimer();
                        });
                    });
                }
                default:
                    throw new Error('unhandled state: ' + req.state);
            }
        });
    }
    /**
     * Look for room key requests by target device and state
     *
     * @param {string} userId Target user ID
     * @param {string} deviceId Target device ID
     *
     * @return {Promise} resolves to a list of all the
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
     */
    getOutgoingSentRoomKeyRequest(userId, deviceId) {
        return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, [RoomKeyRequestState.Sent]);
    }
    /**
     * Find anything in `sent` state, and kick it around the loop again.
     * This is intended for situations where something substantial has changed, and we
     * don't really expect the other end to even care about the cancellation.
     * For example, after initialization or self-verification.
     * @return {Promise} An array of `queueRoomKeyRequest` outputs.
     */
    cancelAndResendAllOutgoingRequests() {
        return __awaiter(this, void 0, void 0, function* () {
            const outgoings = yield this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(RoomKeyRequestState.Sent);
            return Promise.all(outgoings.map(({ requestBody, recipients }) => this.queueRoomKeyRequest(requestBody, recipients, true)));
        });
    }
    // start the background timer to send queued requests, if the timer isn't
    // already running
    startTimer() {
        if (this.sendOutgoingRoomKeyRequestsTimer) {
            return;
        }
        const startSendingOutgoingRoomKeyRequests = () => {
            if (this.sendOutgoingRoomKeyRequestsRunning) {
                throw new Error("RoomKeyRequestSend already in progress!");
            }
            this.sendOutgoingRoomKeyRequestsRunning = true;
            this.sendOutgoingRoomKeyRequests().finally(() => {
                this.sendOutgoingRoomKeyRequestsRunning = false;
            }).catch((e) => {
                // this should only happen if there is an indexeddb error,
                // in which case we're a bit stuffed anyway.
                logger_1.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`);
            });
        };
        this.sendOutgoingRoomKeyRequestsTimer = global.setTimeout(startSendingOutgoingRoomKeyRequests, SEND_KEY_REQUESTS_DELAY_MS);
    }
    // look for and send any queued requests. Runs itself recursively until
    // there are no more requests, or there is an error (in which case, the
    // timer will be restarted before the promise resolves).
    sendOutgoingRoomKeyRequests() {
        if (!this.clientRunning) {
            this.sendOutgoingRoomKeyRequestsTimer = null;
            return Promise.resolve();
        }
        return this.cryptoStore.getOutgoingRoomKeyRequestByState([
            RoomKeyRequestState.CancellationPending,
            RoomKeyRequestState.CancellationPendingAndWillResend,
            RoomKeyRequestState.Unsent,
        ]).then((req) => {
            if (!req) {
                this.sendOutgoingRoomKeyRequestsTimer = null;
                return;
            }
            let prom;
            switch (req.state) {
                case RoomKeyRequestState.Unsent:
                    prom = this.sendOutgoingRoomKeyRequest(req);
                    break;
                case RoomKeyRequestState.CancellationPending:
                    prom = this.sendOutgoingRoomKeyRequestCancellation(req);
                    break;
                case RoomKeyRequestState.CancellationPendingAndWillResend:
                    prom = this.sendOutgoingRoomKeyRequestCancellation(req, true);
                    break;
            }
            return prom.then(() => {
                // go around the loop again
                return this.sendOutgoingRoomKeyRequests();
            }).catch((e) => {
                logger_1.logger.error("Error sending room key request; will retry later.", e);
                this.sendOutgoingRoomKeyRequestsTimer = null;
            });
        });
    }
    // given a RoomKeyRequest, send it and update the request record
    sendOutgoingRoomKeyRequest(req) {
        logger_1.logger.log(`Requesting keys for ${stringifyRequestBody(req.requestBody)}` +
            ` from ${stringifyRecipientList(req.recipients)}` +
            `(id ${req.requestId})`);
        const requestMessage = {
            action: "request",
            requesting_device_id: this.deviceId,
            request_id: req.requestId,
            body: req.requestBody,
        };
        return this.sendMessageToDevices(requestMessage, req.recipients, req.requestTxnId || req.requestId).then(() => {
            return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent, { state: RoomKeyRequestState.Sent });
        });
    }
    // Given a RoomKeyRequest, cancel it and delete the request record unless
    // andResend is set, in which case transition to UNSENT.
    sendOutgoingRoomKeyRequestCancellation(req, andResend = false) {
        logger_1.logger.log(`Sending cancellation for key request for ` +
            `${stringifyRequestBody(req.requestBody)} to ` +
            `${stringifyRecipientList(req.recipients)} ` +
            `(cancellation id ${req.cancellationTxnId})`);
        const requestMessage = {
            action: "request_cancellation",
            requesting_device_id: this.deviceId,
            request_id: req.requestId,
        };
        return this.sendMessageToDevices(requestMessage, req.recipients, req.cancellationTxnId).then(() => {
            if (andResend) {
                // We want to resend, so transition to UNSENT
                return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPendingAndWillResend, { state: RoomKeyRequestState.Unsent });
            }
            return this.cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPending);
        });
    }
    // send a RoomKeyRequest to a list of recipients
    sendMessageToDevices(message, recipients, txnId) {
        const contentMap = {};
        for (const recip of recipients) {
            if (!contentMap[recip.userId]) {
                contentMap[recip.userId] = {};
            }
            contentMap[recip.userId][recip.deviceId] = message;
        }
        return this.baseApis.sendToDevice(event_1.EventType.RoomKeyRequest, contentMap, txnId);
    }
}
exports.OutgoingRoomKeyRequestManager = OutgoingRoomKeyRequestManager;
function stringifyRequestBody(requestBody) {
    // we assume that the request is for megolm keys, which are identified by
    // room id and session id
    return requestBody.room_id + " / " + requestBody.session_id;
}
function stringifyRecipientList(recipients) {
    return '['
        + recipients.map((r) => `${r.userId}:${r.deviceId}`).join(",")
        + ']';
}

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../@types/event":58,"../logger":106}],72:[function(require,module,exports){
"use strict";
/*
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoomList = void 0;
/**
 * @module crypto/RoomList
 *
 * Manages the list of encrypted rooms
 */
const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store");
/* eslint-enable camelcase */
/**
 * @alias module:crypto/RoomList
 */
class RoomList {
    constructor(cryptoStore) {
        this.cryptoStore = cryptoStore;
        // Object of roomId -> room e2e info object (body of the m.room.encryption event)
        this.roomEncryption = {};
    }
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ROOMS], (txn) => {
                this.cryptoStore.getEndToEndRooms(txn, (result) => {
                    this.roomEncryption = result;
                });
            });
        });
    }
    getRoomEncryption(roomId) {
        return this.roomEncryption[roomId] || null;
    }
    isRoomEncrypted(roomId) {
        return Boolean(this.getRoomEncryption(roomId));
    }
    setRoomEncryption(roomId, roomInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            // important that this happens before calling into the store
            // as it prevents the Crypto::setRoomEncryption from calling
            // this twice for consecutive m.room.encryption events
            this.roomEncryption[roomId] = roomInfo;
            yield this.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ROOMS], (txn) => {
                this.cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn);
            });
        });
    }
}
exports.RoomList = RoomList;

},{"./store/indexeddb-crypto-store":88}],73:[function(require,module,exports){
"use strict";
/*
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecretStorage = exports.SECRET_STORAGE_ALGORITHM_V1_AES = void 0;
const logger_1 = require("../logger");
const olmlib = __importStar(require("./olmlib"));
const randomstring_1 = require("../randomstring");
const aes_1 = require("./aes");
const olmlib_1 = require("./olmlib");
exports.SECRET_STORAGE_ALGORITHM_V1_AES = "m.secret_storage.v1.aes-hmac-sha2";
/**
 * Implements Secure Secret Storage and Sharing (MSC1946)
 * @module crypto/SecretStorage
 */
class SecretStorage {
    // In it's pure javascript days, this was relying on some proper Javascript-style
    // type-abuse where sometimes we'd pass in a fake client object with just the account
    // data methods implemented, which is all this class needs unless you use the secret
    // sharing code, so it was fine. As a low-touch TypeScript migration, this now has
    // an extra, optional param for a real matrix client, so you can not pass it as long
    // as you don't request any secrets.
    // A better solution would probably be to split this class up into secret storage and
    // secret sharing which are really two separate things, even though they share an MSC.
    constructor(accountDataAdapter, cryptoCallbacks, baseApis) {
        this.accountDataAdapter = accountDataAdapter;
        this.cryptoCallbacks = cryptoCallbacks;
        this.baseApis = baseApis;
        this.requests = new Map();
    }
    getDefaultKeyId() {
        return __awaiter(this, void 0, void 0, function* () {
            const defaultKey = yield this.accountDataAdapter.getAccountDataFromServer('m.secret_storage.default_key');
            if (!defaultKey)
                return null;
            return defaultKey.key;
        });
    }
    setDefaultKeyId(keyId) {
        return new Promise((resolve, reject) => {
            const listener = (ev) => {
                if (ev.getType() === 'm.secret_storage.default_key' &&
                    ev.getContent().key === keyId) {
                    this.accountDataAdapter.removeListener('accountData', listener);
                    resolve();
                }
            };
            this.accountDataAdapter.on('accountData', listener);
            this.accountDataAdapter.setAccountData('m.secret_storage.default_key', { key: keyId }).catch(e => {
                this.accountDataAdapter.removeListener('accountData', listener);
                reject(e);
            });
        });
    }
    /**
     * Add a key for encrypting secrets.
     *
     * @param {string} algorithm the algorithm used by the key.
     * @param {object} opts the options for the algorithm.  The properties used
     *     depend on the algorithm given.
     * @param {string} [keyId] the ID of the key.  If not given, a random
     *     ID will be generated.
     *
     * @return {object} An object with:
     *     keyId: {string} the ID of the key
     *     keyInfo: {object} details about the key (iv, mac, passphrase)
     */
    addKey(algorithm, opts, keyId) {
        return __awaiter(this, void 0, void 0, function* () {
            const keyInfo = { algorithm };
            if (!opts)
                opts = {};
            if (opts.name) {
                keyInfo.name = opts.name;
            }
            if (algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                if (opts.passphrase) {
                    keyInfo.passphrase = opts.passphrase;
                }
                if (opts.key) {
                    const { iv, mac } = yield aes_1.calculateKeyCheck(opts.key);
                    keyInfo.iv = iv;
                    keyInfo.mac = mac;
                }
            }
            else {
                throw new Error(`Unknown key algorithm ${algorithm}`);
            }
            if (!keyId) {
                do {
                    keyId = randomstring_1.randomString(32);
                } while (yield this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`));
            }
            yield this.accountDataAdapter.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);
            return {
                keyId,
                keyInfo,
            };
        });
    }
    /**
     * Get the key information for a given ID.
     *
     * @param {string} [keyId = default key's ID] The ID of the key to check
     *     for. Defaults to the default key ID if not provided.
     * @returns {Array?} If the key was found, the return value is an array of
     *     the form [keyId, keyInfo].  Otherwise, null is returned.
     *     XXX: why is this an array when addKey returns an object?
     */
    getKey(keyId) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!keyId) {
                keyId = yield this.getDefaultKeyId();
            }
            if (!keyId) {
                return null;
            }
            const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId);
            return keyInfo ? [keyId, keyInfo] : null;
        });
    }
    /**
     * Check whether we have a key with a given ID.
     *
     * @param {string} [keyId = default key's ID] The ID of the key to check
     *     for. Defaults to the default key ID if not provided.
     * @return {boolean} Whether we have the key.
     */
    hasKey(keyId) {
        return __awaiter(this, void 0, void 0, function* () {
            return Boolean(yield this.getKey(keyId));
        });
    }
    /**
     * Check whether a key matches what we expect based on the key info
     *
     * @param {Uint8Array} key the key to check
     * @param {object} info the key info
     *
     * @return {boolean} whether or not the key matches
     */
    checkKey(key, info) {
        return __awaiter(this, void 0, void 0, function* () {
            if (info.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                if (info.mac) {
                    const { mac } = yield aes_1.calculateKeyCheck(key, info.iv);
                    return info.mac.replace(/=+$/g, '') === mac.replace(/=+$/g, '');
                }
                else {
                    // if we have no information, we have to assume the key is right
                    return true;
                }
            }
            else {
                throw new Error("Unknown algorithm");
            }
        });
    }
    /**
     * Store an encrypted secret on the server
     *
     * @param {string} name The name of the secret
     * @param {string} secret The secret contents.
     * @param {Array} keys The IDs of the keys to use to encrypt the secret
     *     or null/undefined to use the default key.
     */
    store(name, secret, keys) {
        return __awaiter(this, void 0, void 0, function* () {
            const encrypted = {};
            if (!keys) {
                const defaultKeyId = yield this.getDefaultKeyId();
                if (!defaultKeyId) {
                    throw new Error("No keys specified and no default key present");
                }
                keys = [defaultKeyId];
            }
            if (keys.length === 0) {
                throw new Error("Zero keys given to encrypt with!");
            }
            for (const keyId of keys) {
                // get key information from key storage
                const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId);
                if (!keyInfo) {
                    throw new Error("Unknown key: " + keyId);
                }
                // encrypt secret, based on the algorithm
                if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                    const keys = { [keyId]: keyInfo };
                    const [, encryption] = yield this.getSecretStorageKey(keys, name);
                    encrypted[keyId] = yield encryption.encrypt(secret);
                }
                else {
                    logger_1.logger.warn("unknown algorithm for secret storage key " + keyId
                        + ": " + keyInfo.algorithm);
                    // do nothing if we don't understand the encryption algorithm
                }
            }
            // save encrypted secret
            yield this.accountDataAdapter.setAccountData(name, { encrypted });
        });
    }
    /**
     * Get a secret from storage.
     *
     * @param {string} name the name of the secret
     *
     * @return {string} the contents of the secret
     */
    get(name) {
        return __awaiter(this, void 0, void 0, function* () {
            const secretInfo = yield this.accountDataAdapter.getAccountDataFromServer(name);
            if (!secretInfo) {
                return;
            }
            if (!secretInfo.encrypted) {
                throw new Error("Content is not encrypted!");
            }
            // get possible keys to decrypt
            const keys = {};
            for (const keyId of Object.keys(secretInfo.encrypted)) {
                // get key information from key storage
                const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId);
                const encInfo = secretInfo.encrypted[keyId];
                // only use keys we understand the encryption algorithm of
                if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                    if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {
                        keys[keyId] = keyInfo;
                    }
                }
            }
            if (Object.keys(keys).length === 0) {
                throw new Error(`Could not decrypt ${name} because none of ` +
                    `the keys it is encrypted with are for a supported algorithm`);
            }
            let keyId;
            let decryption;
            try {
                // fetch private key from app
                [keyId, decryption] = yield this.getSecretStorageKey(keys, name);
                const encInfo = secretInfo.encrypted[keyId];
                // We don't actually need the decryption object if it's a passthrough
                // since we just want to return the key itself. It must be base64
                // encoded, since this is how a key would normally be stored.
                if (encInfo.passthrough)
                    return olmlib_1.encodeBase64(decryption.get_private_key());
                return yield decryption.decrypt(encInfo);
            }
            finally {
                if (decryption && decryption.free)
                    decryption.free();
            }
        });
    }
    /**
     * Check if a secret is stored on the server.
     *
     * @param {string} name the name of the secret
     * @param {boolean} checkKey check if the secret is encrypted by a trusted key
     *
     * @return {object?} map of key name to key info the secret is encrypted
     *     with, or null if it is not present or not encrypted with a trusted
     *     key
     */
    isStored(name, checkKey) {
        return __awaiter(this, void 0, void 0, function* () {
            // check if secret exists
            const secretInfo = yield this.accountDataAdapter.getAccountDataFromServer(name);
            if (!secretInfo)
                return null;
            if (!secretInfo.encrypted) {
                return null;
            }
            if (checkKey === undefined)
                checkKey = true;
            const ret = {};
            // filter secret encryption keys with supported algorithm
            for (const keyId of Object.keys(secretInfo.encrypted)) {
                // get key information from key storage
                const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId);
                if (!keyInfo)
                    continue;
                const encInfo = secretInfo.encrypted[keyId];
                // only use keys we understand the encryption algorithm of
                if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                    if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {
                        ret[keyId] = keyInfo;
                    }
                }
            }
            return Object.keys(ret).length ? ret : null;
        });
    }
    /**
     * Request a secret from another device
     *
     * @param {string} name the name of the secret to request
     * @param {string[]} devices the devices to request the secret from
     */
    request(name, devices) {
        const requestId = this.baseApis.makeTxnId();
        let resolve;
        let reject;
        const promise = new Promise((res, rej) => {
            resolve = res;
            reject = rej;
        });
        this.requests.set(requestId, {
            name,
            devices,
            resolve,
            reject,
        });
        const cancel = (reason) => {
            // send cancellation event
            const cancelData = {
                action: "request_cancellation",
                requesting_device_id: this.baseApis.deviceId,
                request_id: requestId,
            };
            const toDevice = {};
            for (const device of devices) {
                toDevice[device] = cancelData;
            }
            this.baseApis.sendToDevice("m.secret.request", {
                [this.baseApis.getUserId()]: toDevice,
            });
            // and reject the promise so that anyone waiting on it will be
            // notified
            reject(new Error(reason || "Cancelled"));
        };
        // send request to devices
        const requestData = {
            name,
            action: "request",
            requesting_device_id: this.baseApis.deviceId,
            request_id: requestId,
        };
        const toDevice = {};
        for (const device of devices) {
            toDevice[device] = requestData;
        }
        logger_1.logger.info(`Request secret ${name} from ${devices}, id ${requestId}`);
        this.baseApis.sendToDevice("m.secret.request", {
            [this.baseApis.getUserId()]: toDevice,
        });
        return {
            requestId,
            promise,
            cancel,
        };
    }
    onRequestReceived(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const sender = event.getSender();
            const content = event.getContent();
            if (sender !== this.baseApis.getUserId()
                || !(content.name && content.action
                    && content.requesting_device_id && content.request_id)) {
                // ignore requests from anyone else, for now
                return;
            }
            const deviceId = content.requesting_device_id;
            // check if it's a cancel
            if (content.action === "request_cancellation") {
                /*
                Looks like we intended to emit events when we got cancelations, but
                we never put anything in the _incomingRequests object, and the request
                itself doesn't use events anyway so if we were to wire up cancellations,
                they probably ought to use the same callback interface. I'm leaving them
                disabled for now while converting this file to typescript.
                if (this._incomingRequests[deviceId]
                    && this._incomingRequests[deviceId][content.request_id]) {
                    logger.info(
                        "received request cancellation for secret (" + sender +
                        ", " + deviceId + ", " + content.request_id + ")",
                    );
                    this.baseApis.emit("crypto.secrets.requestCancelled", {
                        user_id: sender,
                        device_id: deviceId,
                        request_id: content.request_id,
                    });
                }
                */
            }
            else if (content.action === "request") {
                if (deviceId === this.baseApis.deviceId) {
                    // no point in trying to send ourself the secret
                    return;
                }
                // check if we have the secret
                logger_1.logger.info("received request for secret (" + sender +
                    ", " + deviceId + ", " + content.request_id + ")");
                if (!this.cryptoCallbacks.onSecretRequested) {
                    return;
                }
                const secret = yield this.cryptoCallbacks.onSecretRequested(sender, deviceId, content.request_id, content.name, this.baseApis.checkDeviceTrust(sender, deviceId));
                if (secret) {
                    logger_1.logger.info(`Preparing ${content.name} secret for ${deviceId}`);
                    const payload = {
                        type: "m.secret.send",
                        content: {
                            request_id: content.request_id,
                            secret: secret,
                        },
                    };
                    const encryptedContent = {
                        algorithm: olmlib.OLM_ALGORITHM,
                        sender_key: this.baseApis.crypto.olmDevice.deviceCurve25519Key,
                        ciphertext: {},
                    };
                    yield olmlib.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice, this.baseApis, {
                        [sender]: [
                            this.baseApis.getStoredDevice(sender, deviceId),
                        ],
                    });
                    yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.baseApis.getUserId(), this.baseApis.deviceId, this.baseApis.crypto.olmDevice, sender, this.baseApis.getStoredDevice(sender, deviceId), payload);
                    const contentMap = {
                        [sender]: {
                            [deviceId]: encryptedContent,
                        },
                    };
                    logger_1.logger.info(`Sending ${content.name} secret for ${deviceId}`);
                    this.baseApis.sendToDevice("m.room.encrypted", contentMap);
                }
                else {
                    logger_1.logger.info(`Request denied for ${content.name} secret for ${deviceId}`);
                }
            }
        });
    }
    onSecretReceived(event) {
        if (event.getSender() !== this.baseApis.getUserId()) {
            // we shouldn't be receiving secrets from anyone else, so ignore
            // because someone could be trying to send us bogus data
            return;
        }
        const content = event.getContent();
        logger_1.logger.log("got secret share for request", content.request_id);
        const requestControl = this.requests.get(content.request_id);
        if (requestControl) {
            // make sure that the device that sent it is one of the devices that
            // we requested from
            const deviceInfo = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, event.getSenderKey());
            if (!deviceInfo) {
                logger_1.logger.log("secret share from unknown device with key", event.getSenderKey());
                return;
            }
            if (!requestControl.devices.includes(deviceInfo.deviceId)) {
                logger_1.logger.log("unsolicited secret share from device", deviceInfo.deviceId);
                return;
            }
            logger_1.logger.log(`Successfully received secret ${requestControl.name} ` +
                `from ${deviceInfo.deviceId}`);
            requestControl.resolve(content.secret);
        }
    }
    getSecretStorageKey(keys, name) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.cryptoCallbacks.getSecretStorageKey) {
                throw new Error("No getSecretStorageKey callback supplied");
            }
            const returned = yield this.cryptoCallbacks.getSecretStorageKey({ keys }, name);
            if (!returned) {
                throw new Error("getSecretStorageKey callback returned falsey");
            }
            if (returned.length < 2) {
                throw new Error("getSecretStorageKey callback returned invalid data");
            }
            const [keyId, privateKey] = returned;
            if (!keys[keyId]) {
                throw new Error("App returned unknown key from getSecretStorageKey!");
            }
            if (keys[keyId].algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) {
                const decryption = {
                    encrypt: function (secret) {
                        return __awaiter(this, void 0, void 0, function* () {
                            return yield aes_1.encryptAES(secret, privateKey, name);
                        });
                    },
                    decrypt: function (encInfo) {
                        return __awaiter(this, void 0, void 0, function* () {
                            return yield aes_1.decryptAES(encInfo, privateKey, name);
                        });
                    },
                };
                return [keyId, decryption];
            }
            else {
                throw new Error("Unknown key type: " + keys[keyId].algorithm);
            }
        });
    }
}
exports.SecretStorage = SecretStorage;

},{"../logger":106,"../randomstring":123,"./aes":74,"./olmlib":85}],74:[function(require,module,exports){
(function (Buffer){(function (){
"use strict";
/*
Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateKeyCheck = exports.decryptAES = exports.encryptAES = void 0;
const utils_1 = require("../utils");
const olmlib_1 = require("./olmlib");
const subtleCrypto = (typeof window !== "undefined" && window.crypto) ?
    (window.crypto.subtle || window.crypto.webkitSubtle) : null;
// salt for HKDF, with 8 bytes of zeros
const zeroSalt = new Uint8Array(8);
/**
 * encrypt a string in Node.js
 *
 * @param {string} data the plaintext to encrypt
 * @param {Uint8Array} key the encryption key to use
 * @param {string} name the name of the secret
 * @param {string} ivStr the initialization vector to use
 */
function encryptNode(data, key, name, ivStr) {
    return __awaiter(this, void 0, void 0, function* () {
        const crypto = utils_1.getCrypto();
        if (!crypto) {
            throw new Error("No usable crypto implementation");
        }
        let iv;
        if (ivStr) {
            iv = olmlib_1.decodeBase64(ivStr);
        }
        else {
            iv = crypto.randomBytes(16);
        }
        // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary
        // (which would mean we wouldn't be able to decrypt on Android). The loss
        // of a single bit of iv is a price we have to pay.
        iv[8] &= 0x7f;
        const [aesKey, hmacKey] = deriveKeysNode(key, name);
        const cipher = crypto.createCipheriv("aes-256-ctr", aesKey, iv);
        const ciphertext = Buffer.concat([
            cipher.update(data, "utf8"),
            cipher.final(),
        ]);
        const hmac = crypto.createHmac("sha256", hmacKey)
            .update(ciphertext).digest("base64");
        return {
            iv: olmlib_1.encodeBase64(iv),
            ciphertext: ciphertext.toString("base64"),
            mac: hmac,
        };
    });
}
/**
 * decrypt a string in Node.js
 *
 * @param {object} data the encrypted data
 * @param {string} data.ciphertext the ciphertext in base64
 * @param {string} data.iv the initialization vector in base64
 * @param {string} data.mac the HMAC in base64
 * @param {Uint8Array} key the encryption key to use
 * @param {string} name the name of the secret
 */
function decryptNode(data, key, name) {
    return __awaiter(this, void 0, void 0, function* () {
        const crypto = utils_1.getCrypto();
        if (!crypto) {
            throw new Error("No usable crypto implementation");
        }
        const [aesKey, hmacKey] = deriveKeysNode(key, name);
        const hmac = crypto.createHmac("sha256", hmacKey)
            .update(Buffer.from(data.ciphertext, "base64"))
            .digest("base64").replace(/=+$/g, '');
        if (hmac !== data.mac.replace(/=+$/g, '')) {
            throw new Error(`Error decrypting secret ${name}: bad MAC`);
        }
        const decipher = crypto.createDecipheriv("aes-256-ctr", aesKey, olmlib_1.decodeBase64(data.iv));
        return decipher.update(data.ciphertext, "base64", "utf8")
            + decipher.final("utf8");
    });
}
function deriveKeysNode(key, name) {
    const crypto = utils_1.getCrypto();
    const prk = crypto.createHmac("sha256", zeroSalt).update(key).digest();
    const b = Buffer.alloc(1, 1);
    const aesKey = crypto.createHmac("sha256", prk)
        .update(name, "utf8").update(b).digest();
    b[0] = 2;
    const hmacKey = crypto.createHmac("sha256", prk)
        .update(aesKey).update(name, "utf8").update(b).digest();
    return [aesKey, hmacKey];
}
/**
 * encrypt a string in Node.js
 *
 * @param {string} data the plaintext to encrypt
 * @param {Uint8Array} key the encryption key to use
 * @param {string} name the name of the secret
 * @param {string} ivStr the initialization vector to use
 */
function encryptBrowser(data, key, name, ivStr) {
    return __awaiter(this, void 0, void 0, function* () {
        let iv;
        if (ivStr) {
            iv = olmlib_1.decodeBase64(ivStr);
        }
        else {
            iv = new Uint8Array(16);
            window.crypto.getRandomValues(iv);
        }
        // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary
        // (which would mean we wouldn't be able to decrypt on Android). The loss
        // of a single bit of iv is a price we have to pay.
        iv[8] &= 0x7f;
        const [aesKey, hmacKey] = yield deriveKeysBrowser(key, name);
        const encodedData = new TextEncoder().encode(data);
        const ciphertext = yield subtleCrypto.encrypt({
            name: "AES-CTR",
            counter: iv,
            length: 64,
        }, aesKey, encodedData);
        const hmac = yield subtleCrypto.sign({ name: 'HMAC' }, hmacKey, ciphertext);
        return {
            iv: olmlib_1.encodeBase64(iv),
            ciphertext: olmlib_1.encodeBase64(ciphertext),
            mac: olmlib_1.encodeBase64(hmac),
        };
    });
}
/**
 * decrypt a string in the browser
 *
 * @param {object} data the encrypted data
 * @param {string} data.ciphertext the ciphertext in base64
 * @param {string} data.iv the initialization vector in base64
 * @param {string} data.mac the HMAC in base64
 * @param {Uint8Array} key the encryption key to use
 * @param {string} name the name of the secret
 */
function decryptBrowser(data, key, name) {
    return __awaiter(this, void 0, void 0, function* () {
        const [aesKey, hmacKey] = yield deriveKeysBrowser(key, name);
        const ciphertext = olmlib_1.decodeBase64(data.ciphertext);
        if (!(yield subtleCrypto.verify({ name: "HMAC" }, hmacKey, olmlib_1.decodeBase64(data.mac), ciphertext))) {
            throw new Error(`Error decrypting secret ${name}: bad MAC`);
        }
        const plaintext = yield subtleCrypto.decrypt({
            name: "AES-CTR",
            counter: olmlib_1.decodeBase64(data.iv),
            length: 64,
        }, aesKey, ciphertext);
        return new TextDecoder().decode(new Uint8Array(plaintext));
    });
}
function deriveKeysBrowser(key, name) {
    return __awaiter(this, void 0, void 0, function* () {
        const hkdfkey = yield subtleCrypto.importKey('raw', key, { name: "HKDF" }, false, ["deriveBits"]);
        const keybits = yield subtleCrypto.deriveBits({
            name: "HKDF",
            salt: zeroSalt,
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879
            info: (new TextEncoder().encode(name)),
            hash: "SHA-256",
        }, hkdfkey, 512);
        const aesKey = keybits.slice(0, 32);
        const hmacKey = keybits.slice(32);
        const aesProm = subtleCrypto.importKey('raw', aesKey, { name: 'AES-CTR' }, false, ['encrypt', 'decrypt']);
        const hmacProm = subtleCrypto.importKey('raw', hmacKey, {
            name: 'HMAC',
            hash: { name: 'SHA-256' },
        }, false, ['sign', 'verify']);
        return yield Promise.all([aesProm, hmacProm]);
    });
}
function encryptAES(data, key, name, ivStr) {
    return subtleCrypto ? encryptBrowser(data, key, name, ivStr) : encryptNode(data, key, name, ivStr);
}
exports.encryptAES = encryptAES;
function decryptAES(data, key, name) {
    return subtleCrypto ? decryptBrowser(data, key, name) : decryptNode(data, key, name);
}
exports.decryptAES = decryptAES;
// string of zeroes, for calculating the key check
const 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";
/** Calculate the MAC for checking the key.
 *
 * @param {Uint8Array} key the key to use
 * @param {string} [iv] The initialization vector as a base64-encoded string.
 *     If omitted, a random initialization vector will be created.
 * @return {Promise<object>} An object that contains, `mac` and `iv` properties.
 */
function calculateKeyCheck(key, iv) {
    return encryptAES(ZERO_STR, key, "", iv);
}
exports.calculateKeyCheck = calculateKeyCheck;

}).call(this)}).call(this,require("buffer").Buffer)

},{"../utils":137,"./olmlib":85,"buffer":34}],75:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAlgorithm = exports.UnknownDeviceError = exports.DecryptionError = exports.DecryptionAlgorithm = exports.EncryptionAlgorithm = exports.DECRYPTION_CLASSES = exports.ENCRYPTION_CLASSES = void 0;
/**
 * map of registered encryption algorithm classes. A map from string to {@link
 * module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm} class
 *
 * @type {Object.<string, function(new: module:crypto/algorithms/base.EncryptionAlgorithm)>}
 */
exports.ENCRYPTION_CLASSES = {};
/**
 * map of registered encryption algorithm classes. Map from string to {@link
 * module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm} class
 *
 * @type {Object.<string, function(new: module:crypto/algorithms/base.DecryptionAlgorithm)>}
 */
exports.DECRYPTION_CLASSES = {};
/**
 * base type for encryption implementations
 *
 * @alias module:crypto/algorithms/base.EncryptionAlgorithm
 *
 * @param {object} params parameters
 * @param {string} params.userId  The UserID for the local user
 * @param {string} params.deviceId The identifier for this device.
 * @param {module:crypto} params.crypto crypto core
 * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper
 * @param {MatrixClient} baseApis base matrix api interface
 * @param {string} params.roomId  The ID of the room we will be sending to
 * @param {object} params.config  The body of the m.room.encryption event
 */
class EncryptionAlgorithm {
    constructor(params) {
        this.userId = params.userId;
        this.deviceId = params.deviceId;
        this.crypto = params.crypto;
        this.olmDevice = params.olmDevice;
        this.baseApis = params.baseApis;
        this.roomId = params.roomId;
    }
    /**
     * Perform any background tasks that can be done before a message is ready to
     * send, in order to speed up sending of the message.
     *
     * @param {module:models/room} room the room the event is in
     */
    prepareToEncrypt(room) { }
    /**
     * Called when the membership of a member of the room changes.
     *
     * @param {module:models/event.MatrixEvent} event  event causing the change
     * @param {module:models/room-member} member  user whose membership changed
     * @param {string=} oldMembership  previous membership
     * @public
     * @abstract
     */
    onRoomMembership(event, member, oldMembership) { }
}
exports.EncryptionAlgorithm = EncryptionAlgorithm;
/**
 * base type for decryption implementations
 *
 * @alias module:crypto/algorithms/base.DecryptionAlgorithm
 * @param {object} params parameters
 * @param {string} params.userId  The UserID for the local user
 * @param {module:crypto} params.crypto crypto core
 * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper
 * @param {MatrixClient} baseApis base matrix api interface
 * @param {string=} params.roomId The ID of the room we will be receiving
 *     from. Null for to-device events.
 */
class DecryptionAlgorithm {
    constructor(params) {
        this.userId = params.userId;
        this.crypto = params.crypto;
        this.olmDevice = params.olmDevice;
        this.baseApis = params.baseApis;
        this.roomId = params.roomId;
    }
    /**
     * Handle a key event
     *
     * @method module:crypto/algorithms/base.DecryptionAlgorithm#onRoomKeyEvent
     *
     * @param {module:models/event.MatrixEvent} params event key event
     */
    onRoomKeyEvent(params) {
        // ignore by default
    }
    /**
     * Import a room key
     *
     * @param {module:crypto/OlmDevice.MegolmSessionData} session
     * @param {object} opts object
     */
    importRoomKey(session, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            // ignore by default
        });
    }
    /**
     * Determine if we have the keys necessary to respond to a room key request
     *
     * @param {module:crypto~IncomingRoomKeyRequest} keyRequest
     * @return {Promise<boolean>} true if we have the keys and could (theoretically) share
     *  them; else false.
     */
    hasKeysForKeyRequest(keyRequest) {
        return Promise.resolve(false);
    }
    /**
     * Send the response to a room key request
     *
     * @param {module:crypto~IncomingRoomKeyRequest} keyRequest
     */
    shareKeysWithDevice(keyRequest) {
        throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm");
    }
    /**
     * Retry decrypting all the events from a sender that haven't been
     * decrypted yet.
     *
     * @param {string} senderKey the sender's key
     */
    retryDecryptionFromSender(senderKey) {
        return __awaiter(this, void 0, void 0, function* () {
            // ignore by default
            return false;
        });
    }
}
exports.DecryptionAlgorithm = DecryptionAlgorithm;
/**
 * Exception thrown when decryption fails
 *
 * @alias module:crypto/algorithms/base.DecryptionError
 * @param {string} msg user-visible message describing the problem
 *
 * @param {Object=} details key/value pairs reported in the logs but not shown
 *   to the user.
 *
 * @extends Error
 */
class DecryptionError extends Error {
    constructor(code, msg, details) {
        super(msg);
        this.code = code;
        this.code = code;
        this.name = 'DecryptionError';
        this.detailedString = detailedStringForDecryptionError(this, details);
    }
}
exports.DecryptionError = DecryptionError;
function detailedStringForDecryptionError(err, details) {
    let result = err.name + '[msg: ' + err.message;
    if (details) {
        result += ', ' + Object.keys(details).map((k) => k + ': ' + details[k]).join(', ');
    }
    result += ']';
    return result;
}
/**
 * Exception thrown specifically when we want to warn the user to consider
 * the security of their conversation before continuing
 *
 * @param {string} msg message describing the problem
 * @param {Object} devices userId -> {deviceId -> object}
 *      set of unknown devices per user we're warning about
 * @extends Error
 */
class UnknownDeviceError extends Error {
    constructor(msg, devices) {
        super(msg);
        this.devices = devices;
        this.name = "UnknownDeviceError";
        this.devices = devices;
    }
}
exports.UnknownDeviceError = UnknownDeviceError;
/**
 * Registers an encryption/decryption class for a particular algorithm
 *
 * @param {string} algorithm algorithm tag to register for
 *
 * @param {class} encryptor {@link
 *     module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm}
 *     implementation
 *
 * @param {class} decryptor {@link
 *     module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm}
 *     implementation
 */
function registerAlgorithm(algorithm, encryptor, decryptor) {
    exports.ENCRYPTION_CLASSES[algorithm] = encryptor;
    exports.DECRYPTION_CLASSES[algorithm] = decryptor;
}
exports.registerAlgorithm = registerAlgorithm;

},{}],76:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @module crypto/algorithms
 */
require("./olm");
require("./megolm");
__exportStar(require("./base"), exports);

},{"./base":75,"./megolm":77,"./olm":78}],77:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRoomSharedHistory = void 0;
/**
 * Defines m.olm encryption/decryption
 *
 * @module crypto/algorithms/megolm
 */
const logger_1 = require("../../logger");
const olmlib = __importStar(require("../olmlib"));
const base_1 = require("./base");
const OlmDevice_1 = require("../OlmDevice");
// determine whether the key can be shared with invitees
function isRoomSharedHistory(room) {
    var _a, _b;
    const visibilityEvent = (_a = room === null || room === void 0 ? void 0 : room.currentState) === null || _a === void 0 ? void 0 : _a.getStateEvents("m.room.history_visibility", "");
    // NOTE: if the room visibility is unset, it would normally default to
    // "world_readable".
    // (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5)
    // But we will be paranoid here, and treat it as a situation where the room
    // is not shared-history
    const visibility = (_b = visibilityEvent === null || visibilityEvent === void 0 ? void 0 : visibilityEvent.getContent()) === null || _b === void 0 ? void 0 : _b.history_visibility;
    return ["world_readable", "shared"].includes(visibility);
}
exports.isRoomSharedHistory = isRoomSharedHistory;
/* eslint-enable camelcase */
/**
 * @private
 * @constructor
 *
 * @param {string} sessionId
 * @param {boolean} sharedHistory whether the session can be freely shared with
 *    other group members, according to the room history visibility settings
 *
 * @property {string} sessionId
 * @property {Number} useCount     number of times this session has been used
 * @property {Number} creationTime when the session was created (ms since the epoch)
 *
 * @property {object} sharedWithDevices
 *    devices with which we have shared the session key
 *        userId -> {deviceId -> msgindex}
 */
class OutboundSessionInfo {
    constructor(sessionId, sharedHistory = false) {
        this.sessionId = sessionId;
        this.sharedHistory = sharedHistory;
        this.useCount = 0;
        this.sharedWithDevices = {};
        this.blockedDevicesNotified = {};
        this.creationTime = new Date().getTime();
    }
    /**
     * Check if it's time to rotate the session
     *
     * @param {Number} rotationPeriodMsgs
     * @param {Number} rotationPeriodMs
     * @return {Boolean}
     */
    needsRotation(rotationPeriodMsgs, rotationPeriodMs) {
        const sessionLifetime = new Date().getTime() - this.creationTime;
        if (this.useCount >= rotationPeriodMsgs ||
            sessionLifetime >= rotationPeriodMs) {
            logger_1.logger.log("Rotating megolm session after " + this.useCount +
                " messages, " + sessionLifetime + "ms");
            return true;
        }
        return false;
    }
    markSharedWithDevice(userId, deviceId, chainIndex) {
        if (!this.sharedWithDevices[userId]) {
            this.sharedWithDevices[userId] = {};
        }
        this.sharedWithDevices[userId][deviceId] = chainIndex;
    }
    markNotifiedBlockedDevice(userId, deviceId) {
        if (!this.blockedDevicesNotified[userId]) {
            this.blockedDevicesNotified[userId] = {};
        }
        this.blockedDevicesNotified[userId][deviceId] = true;
    }
    /**
     * Determine if this session has been shared with devices which it shouldn't
     * have been.
     *
     * @param {Object} devicesInRoom userId -> {deviceId -> object}
     *   devices we should shared the session with.
     *
     * @return {Boolean} true if we have shared the session with devices which aren't
     * in devicesInRoom.
     */
    sharedWithTooManyDevices(devicesInRoom) {
        for (const userId in this.sharedWithDevices) {
            if (!this.sharedWithDevices.hasOwnProperty(userId)) {
                continue;
            }
            if (!devicesInRoom.hasOwnProperty(userId)) {
                logger_1.logger.log("Starting new megolm session because we shared with " + userId);
                return true;
            }
            for (const deviceId in this.sharedWithDevices[userId]) {
                if (!this.sharedWithDevices[userId].hasOwnProperty(deviceId)) {
                    continue;
                }
                if (!devicesInRoom[userId].hasOwnProperty(deviceId)) {
                    logger_1.logger.log("Starting new megolm session because we shared with " +
                        userId + ":" + deviceId);
                    return true;
                }
            }
        }
    }
}
/**
 * Megolm encryption implementation
 *
 * @constructor
 * @extends {module:crypto/algorithms/EncryptionAlgorithm}
 *
 * @param {object} params parameters, as per
 *     {@link module:crypto/algorithms/EncryptionAlgorithm}
 */
class MegolmEncryption extends base_1.EncryptionAlgorithm {
    constructor(params) {
        var _a, _b, _c, _d;
        super(params);
        // the most recent attempt to set up a session. This is used to serialise
        // the session setups, so that we have a race-free view of which session we
        // are using, and which devices we have shared the keys with. It resolves
        // with an OutboundSessionInfo (or undefined, for the first message in the
        // room).
        this.setupPromise = Promise.resolve(undefined);
        // Map of outbound sessions by sessions ID. Used if we need a particular
        // session (the session we're currently using to send is always obtained
        // using setupPromise).
        this.outboundSessions = {};
        this.sessionRotationPeriodMsgs = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.rotation_period_msgs) !== null && _b !== void 0 ? _b : 100;
        this.sessionRotationPeriodMs = (_d = (_c = params.config) === null || _c === void 0 ? void 0 : _c.rotation_period_ms) !== null && _d !== void 0 ? _d : 7 * 24 * 3600 * 1000;
    }
    /**
     * @private
     *
     * @param {module:models/room} room
     * @param {Object} devicesInRoom The devices in this room, indexed by user ID
     * @param {Object} blocked The devices that are blocked, indexed by user ID
     * @param {boolean} [singleOlmCreationPhase] Only perform one round of olm
     *     session creation
     *
     * @return {Promise} Promise which resolves to the
     *    OutboundSessionInfo when setup is complete.
     */
    ensureOutboundSession(room, devicesInRoom, blocked, singleOlmCreationPhase = false) {
        return __awaiter(this, void 0, void 0, function* () {
            let session;
            // takes the previous OutboundSessionInfo, and considers whether to create
            // a new one. Also shares the key with any (new) devices in the room.
            // Updates `session` to hold the final OutboundSessionInfo.
            //
            // returns a promise which resolves once the keyshare is successful.
            const prepareSession = (oldSession) => __awaiter(this, void 0, void 0, function* () {
                session = oldSession;
                const sharedHistory = isRoomSharedHistory(room);
                // history visibility changed
                if (session && sharedHistory !== session.sharedHistory) {
                    session = null;
                }
                // need to make a brand new session?
                if (session && session.needsRotation(this.sessionRotationPeriodMsgs, this.sessionRotationPeriodMs)) {
                    logger_1.logger.log("Starting new megolm session because we need to rotate.");
                    session = null;
                }
                // determine if we have shared with anyone we shouldn't have
                if (session && session.sharedWithTooManyDevices(devicesInRoom)) {
                    session = null;
                }
                if (!session) {
                    logger_1.logger.log(`Starting new megolm session for room ${this.roomId}`);
                    session = yield this.prepareNewSession(sharedHistory);
                    logger_1.logger.log(`Started new megolm session ${session.sessionId} ` +
                        `for room ${this.roomId}`);
                    this.outboundSessions[session.sessionId] = session;
                }
                // now check if we need to share with any devices
                const shareMap = {};
                for (const [userId, userDevices] of Object.entries(devicesInRoom)) {
                    for (const [deviceId, deviceInfo] of Object.entries(userDevices)) {
                        const key = deviceInfo.getIdentityKey();
                        if (key == this.olmDevice.deviceCurve25519Key) {
                            // don't bother sending to ourself
                            continue;
                        }
                        if (!session.sharedWithDevices[userId] ||
                            session.sharedWithDevices[userId][deviceId] === undefined) {
                            shareMap[userId] = shareMap[userId] || [];
                            shareMap[userId].push(deviceInfo);
                        }
                    }
                }
                const key = this.olmDevice.getOutboundGroupSessionKey(session.sessionId);
                const payload = {
                    type: "m.room_key",
                    content: {
                        "algorithm": olmlib.MEGOLM_ALGORITHM,
                        "room_id": this.roomId,
                        "session_id": session.sessionId,
                        "session_key": key.key,
                        "chain_index": key.chain_index,
                        "org.matrix.msc3061.shared_history": sharedHistory,
                    },
                };
                const [devicesWithoutSession, olmSessions] = yield olmlib.getExistingOlmSessions(this.olmDevice, this.baseApis, shareMap);
                yield Promise.all([
                    (() => __awaiter(this, void 0, void 0, function* () {
                        // share keys with devices that we already have a session for
                        logger_1.logger.debug(`Sharing keys with existing Olm sessions in ${this.roomId}`);
                        yield this.shareKeyWithOlmSessions(session, key, payload, olmSessions);
                        logger_1.logger.debug(`Shared keys with existing Olm sessions in ${this.roomId}`);
                    }))(),
                    (() => __awaiter(this, void 0, void 0, function* () {
                        logger_1.logger.debug(`Sharing keys (start phase 1) with new Olm sessions in ${this.roomId}`);
                        const errorDevices = [];
                        // meanwhile, establish olm sessions for devices that we don't
                        // already have a session for, and share keys with them.  If
                        // we're doing two phases of olm session creation, use a
                        // shorter timeout when fetching one-time keys for the first
                        // phase.
                        const start = Date.now();
                        const failedServers = [];
                        yield this.shareKeyWithDevices(session, key, payload, devicesWithoutSession, errorDevices, singleOlmCreationPhase ? 10000 : 2000, failedServers);
                        logger_1.logger.debug(`Shared keys (end phase 1) with new Olm sessions in ${this.roomId}`);
                        if (!singleOlmCreationPhase && (Date.now() - start < 10000)) {
                            // perform the second phase of olm session creation if requested,
                            // and if the first phase didn't take too long
                            (() => __awaiter(this, void 0, void 0, function* () {
                                // Retry sending keys to devices that we were unable to establish
                                // an olm session for.  This time, we use a longer timeout, but we
                                // do this in the background and don't block anything else while we
                                // do this.  We only need to retry users from servers that didn't
                                // respond the first time.
                                const retryDevices = {};
                                const failedServerMap = new Set;
                                for (const server of failedServers) {
                                    failedServerMap.add(server);
                                }
                                const failedDevices = [];
                                for (const { userId, deviceInfo } of errorDevices) {
                                    const userHS = userId.slice(userId.indexOf(":") + 1);
                                    if (failedServerMap.has(userHS)) {
                                        retryDevices[userId] = retryDevices[userId] || [];
                                        retryDevices[userId].push(deviceInfo);
                                    }
                                    else {
                                        // if we aren't going to retry, then handle it
                                        // as a failed device
                                        failedDevices.push({ userId, deviceInfo });
                                    }
                                }
                                logger_1.logger.debug(`Sharing keys (start phase 2) with new Olm sessions in ${this.roomId}`);
                                yield this.shareKeyWithDevices(session, key, payload, retryDevices, failedDevices, 30000);
                                logger_1.logger.debug(`Shared keys (end phase 2) with new Olm sessions in ${this.roomId}`);
                                yield this.notifyFailedOlmDevices(session, key, failedDevices);
                            }))();
                        }
                        else {
                            yield this.notifyFailedOlmDevices(session, key, errorDevices);
                        }
                        logger_1.logger.debug(`Shared keys (all phases done) with new Olm sessions in ${this.roomId}`);
                    }))(),
                    (() => __awaiter(this, void 0, void 0, function* () {
                        logger_1.logger.debug(`Notifying blocked devices in ${this.roomId}`);
                        // also, notify blocked devices that they're blocked
                        const blockedMap = {};
                        let blockedCount = 0;
                        for (const [userId, userBlockedDevices] of Object.entries(blocked)) {
                            for (const [deviceId, device] of Object.entries(userBlockedDevices)) {
                                if (!session.blockedDevicesNotified[userId] ||
                                    session.blockedDevicesNotified[userId][deviceId] === undefined) {
                                    blockedMap[userId] = blockedMap[userId] || {};
                                    blockedMap[userId][deviceId] = { device };
                                    blockedCount++;
                                }
                            }
                        }
                        yield this.notifyBlockedDevices(session, blockedMap);
                        logger_1.logger.debug(`Notified ${blockedCount} blocked devices in ${this.roomId}`);
                    }))(),
                ]);
            });
            // helper which returns the session prepared by prepareSession
            function returnSession() {
                return session;
            }
            // first wait for the previous share to complete
            const prom = this.setupPromise.then(prepareSession);
            // Ensure any failures are logged for debugging
            prom.catch(e => {
                logger_1.logger.error(`Failed to ensure outbound session in ${this.roomId}`, e);
            });
            // setupPromise resolves to `session` whether or not the share succeeds
            this.setupPromise = prom.then(returnSession, returnSession);
            // but we return a promise which only resolves if the share was successful.
            return prom.then(returnSession);
        });
    }
    /**
     * @private
     *
     * @param {boolean} sharedHistory
     *
     * @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     */
    prepareNewSession(sharedHistory) {
        return __awaiter(this, void 0, void 0, function* () {
            const sessionId = this.olmDevice.createOutboundGroupSession();
            const key = this.olmDevice.getOutboundGroupSessionKey(sessionId);
            yield this.olmDevice.addInboundGroupSession(this.roomId, this.olmDevice.deviceCurve25519Key, [], sessionId, key.key, { ed25519: this.olmDevice.deviceEd25519Key }, false, { sharedHistory });
            // don't wait for it to complete
            this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key, sessionId);
            return new OutboundSessionInfo(sessionId, sharedHistory);
        });
    }
    /**
     * Determines what devices in devicesByUser don't have an olm session as given
     * in devicemap.
     *
     * @private
     *
     * @param {object} devicemap the devices that have olm sessions, as returned by
     *     olmlib.ensureOlmSessionsForDevices.
     * @param {object} devicesByUser a map of user IDs to array of deviceInfo
     * @param {array} [noOlmDevices] an array to fill with devices that don't have
     *     olm sessions
     *
     * @return {array} an array of devices that don't have olm sessions.  If
     *     noOlmDevices is specified, then noOlmDevices will be returned.
     */
    getDevicesWithoutSessions(devicemap, devicesByUser, noOlmDevices = []) {
        for (const [userId, devicesToShareWith] of Object.entries(devicesByUser)) {
            const sessionResults = devicemap[userId];
            for (const deviceInfo of devicesToShareWith) {
                const deviceId = deviceInfo.deviceId;
                const sessionResult = sessionResults[deviceId];
                if (!sessionResult.sessionId) {
                    // no session with this device, probably because there
                    // were no one-time keys.
                    noOlmDevices.push({ userId, deviceInfo });
                    delete sessionResults[deviceId];
                    // ensureOlmSessionsForUsers has already done the logging,
                    // so just skip it.
                    continue;
                }
            }
        }
        return noOlmDevices;
    }
    /**
     * Splits the user device map into multiple chunks to reduce the number of
     * devices we encrypt to per API call.
     *
     * @private
     *
     * @param {object} devicesByUser map from userid to list of devices
     *
     * @return {array<array<object>>} the blocked devices, split into chunks
     */
    splitDevices(devicesByUser) {
        const maxDevicesPerRequest = 20;
        // use an array where the slices of a content map gets stored
        let currentSlice = [];
        const mapSlices = [currentSlice];
        for (const [userId, userDevices] of Object.entries(devicesByUser)) {
            for (const deviceInfo of Object.values(userDevices)) {
                currentSlice.push({
                    userId: userId,
                    deviceInfo: deviceInfo.device,
                });
            }
            // We do this in the per-user loop as we prefer that all messages to the
            // same user end up in the same API call to make it easier for the
            // server (e.g. only have to send one EDU if a remote user, etc). This
            // does mean that if a user has many devices we may go over the desired
            // limit, but its not a hard limit so that is fine.
            if (currentSlice.length > maxDevicesPerRequest) {
                // the current slice is filled up. Start inserting into the next slice
                currentSlice = [];
                mapSlices.push(currentSlice);
            }
        }
        if (currentSlice.length === 0) {
            mapSlices.pop();
        }
        return mapSlices;
    }
    /**
     * @private
     *
     * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     *
     * @param {number} chainIndex current chain index
     *
     * @param {object<userId, deviceInfo>} userDeviceMap
     *   mapping from userId to deviceInfo
     *
     * @param {object} payload fields to include in the encrypted payload
     *
     * @return {Promise} Promise which resolves once the key sharing
     *     for the given userDeviceMap is generated and has been sent.
     */
    encryptAndSendKeysToDevices(session, chainIndex, userDeviceMap, payload) {
        const contentMap = {};
        const promises = [];
        for (let i = 0; i < userDeviceMap.length; i++) {
            const encryptedContent = {
                algorithm: olmlib.OLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: {},
            };
            const val = userDeviceMap[i];
            const userId = val.userId;
            const deviceInfo = val.deviceInfo;
            const deviceId = deviceInfo.deviceId;
            if (!contentMap[userId]) {
                contentMap[userId] = {};
            }
            contentMap[userId][deviceId] = encryptedContent;
            promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, deviceInfo, payload));
        }
        return Promise.all(promises).then(() => {
            // prune out any devices that encryptMessageForDevice could not encrypt for,
            // in which case it will have just not added anything to the ciphertext object.
            // There's no point sending messages to devices if we couldn't encrypt to them,
            // since that's effectively a blank message.
            for (const userId of Object.keys(contentMap)) {
                for (const deviceId of Object.keys(contentMap[userId])) {
                    if (Object.keys(contentMap[userId][deviceId].ciphertext).length === 0) {
                        logger_1.logger.log("No ciphertext for device " +
                            userId + ":" + deviceId + ": pruning");
                        delete contentMap[userId][deviceId];
                    }
                }
                // No devices left for that user? Strip that too.
                if (Object.keys(contentMap[userId]).length === 0) {
                    logger_1.logger.log("Pruned all devices for user " + userId);
                    delete contentMap[userId];
                }
            }
            // Is there anything left?
            if (Object.keys(contentMap).length === 0) {
                logger_1.logger.log("No users left to send to: aborting");
                return;
            }
            return this.baseApis.sendToDevice("m.room.encrypted", contentMap).then(() => {
                // store that we successfully uploaded the keys of the current slice
                for (const userId of Object.keys(contentMap)) {
                    for (const deviceId of Object.keys(contentMap[userId])) {
                        session.markSharedWithDevice(userId, deviceId, chainIndex);
                    }
                }
            });
        });
    }
    /**
     * @private
     *
     * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     *
     * @param {array<object>} userDeviceMap list of blocked devices to notify
     *
     * @param {object} payload fields to include in the notification payload
     *
     * @return {Promise} Promise which resolves once the notifications
     *     for the given userDeviceMap is generated and has been sent.
     */
    sendBlockedNotificationsToDevices(session, userDeviceMap, payload) {
        return __awaiter(this, void 0, void 0, function* () {
            const contentMap = {};
            for (const val of userDeviceMap) {
                const userId = val.userId;
                const blockedInfo = val.deviceInfo;
                const deviceInfo = blockedInfo.deviceInfo;
                const deviceId = deviceInfo.deviceId;
                const message = Object.assign({}, payload);
                message.code = blockedInfo.code;
                message.reason = blockedInfo.reason;
                if (message.code === "m.no_olm") {
                    delete message.room_id;
                    delete message.session_id;
                }
                if (!contentMap[userId]) {
                    contentMap[userId] = {};
                }
                contentMap[userId][deviceId] = message;
            }
            yield this.baseApis.sendToDevice("org.matrix.room_key.withheld", contentMap);
            // store that we successfully uploaded the keys of the current slice
            for (const userId of Object.keys(contentMap)) {
                for (const deviceId of Object.keys(contentMap[userId])) {
                    session.markNotifiedBlockedDevice(userId, deviceId);
                }
            }
        });
    }
    /**
     * Re-shares a megolm session key with devices if the key has already been
     * sent to them.
     *
     * @param {string} senderKey The key of the originating device for the session
     * @param {string} sessionId ID of the outbound session to share
     * @param {string} userId ID of the user who owns the target device
     * @param {module:crypto/deviceinfo} device The target device
     */
    reshareKeyWithDevice(senderKey, sessionId, userId, device) {
        return __awaiter(this, void 0, void 0, function* () {
            const obSessionInfo = this.outboundSessions[sessionId];
            if (!obSessionInfo) {
                logger_1.logger.debug(`megolm session ${sessionId} not found: not re-sharing keys`);
                return;
            }
            // The chain index of the key we previously sent this device
            if (obSessionInfo.sharedWithDevices[userId] === undefined) {
                logger_1.logger.debug(`megolm session ${sessionId} never shared with user ${userId}`);
                return;
            }
            const sentChainIndex = obSessionInfo.sharedWithDevices[userId][device.deviceId];
            if (sentChainIndex === undefined) {
                logger_1.logger.debug("megolm session ID " + sessionId + " never shared with device " +
                    userId + ":" + device.deviceId);
                return;
            }
            // get the key from the inbound session: the outbound one will already
            // have been ratcheted to the next chain index.
            const key = yield this.olmDevice.getInboundGroupSessionKey(this.roomId, senderKey, sessionId, sentChainIndex);
            if (!key) {
                logger_1.logger.warn(`No inbound session key found for megolm ${sessionId}: not re-sharing keys`);
                return;
            }
            yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, {
                [userId]: [device],
            });
            const payload = {
                type: "m.forwarded_room_key",
                content: {
                    "algorithm": olmlib.MEGOLM_ALGORITHM,
                    "room_id": this.roomId,
                    "session_id": sessionId,
                    "session_key": key.key,
                    "chain_index": key.chain_index,
                    "sender_key": senderKey,
                    "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
                    "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
                    "org.matrix.msc3061.shared_history": key.shared_history || false,
                },
            };
            const encryptedContent = {
                algorithm: olmlib.OLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: {},
            };
            yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, device, payload);
            yield this.baseApis.sendToDevice("m.room.encrypted", {
                [userId]: {
                    [device.deviceId]: encryptedContent,
                },
            });
            logger_1.logger.debug(`Re-shared key for megolm session ${sessionId} with ${userId}:${device.deviceId}`);
        });
    }
    /**
     * @private
     *
     * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     *
     * @param {object} key the session key as returned by
     *    OlmDevice.getOutboundGroupSessionKey
     *
     * @param {object} payload the base to-device message payload for sharing keys
     *
     * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser
     *    map from userid to list of devices
     *
     * @param {array<object>} errorDevices
     *    array that will be populated with the devices that we can't get an
     *    olm session for
     *
     * @param {Number} [otkTimeout] The timeout in milliseconds when requesting
     *     one-time keys for establishing new olm sessions.
     *
     * @param {Array} [failedServers] An array to fill with remote servers that
     *     failed to respond to one-time-key requests.
     */
    shareKeyWithDevices(session, key, payload, devicesByUser, errorDevices, otkTimeout, failedServers) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug(`Ensuring Olm sessions for devices in ${this.roomId}`);
            const devicemap = yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, false, otkTimeout, failedServers, logger_1.logger.withPrefix(`[${this.roomId}]`));
            logger_1.logger.debug(`Ensured Olm sessions for devices in ${this.roomId}`);
            this.getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices);
            logger_1.logger.debug(`Sharing keys with Olm sessions in ${this.roomId}`);
            yield this.shareKeyWithOlmSessions(session, key, payload, devicemap);
            logger_1.logger.debug(`Shared keys with Olm sessions in ${this.roomId}`);
        });
    }
    shareKeyWithOlmSessions(session, key, payload, devicemap) {
        return __awaiter(this, void 0, void 0, function* () {
            const userDeviceMaps = this.splitDevices(devicemap);
            for (let i = 0; i < userDeviceMaps.length; i++) {
                const taskDetail = `megolm keys for ${session.sessionId} ` +
                    `in ${this.roomId} (slice ${i + 1}/${userDeviceMaps.length})`;
                try {
                    logger_1.logger.debug(`Sharing ${taskDetail}`);
                    yield this.encryptAndSendKeysToDevices(session, key.chain_index, userDeviceMaps[i], payload);
                    logger_1.logger.debug(`Shared ${taskDetail}`);
                }
                catch (e) {
                    logger_1.logger.error(`Failed to share ${taskDetail}`);
                    throw e;
                }
            }
        });
    }
    /**
     * Notify devices that we weren't able to create olm sessions.
     *
     * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     *
     * @param {object} key
     *
     * @param {Array<object>} failedDevices the devices that we were unable to
     *     create olm sessions for, as returned by shareKeyWithDevices
     */
    notifyFailedOlmDevices(session, key, failedDevices) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug(`Notifying ${failedDevices.length} devices we failed to ` +
                `create Olm sessions in ${this.roomId}`);
            // mark the devices that failed as "handled" because we don't want to try
            // to claim a one-time-key for dead devices on every message.
            for (const { userId, deviceInfo } of failedDevices) {
                const deviceId = deviceInfo.deviceId;
                session.markSharedWithDevice(userId, deviceId, key.chain_index);
            }
            const filteredFailedDevices = yield this.olmDevice.filterOutNotifiedErrorDevices(failedDevices);
            logger_1.logger.debug(`Filtered down to ${filteredFailedDevices.length} error devices ` +
                `in ${this.roomId}`);
            const blockedMap = {};
            for (const { userId, deviceInfo } of filteredFailedDevices) {
                blockedMap[userId] = blockedMap[userId] || {};
                // we use a similar format to what
                // olmlib.ensureOlmSessionsForDevices returns, so that
                // we can use the same function to split
                blockedMap[userId][deviceInfo.deviceId] = {
                    device: {
                        code: "m.no_olm",
                        reason: OlmDevice_1.WITHHELD_MESSAGES["m.no_olm"],
                        deviceInfo,
                    },
                };
            }
            // send the notifications
            yield this.notifyBlockedDevices(session, blockedMap);
            logger_1.logger.debug(`Notified ${filteredFailedDevices.length} devices we failed to ` +
                `create Olm sessions in ${this.roomId}`);
        });
    }
    /**
     * Notify blocked devices that they have been blocked.
     *
     * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session
     *
     * @param {object<string, object>} devicesByUser
     *    map from userid to device ID to blocked data
     */
    notifyBlockedDevices(session, devicesByUser) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = {
                room_id: this.roomId,
                session_id: session.sessionId,
                algorithm: olmlib.MEGOLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
            };
            const userDeviceMaps = this.splitDevices(devicesByUser);
            for (let i = 0; i < userDeviceMaps.length; i++) {
                try {
                    yield this.sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload);
                    logger_1.logger.log(`Completed blacklist notification for ${session.sessionId} `
                        + `in ${this.roomId} (slice ${i + 1}/${userDeviceMaps.length})`);
                }
                catch (e) {
                    logger_1.logger.log(`blacklist notification for ${session.sessionId} in `
                        + `${this.roomId} (slice ${i + 1}/${userDeviceMaps.length}) failed`);
                    throw e;
                }
            }
        });
    }
    /**
     * Perform any background tasks that can be done before a message is ready to
     * send, in order to speed up sending of the message.
     *
     * @param {module:models/room} room the room the event is in
     */
    prepareToEncrypt(room) {
        if (this.encryptionPreparation) {
            // We're already preparing something, so don't do anything else.
            // FIXME: check if we need to restart
            // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)
            const elapsedTime = Date.now() - this.encryptionPreparationMetadata.startTime;
            logger_1.logger.debug(`Already started preparing to encrypt for ${this.roomId} ` +
                `${elapsedTime} ms ago, skipping`);
            return;
        }
        logger_1.logger.debug(`Preparing to encrypt events for ${this.roomId}`);
        this.encryptionPreparationMetadata = {
            startTime: Date.now(),
        };
        this.encryptionPreparation = (() => __awaiter(this, void 0, void 0, function* () {
            try {
                logger_1.logger.debug(`Getting devices in ${this.roomId}`);
                const [devicesInRoom, blocked] = yield this.getDevicesInRoom(room);
                if (this.crypto.getGlobalErrorOnUnknownDevices()) {
                    // Drop unknown devices for now.  When the message gets sent, we'll
                    // throw an error, but we'll still be prepared to send to the known
                    // devices.
                    this.removeUnknownDevices(devicesInRoom);
                }
                logger_1.logger.debug(`Ensuring outbound session in ${this.roomId}`);
                yield this.ensureOutboundSession(room, devicesInRoom, blocked, true);
                logger_1.logger.debug(`Ready to encrypt events for ${this.roomId}`);
            }
            catch (e) {
                logger_1.logger.error(`Failed to prepare to encrypt events for ${this.roomId}`, e);
            }
            finally {
                delete this.encryptionPreparationMetadata;
                delete this.encryptionPreparation;
            }
        }))();
    }
    /**
     * @inheritdoc
     *
     * @param {module:models/room} room
     * @param {string} eventType
     * @param {object} content plaintext event content
     *
     * @return {Promise} Promise which resolves to the new event body
     */
    encryptMessage(room, eventType, content) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log(`Starting to encrypt event for ${this.roomId}`);
            if (this.encryptionPreparation) {
                // If we started sending keys, wait for it to be done.
                // FIXME: check if we need to cancel
                // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)
                try {
                    yield this.encryptionPreparation;
                }
                catch (e) {
                    // ignore any errors -- if the preparation failed, we'll just
                    // restart everything here
                }
            }
            const [devicesInRoom, blocked] = yield this.getDevicesInRoom(room);
            // check if any of these devices are not yet known to the user.
            // if so, warn the user so they can verify or ignore.
            if (this.crypto.getGlobalErrorOnUnknownDevices()) {
                this.checkForUnknownDevices(devicesInRoom);
            }
            const session = yield this.ensureOutboundSession(room, devicesInRoom, blocked);
            const payloadJson = {
                room_id: this.roomId,
                type: eventType,
                content: content,
            };
            const ciphertext = this.olmDevice.encryptGroupMessage(session.sessionId, JSON.stringify(payloadJson));
            const encryptedContent = {
                algorithm: olmlib.MEGOLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: ciphertext,
                session_id: session.sessionId,
                // Include our device ID so that recipients can send us a
                // m.new_device message if they don't have our session key.
                // XXX: Do we still need this now that m.new_device messages
                // no longer exist since #483?
                device_id: this.deviceId,
            };
            session.useCount++;
            return encryptedContent;
        });
    }
    /**
     * Forces the current outbound group session to be discarded such
     * that another one will be created next time an event is sent.
     *
     * This should not normally be necessary.
     */
    forceDiscardSession() {
        this.setupPromise = this.setupPromise.then(() => null);
    }
    /**
     * Checks the devices we're about to send to and see if any are entirely
     * unknown to the user.  If so, warn the user, and mark them as known to
     * give the user a chance to go verify them before re-sending this message.
     *
     * @param {Object} devicesInRoom userId -> {deviceId -> object}
     *   devices we should shared the session with.
     */
    checkForUnknownDevices(devicesInRoom) {
        const unknownDevices = {};
        Object.keys(devicesInRoom).forEach((userId) => {
            Object.keys(devicesInRoom[userId]).forEach((deviceId) => {
                const device = devicesInRoom[userId][deviceId];
                if (device.isUnverified() && !device.isKnown()) {
                    if (!unknownDevices[userId]) {
                        unknownDevices[userId] = {};
                    }
                    unknownDevices[userId][deviceId] = device;
                }
            });
        });
        if (Object.keys(unknownDevices).length) {
            // it'd be kind to pass unknownDevices up to the user in this error
            throw new base_1.UnknownDeviceError("This room contains unknown devices which have not been verified. " +
                "We strongly recommend you verify them before continuing.", unknownDevices);
        }
    }
    /**
     * Remove unknown devices from a set of devices.  The devicesInRoom parameter
     * will be modified.
     *
     * @param {Object} devicesInRoom userId -> {deviceId -> object}
     *   devices we should shared the session with.
     */
    removeUnknownDevices(devicesInRoom) {
        for (const [userId, userDevices] of Object.entries(devicesInRoom)) {
            for (const [deviceId, device] of Object.entries(userDevices)) {
                if (device.isUnverified() && !device.isKnown()) {
                    delete userDevices[deviceId];
                }
            }
            if (Object.keys(userDevices).length === 0) {
                delete devicesInRoom[userId];
            }
        }
    }
    /**
     * Get the list of unblocked devices for all users in the room
     *
     * @param {module:models/room} room
     *
     * @return {Promise} Promise which resolves to an array whose
     *     first element is a map from userId to deviceId to deviceInfo indicating
     *     the devices that messages should be encrypted to, and whose second
     *     element is a map from userId to deviceId to data indicating the devices
     *     that are in the room but that have been blocked
     */
    getDevicesInRoom(room) {
        return __awaiter(this, void 0, void 0, function* () {
            const members = yield room.getEncryptionTargetMembers();
            const roomMembers = members.map(function (u) {
                return u.userId;
            });
            // The global value is treated as a default for when rooms don't specify a value.
            let isBlacklisting = this.crypto.getGlobalBlacklistUnverifiedDevices();
            if (typeof room.getBlacklistUnverifiedDevices() === 'boolean') {
                isBlacklisting = room.getBlacklistUnverifiedDevices();
            }
            // We are happy to use a cached version here: we assume that if we already
            // have a list of the user's devices, then we already share an e2e room
            // with them, which means that they will have announced any new devices via
            // device_lists in their /sync response.  This cache should then be maintained
            // using all the device_lists changes and left fields.
            // See https://github.com/vector-im/element-web/issues/2305 for details.
            const devices = yield this.crypto.downloadKeys(roomMembers, false);
            const blocked = {};
            // remove any blocked devices
            for (const userId in devices) {
                if (!devices.hasOwnProperty(userId)) {
                    continue;
                }
                const userDevices = devices[userId];
                for (const deviceId in userDevices) {
                    if (!userDevices.hasOwnProperty(deviceId)) {
                        continue;
                    }
                    const deviceTrust = this.crypto.checkDeviceTrust(userId, deviceId);
                    if (userDevices[deviceId].isBlocked() ||
                        (!deviceTrust.isVerified() && isBlacklisting)) {
                        if (!blocked[userId]) {
                            blocked[userId] = {};
                        }
                        const isBlocked = userDevices[deviceId].isBlocked();
                        blocked[userId][deviceId] = {
                            code: isBlocked ? "m.blacklisted" : "m.unverified",
                            reason: OlmDevice_1.WITHHELD_MESSAGES[isBlocked ? "m.blacklisted" : "m.unverified"],
                            deviceInfo: userDevices[deviceId],
                        };
                        delete userDevices[deviceId];
                    }
                }
            }
            return [devices, blocked];
        });
    }
}
/**
 * Megolm decryption implementation
 *
 * @constructor
 * @extends {module:crypto/algorithms/DecryptionAlgorithm}
 *
 * @param {object} params parameters, as per
 *     {@link module:crypto/algorithms/DecryptionAlgorithm}
 */
class MegolmDecryption extends base_1.DecryptionAlgorithm {
    constructor() {
        super(...arguments);
        // events which we couldn't decrypt due to unknown sessions / indexes: map from
        // senderKey|sessionId to Set of MatrixEvents
        this.pendingEvents = {};
        // this gets stubbed out by the unit tests.
        this.olmlib = olmlib;
    }
    /**
     * @inheritdoc
     *
     * @param {MatrixEvent} event
     *
     * returns a promise which resolves to a
     * {@link module:crypto~EventDecryptionResult} once we have finished
     * decrypting, or rejects with an `algorithms.DecryptionError` if there is a
     * problem decrypting the event.
     */
    decryptEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const content = event.getWireContent();
            if (!content.sender_key || !content.session_id ||
                !content.ciphertext) {
                throw new base_1.DecryptionError("MEGOLM_MISSING_FIELDS", "Missing fields in input");
            }
            // we add the event to the pending list *before* we start decryption.
            //
            // then, if the key turns up while decryption is in progress (and
            // decryption fails), we will schedule a retry.
            // (fixes https://github.com/vector-im/element-web/issues/5001)
            this.addEventToPendingList(event);
            let res;
            try {
                res = yield this.olmDevice.decryptGroupMessage(event.getRoomId(), content.sender_key, content.session_id, content.ciphertext, event.getId(), event.getTs());
            }
            catch (e) {
                if (e.name === "DecryptionError") {
                    // re-throw decryption errors as-is
                    throw e;
                }
                let errorCode = "OLM_DECRYPT_GROUP_MESSAGE_ERROR";
                if (e && e.message === 'OLM.UNKNOWN_MESSAGE_INDEX') {
                    this.requestKeysForEvent(event);
                    errorCode = 'OLM_UNKNOWN_MESSAGE_INDEX';
                }
                throw new base_1.DecryptionError(errorCode, e ? e.toString() : "Unknown Error: Error is undefined", {
                    session: content.sender_key + '|' + content.session_id,
                });
            }
            if (res === null) {
                // We've got a message for a session we don't have.
                //
                // (XXX: We might actually have received this key since we started
                // decrypting, in which case we'll have scheduled a retry, and this
                // request will be redundant. We could probably check to see if the
                // event is still in the pending list; if not, a retry will have been
                // scheduled, so we needn't send out the request here.)
                this.requestKeysForEvent(event);
                // See if there was a problem with the olm session at the time the
                // event was sent.  Use a fuzz factor of 2 minutes.
                const problem = yield this.olmDevice.sessionMayHaveProblems(content.sender_key, event.getTs() - 120000);
                if (problem) {
                    let problemDescription = PROBLEM_DESCRIPTIONS[problem.type]
                        || PROBLEM_DESCRIPTIONS.unknown;
                    if (problem.fixed) {
                        problemDescription +=
                            " Trying to create a new secure channel and re-requesting the keys.";
                    }
                    throw new base_1.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", problemDescription, {
                        session: content.sender_key + '|' + content.session_id,
                    });
                }
                throw new base_1.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", "The sender's device has not sent us the keys for this message.", {
                    session: content.sender_key + '|' + content.session_id,
                });
            }
            // success. We can remove the event from the pending list, if that hasn't
            // already happened.
            this.removeEventFromPendingList(event);
            const payload = JSON.parse(res.result);
            // belt-and-braces check that the room id matches that indicated by the HS
            // (this is somewhat redundant, since the megolm session is scoped to the
            // room, so neither the sender nor a MITM can lie about the room_id).
            if (payload.room_id !== event.getRoomId()) {
                throw new base_1.DecryptionError("MEGOLM_BAD_ROOM", "Message intended for room " + payload.room_id);
            }
            return {
                clearEvent: payload,
                senderCurve25519Key: res.senderKey,
                claimedEd25519Key: res.keysClaimed.ed25519,
                forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain,
                untrusted: res.untrusted,
            };
        });
    }
    requestKeysForEvent(event) {
        const wireContent = event.getWireContent();
        const recipients = event.getKeyRequestRecipients(this.userId);
        this.crypto.requestRoomKey({
            room_id: event.getRoomId(),
            algorithm: wireContent.algorithm,
            sender_key: wireContent.sender_key,
            session_id: wireContent.session_id,
        }, recipients);
    }
    /**
     * Add an event to the list of those awaiting their session keys.
     *
     * @private
     *
     * @param {module:models/event.MatrixEvent} event
     */
    addEventToPendingList(event) {
        const content = event.getWireContent();
        const senderKey = content.sender_key;
        const sessionId = content.session_id;
        if (!this.pendingEvents[senderKey]) {
            this.pendingEvents[senderKey] = new Map();
        }
        const senderPendingEvents = this.pendingEvents[senderKey];
        if (!senderPendingEvents.has(sessionId)) {
            senderPendingEvents.set(sessionId, new Set());
        }
        senderPendingEvents.get(sessionId).add(event);
    }
    /**
     * Remove an event from the list of those awaiting their session keys.
     *
     * @private
     *
     * @param {module:models/event.MatrixEvent} event
     */
    removeEventFromPendingList(event) {
        const content = event.getWireContent();
        const senderKey = content.sender_key;
        const sessionId = content.session_id;
        const senderPendingEvents = this.pendingEvents[senderKey];
        const pendingEvents = senderPendingEvents && senderPendingEvents.get(sessionId);
        if (!pendingEvents) {
            return;
        }
        pendingEvents.delete(event);
        if (pendingEvents.size === 0) {
            senderPendingEvents.delete(senderKey);
        }
        if (senderPendingEvents.size === 0) {
            delete this.pendingEvents[senderKey];
        }
    }
    /**
     * @inheritdoc
     *
     * @param {module:models/event.MatrixEvent} event key event
     */
    onRoomKeyEvent(event) {
        const content = event.getContent();
        const sessionId = content.session_id;
        let senderKey = event.getSenderKey();
        let forwardingKeyChain = [];
        let exportFormat = false;
        let keysClaimed;
        if (!content.room_id ||
            !sessionId ||
            !content.session_key) {
            logger_1.logger.error("key event is missing fields");
            return;
        }
        if (!senderKey) {
            logger_1.logger.error("key event has no sender key (not encrypted?)");
            return;
        }
        if (event.getType() == "m.forwarded_room_key") {
            exportFormat = true;
            forwardingKeyChain = content.forwarding_curve25519_key_chain;
            if (!Array.isArray(forwardingKeyChain)) {
                forwardingKeyChain = [];
            }
            // copy content before we modify it
            forwardingKeyChain = forwardingKeyChain.slice();
            forwardingKeyChain.push(senderKey);
            senderKey = content.sender_key;
            if (!senderKey) {
                logger_1.logger.error("forwarded_room_key event is missing sender_key field");
                return;
            }
            const ed25519Key = content.sender_claimed_ed25519_key;
            if (!ed25519Key) {
                logger_1.logger.error(`forwarded_room_key_event is missing sender_claimed_ed25519_key field`);
                return;
            }
            keysClaimed = {
                ed25519: ed25519Key,
            };
        }
        else {
            keysClaimed = event.getKeysClaimed();
        }
        const extraSessionData = {};
        if (content["org.matrix.msc3061.shared_history"]) {
            extraSessionData.sharedHistory = true;
        }
        return this.olmDevice.addInboundGroupSession(content.room_id, senderKey, forwardingKeyChain, sessionId, content.session_key, keysClaimed, exportFormat, extraSessionData).then(() => {
            // have another go at decrypting events sent with this session.
            this.retryDecryption(senderKey, sessionId)
                .then((success) => {
                // cancel any outstanding room key requests for this session.
                // Only do this if we managed to decrypt every message in the
                // session, because if we didn't, we leave the other key
                // requests in the hopes that someone sends us a key that
                // includes an earlier index.
                if (success) {
                    this.crypto.cancelRoomKeyRequest({
                        algorithm: content.algorithm,
                        room_id: content.room_id,
                        session_id: content.session_id,
                        sender_key: senderKey,
                    });
                }
            });
        }).then(() => {
            // don't wait for the keys to be backed up for the server
            this.crypto.backupManager.backupGroupSession(senderKey, content.session_id);
        }).catch((e) => {
            logger_1.logger.error(`Error handling m.room_key_event: ${e}`);
        });
    }
    /**
     * @inheritdoc
     *
     * @param {module:models/event.MatrixEvent} event key event
     */
    onRoomKeyWithheldEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const content = event.getContent();
            const senderKey = content.sender_key;
            if (content.code === "m.no_olm") {
                const sender = event.getSender();
                logger_1.logger.warn(`${sender}:${senderKey} was unable to establish an olm session with us`);
                // if the sender says that they haven't been able to establish an olm
                // session, let's proactively establish one
                // Note: after we record that the olm session has had a problem, we
                // trigger retrying decryption for all the messages from the sender's
                // key, so that we can update the error message to indicate the olm
                // session problem.
                if (yield this.olmDevice.getSessionIdForDevice(senderKey)) {
                    // a session has already been established, so we don't need to
                    // create a new one.
                    logger_1.logger.debug("New session already created.  Not creating a new one.");
                    yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", true);
                    this.retryDecryptionFromSender(senderKey);
                    return;
                }
                let device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);
                if (!device) {
                    // if we don't know about the device, fetch the user's devices again
                    // and retry before giving up
                    yield this.crypto.downloadKeys([sender], false);
                    device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);
                    if (!device) {
                        logger_1.logger.info("Couldn't find device for identity key " + senderKey +
                            ": not establishing session");
                        yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", false);
                        this.retryDecryptionFromSender(senderKey);
                        return;
                    }
                }
                yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, { [sender]: [device] }, false);
                const encryptedContent = {
                    algorithm: olmlib.OLM_ALGORITHM,
                    sender_key: this.olmDevice.deviceCurve25519Key,
                    ciphertext: {},
                };
                yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, sender, device, { type: "m.dummy" });
                yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", true);
                this.retryDecryptionFromSender(senderKey);
                yield this.baseApis.sendToDevice("m.room.encrypted", {
                    [sender]: {
                        [device.deviceId]: encryptedContent,
                    },
                });
            }
            else {
                yield this.olmDevice.addInboundGroupSessionWithheld(content.room_id, senderKey, content.session_id, content.code, content.reason);
            }
        });
    }
    /**
     * @inheritdoc
     */
    hasKeysForKeyRequest(keyRequest) {
        const body = keyRequest.requestBody;
        return this.olmDevice.hasInboundSessionKeys(body.room_id, body.sender_key, body.session_id);
    }
    /**
     * @inheritdoc
     */
    shareKeysWithDevice(keyRequest) {
        const userId = keyRequest.userId;
        const deviceId = keyRequest.deviceId;
        const deviceInfo = this.crypto.getStoredDevice(userId, deviceId);
        const body = keyRequest.requestBody;
        this.olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, {
            [userId]: [deviceInfo],
        }).then((devicemap) => {
            const olmSessionResult = devicemap[userId][deviceId];
            if (!olmSessionResult.sessionId) {
                // no session with this device, probably because there
                // were no one-time keys.
                //
                // ensureOlmSessionsForUsers has already done the logging,
                // so just skip it.
                return null;
            }
            logger_1.logger.log("sharing keys for session " + body.sender_key + "|"
                + body.session_id + " with device "
                + userId + ":" + deviceId);
            return this.buildKeyForwardingMessage(body.room_id, body.sender_key, body.session_id);
        }).then((payload) => {
            const encryptedContent = {
                algorithm: olmlib.OLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: {},
            };
            return this.olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, userId, deviceInfo, payload).then(() => {
                const contentMap = {
                    [userId]: {
                        [deviceId]: encryptedContent,
                    },
                };
                // TODO: retries
                return this.baseApis.sendToDevice("m.room.encrypted", contentMap);
            });
        });
    }
    buildKeyForwardingMessage(roomId, senderKey, sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            const key = yield this.olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId);
            return {
                type: "m.forwarded_room_key",
                content: {
                    "algorithm": olmlib.MEGOLM_ALGORITHM,
                    "room_id": roomId,
                    "sender_key": senderKey,
                    "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
                    "session_id": sessionId,
                    "session_key": key.key,
                    "chain_index": key.chain_index,
                    "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
                    "org.matrix.msc3061.shared_history": key.shared_history || false,
                },
            };
        });
    }
    /**
     * @inheritdoc
     *
     * @param {module:crypto/OlmDevice.MegolmSessionData} session
     * @param {object} [opts={}] options for the import
     * @param {boolean} [opts.untrusted] whether the key should be considered as untrusted
     * @param {string} [opts.source] where the key came from
     */
    importRoomKey(session, opts = {}) {
        const extraSessionData = {};
        if (opts.untrusted || session.untrusted) {
            extraSessionData.untrusted = true;
        }
        if (session["org.matrix.msc3061.shared_history"]) {
            extraSessionData.sharedHistory = true;
        }
        return this.olmDevice.addInboundGroupSession(session.room_id, session.sender_key, session.forwarding_curve25519_key_chain, session.session_id, session.session_key, session.sender_claimed_keys, true, extraSessionData).then(() => {
            if (opts.source !== "backup") {
                // don't wait for it to complete
                this.crypto.backupManager.backupGroupSession(session.sender_key, session.session_id).catch((e) => {
                    // This throws if the upload failed, but this is fine
                    // since it will have written it to the db and will retry.
                    logger_1.logger.log("Failed to back up megolm session", e);
                });
            }
            // have another go at decrypting events sent with this session.
            this.retryDecryption(session.sender_key, session.session_id);
        });
    }
    /**
     * Have another go at decrypting events after we receive a key. Resolves once
     * decryption has been re-attempted on all events.
     *
     * @private
     * @param {String} senderKey
     * @param {String} sessionId
     *
     * @return {Boolean} whether all messages were successfully decrypted
     */
    retryDecryption(senderKey, sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            const senderPendingEvents = this.pendingEvents[senderKey];
            if (!senderPendingEvents) {
                return true;
            }
            const pending = senderPendingEvents.get(sessionId);
            if (!pending) {
                return true;
            }
            logger_1.logger.debug("Retrying decryption on events", [...pending]);
            yield Promise.all([...pending].map((ev) => __awaiter(this, void 0, void 0, function* () {
                try {
                    yield ev.attemptDecryption(this.crypto, { isRetry: true });
                }
                catch (e) {
                    // don't die if something goes wrong
                }
            })));
            // If decrypted successfully, they'll have been removed from pendingEvents
            return !((this.pendingEvents[senderKey] || {})[sessionId]);
        });
    }
    retryDecryptionFromSender(senderKey) {
        return __awaiter(this, void 0, void 0, function* () {
            const senderPendingEvents = this.pendingEvents[senderKey];
            if (!senderPendingEvents) {
                return true;
            }
            delete this.pendingEvents[senderKey];
            yield Promise.all([...senderPendingEvents].map(([_sessionId, pending]) => __awaiter(this, void 0, void 0, function* () {
                yield Promise.all([...pending].map((ev) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        yield ev.attemptDecryption(this.crypto);
                    }
                    catch (e) {
                        // don't die if something goes wrong
                    }
                })));
            })));
            return !this.pendingEvents[senderKey];
        });
    }
    sendSharedHistoryInboundSessions(devicesByUser) {
        return __awaiter(this, void 0, void 0, function* () {
            yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser);
            logger_1.logger.log("sendSharedHistoryInboundSessions to users", Object.keys(devicesByUser));
            const sharedHistorySessions = yield this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);
            logger_1.logger.log("shared-history sessions", sharedHistorySessions);
            for (const [senderKey, sessionId] of sharedHistorySessions) {
                const payload = yield this.buildKeyForwardingMessage(this.roomId, senderKey, sessionId);
                const promises = [];
                const contentMap = {};
                for (const [userId, devices] of Object.entries(devicesByUser)) {
                    contentMap[userId] = {};
                    for (const deviceInfo of devices) {
                        const encryptedContent = {
                            algorithm: olmlib.OLM_ALGORITHM,
                            sender_key: this.olmDevice.deviceCurve25519Key,
                            ciphertext: {},
                        };
                        contentMap[userId][deviceInfo.deviceId] = encryptedContent;
                        promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, userId, deviceInfo, payload));
                    }
                }
                yield Promise.all(promises);
                // prune out any devices that encryptMessageForDevice could not encrypt for,
                // in which case it will have just not added anything to the ciphertext object.
                // There's no point sending messages to devices if we couldn't encrypt to them,
                // since that's effectively a blank message.
                for (const userId of Object.keys(contentMap)) {
                    for (const deviceId of Object.keys(contentMap[userId])) {
                        if (Object.keys(contentMap[userId][deviceId].ciphertext).length === 0) {
                            logger_1.logger.log("No ciphertext for device " +
                                userId + ":" + deviceId + ": pruning");
                            delete contentMap[userId][deviceId];
                        }
                    }
                    // No devices left for that user? Strip that too.
                    if (Object.keys(contentMap[userId]).length === 0) {
                        logger_1.logger.log("Pruned all devices for user " + userId);
                        delete contentMap[userId];
                    }
                }
                // Is there anything left?
                if (Object.keys(contentMap).length === 0) {
                    logger_1.logger.log("No users left to send to: aborting");
                    return;
                }
                yield this.baseApis.sendToDevice("m.room.encrypted", contentMap);
            }
        });
    }
}
const PROBLEM_DESCRIPTIONS = {
    no_olm: "The sender was unable to establish a secure channel.",
    unknown: "The secure channel with the sender was corrupted.",
};
base_1.registerAlgorithm(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption);

},{"../../logger":106,"../OlmDevice":70,"../olmlib":85,"./base":75}],78:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Defines m.olm encryption/decryption
 *
 * @module crypto/algorithms/olm
 */
const logger_1 = require("../../logger");
const olmlib = __importStar(require("../olmlib"));
const deviceinfo_1 = require("../deviceinfo");
const base_1 = require("./base");
const DeviceVerification = deviceinfo_1.DeviceInfo.DeviceVerification;
/**
 * Olm encryption implementation
 *
 * @constructor
 * @extends {module:crypto/algorithms/EncryptionAlgorithm}
 *
 * @param {object} params parameters, as per
 *     {@link module:crypto/algorithms/EncryptionAlgorithm}
 */
class OlmEncryption extends base_1.EncryptionAlgorithm {
    constructor() {
        super(...arguments);
        this.sessionPrepared = false;
        this.prepPromise = null;
    }
    /**
     * @private

     * @param {string[]} roomMembers list of currently-joined users in the room
     * @return {Promise} Promise which resolves when setup is complete
     */
    ensureSession(roomMembers) {
        if (this.prepPromise) {
            // prep already in progress
            return this.prepPromise;
        }
        if (this.sessionPrepared) {
            // prep already done
            return Promise.resolve();
        }
        this.prepPromise = this.crypto.downloadKeys(roomMembers).then((res) => {
            return this.crypto.ensureOlmSessionsForUsers(roomMembers);
        }).then(() => {
            this.sessionPrepared = true;
        }).finally(() => {
            this.prepPromise = null;
        });
        return this.prepPromise;
    }
    /**
     * @inheritdoc
     *
     * @param {module:models/room} room
     * @param {string} eventType
     * @param {object} content plaintext event content
     *
     * @return {Promise} Promise which resolves to the new event body
     */
    encryptMessage(room, eventType, content) {
        return __awaiter(this, void 0, void 0, function* () {
            // pick the list of recipients based on the membership list.
            //
            // TODO: there is a race condition here! What if a new user turns up
            // just as you are sending a secret message?
            const members = yield room.getEncryptionTargetMembers();
            const users = members.map(function (u) {
                return u.userId;
            });
            yield this.ensureSession(users);
            const payloadFields = {
                room_id: room.roomId,
                type: eventType,
                content: content,
            };
            const encryptedContent = {
                algorithm: olmlib.OLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: {},
            };
            const promises = [];
            for (let i = 0; i < users.length; ++i) {
                const userId = users[i];
                const devices = this.crypto.getStoredDevicesForUser(userId);
                for (let j = 0; j < devices.length; ++j) {
                    const deviceInfo = devices[j];
                    const key = deviceInfo.getIdentityKey();
                    if (key == this.olmDevice.deviceCurve25519Key) {
                        // don't bother sending to ourself
                        continue;
                    }
                    if (deviceInfo.verified == DeviceVerification.BLOCKED) {
                        // don't bother setting up sessions with blocked users
                        continue;
                    }
                    promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, deviceInfo, payloadFields));
                }
            }
            return yield Promise.all(promises).then(() => encryptedContent);
        });
    }
}
/**
 * Olm decryption implementation
 *
 * @constructor
 * @extends {module:crypto/algorithms/DecryptionAlgorithm}
 * @param {object} params parameters, as per
 *     {@link module:crypto/algorithms/DecryptionAlgorithm}
 */
class OlmDecryption extends base_1.DecryptionAlgorithm {
    /**
     * @inheritdoc
     *
     * @param {MatrixEvent} event
     *
     * returns a promise which resolves to a
     * {@link module:crypto~EventDecryptionResult} once we have finished
     * decrypting. Rejects with an `algorithms.DecryptionError` if there is a
     * problem decrypting the event.
     */
    decryptEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const content = event.getWireContent();
            const deviceKey = content.sender_key;
            const ciphertext = content.ciphertext;
            if (!ciphertext) {
                throw new base_1.DecryptionError("OLM_MISSING_CIPHERTEXT", "Missing ciphertext");
            }
            if (!(this.olmDevice.deviceCurve25519Key in ciphertext)) {
                throw new base_1.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS", "Not included in recipients");
            }
            const message = ciphertext[this.olmDevice.deviceCurve25519Key];
            let payloadString;
            try {
                payloadString = yield this.decryptMessage(deviceKey, message);
            }
            catch (e) {
                throw new base_1.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE", "Bad Encrypted Message", {
                    sender: deviceKey,
                    err: e,
                });
            }
            const payload = JSON.parse(payloadString);
            // check that we were the intended recipient, to avoid unknown-key attack
            // https://github.com/vector-im/vector-web/issues/2483
            if (payload.recipient != this.userId) {
                throw new base_1.DecryptionError("OLM_BAD_RECIPIENT", "Message was intented for " + payload.recipient);
            }
            if (payload.recipient_keys.ed25519 != this.olmDevice.deviceEd25519Key) {
                throw new base_1.DecryptionError("OLM_BAD_RECIPIENT_KEY", "Message not intended for this device", {
                    intended: payload.recipient_keys.ed25519,
                    our_key: this.olmDevice.deviceEd25519Key,
                });
            }
            // check that the original sender matches what the homeserver told us, to
            // avoid people masquerading as others.
            // (this check is also provided via the sender's embedded ed25519 key,
            // which is checked elsewhere).
            if (payload.sender != event.getSender()) {
                throw new base_1.DecryptionError("OLM_FORWARDED_MESSAGE", "Message forwarded from " + payload.sender, {
                    reported_sender: event.getSender(),
                });
            }
            // Olm events intended for a room have a room_id.
            if (payload.room_id !== event.getRoomId()) {
                throw new base_1.DecryptionError("OLM_BAD_ROOM", "Message intended for room " + payload.room_id, {
                    reported_room: event.getRoomId(),
                });
            }
            const claimedKeys = payload.keys || {};
            return {
                clearEvent: payload,
                senderCurve25519Key: deviceKey,
                claimedEd25519Key: claimedKeys.ed25519 || null,
            };
        });
    }
    /**
     * Attempt to decrypt an Olm message
     *
     * @param {string} theirDeviceIdentityKey  Curve25519 identity key of the sender
     * @param {object} message  message object, with 'type' and 'body' fields
     *
     * @return {string} payload, if decrypted successfully.
     */
    decryptMessage(theirDeviceIdentityKey, message) {
        return __awaiter(this, void 0, void 0, function* () {
            // This is a wrapper that serialises decryptions of prekey messages, because
            // otherwise we race between deciding we have no active sessions for the message
            // and creating a new one, which we can only do once because it removes the OTK.
            if (message.type !== 0) {
                // not a prekey message: we can safely just try & decrypt it
                return this.reallyDecryptMessage(theirDeviceIdentityKey, message);
            }
            else {
                const myPromise = this.olmDevice._olmPrekeyPromise.then(() => {
                    return this.reallyDecryptMessage(theirDeviceIdentityKey, message);
                });
                // we want the error, but don't propagate it to the next decryption
                this.olmDevice._olmPrekeyPromise = myPromise.catch(() => { });
                return yield myPromise;
            }
        });
    }
    reallyDecryptMessage(theirDeviceIdentityKey, message) {
        return __awaiter(this, void 0, void 0, function* () {
            const sessionIds = yield this.olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey);
            // try each session in turn.
            const decryptionErrors = {};
            for (let i = 0; i < sessionIds.length; i++) {
                const sessionId = sessionIds[i];
                try {
                    const payload = yield this.olmDevice.decryptMessage(theirDeviceIdentityKey, sessionId, message.type, message.body);
                    logger_1.logger.log("Decrypted Olm message from " + theirDeviceIdentityKey +
                        " with session " + sessionId);
                    return payload;
                }
                catch (e) {
                    const foundSession = yield this.olmDevice.matchesSession(theirDeviceIdentityKey, sessionId, message.type, message.body);
                    if (foundSession) {
                        // decryption failed, but it was a prekey message matching this
                        // session, so it should have worked.
                        throw new Error("Error decrypting prekey message with existing session id " +
                            sessionId + ": " + e.message);
                    }
                    // otherwise it's probably a message for another session; carry on, but
                    // keep a record of the error
                    decryptionErrors[sessionId] = e.message;
                }
            }
            if (message.type !== 0) {
                // not a prekey message, so it should have matched an existing session, but it
                // didn't work.
                if (sessionIds.length === 0) {
                    throw new Error("No existing sessions");
                }
                throw new Error("Error decrypting non-prekey message with existing sessions: " +
                    JSON.stringify(decryptionErrors));
            }
            // prekey message which doesn't match any existing sessions: make a new
            // session.
            let res;
            try {
                res = yield this.olmDevice.createInboundSession(theirDeviceIdentityKey, message.type, message.body);
            }
            catch (e) {
                decryptionErrors["(new)"] = e.message;
                throw new Error("Error decrypting prekey message: " +
                    JSON.stringify(decryptionErrors));
            }
            logger_1.logger.log("created new inbound Olm session ID " +
                res.session_id + " with " + theirDeviceIdentityKey);
            return res.payload;
        });
    }
}
base_1.registerAlgorithm(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption);

},{"../../logger":106,"../deviceinfo":82,"../olmlib":85,"./base":75}],79:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CrossSigningKey = void 0;
// TODO: Merge this with crypto.js once converted
var CrossSigningKey;
(function (CrossSigningKey) {
    CrossSigningKey["Master"] = "master";
    CrossSigningKey["SelfSigning"] = "self_signing";
    CrossSigningKey["UserSigning"] = "user_signing";
})(CrossSigningKey = exports.CrossSigningKey || (exports.CrossSigningKey = {}));

},{}],80:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultAlgorithm = exports.algorithmsByName = exports.Aes256 = exports.Curve25519 = exports.BackupManager = void 0;
/**
 * @module crypto/backup
 *
 * Classes for dealing with key backup.
 */
const client_1 = require("../client");
const logger_1 = require("../logger");
const olmlib_1 = require("./olmlib");
const key_passphrase_1 = require("./key_passphrase");
const utils_1 = require("../utils");
const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store");
const recoverykey_1 = require("./recoverykey");
const aes_1 = require("./aes");
const utils_2 = require("../utils");
const NamespacedValue_1 = require("../NamespacedValue");
const KEY_BACKUP_KEYS_PER_REQUEST = 200;
/**
 * Manages the key backup.
 */
class BackupManager {
    constructor(baseApis, getKey) {
        this.baseApis = baseApis;
        this.getKey = getKey;
        this.checkedForBackup = false;
        this.sendingBackups = false;
    }
    get version() {
        return this.backupInfo && this.backupInfo.version;
    }
    /**
     * Performs a quick check to ensure that the backup info looks sane.
     *
     * Throws an error if a problem is detected.
     *
     * @param {IKeyBackupInfo} info the key backup info
     */
    static checkBackupVersion(info) {
        const Algorithm = exports.algorithmsByName[info.algorithm];
        if (!Algorithm) {
            throw new Error("Unknown backup algorithm: " + info.algorithm);
        }
        if (!(typeof info.auth_data === "object")) {
            throw new Error("Invalid backup data returned");
        }
        return Algorithm.checkBackupVersion(info);
    }
    static makeAlgorithm(info, getKey) {
        return __awaiter(this, void 0, void 0, function* () {
            const Algorithm = exports.algorithmsByName[info.algorithm];
            if (!Algorithm) {
                throw new Error("Unknown backup algorithm");
            }
            return yield Algorithm.init(info.auth_data, getKey);
        });
    }
    enableKeyBackup(info) {
        return __awaiter(this, void 0, void 0, function* () {
            this.backupInfo = info;
            if (this.algorithm) {
                this.algorithm.free();
            }
            this.algorithm = yield BackupManager.makeAlgorithm(info, this.getKey);
            this.baseApis.emit('crypto.keyBackupStatus', true);
            // There may be keys left over from a partially completed backup, so
            // schedule a send to check.
            this.scheduleKeyBackupSend();
        });
    }
    /**
     * Disable backing up of keys.
     */
    disableKeyBackup() {
        if (this.algorithm) {
            this.algorithm.free();
        }
        this.algorithm = undefined;
        this.backupInfo = undefined;
        this.baseApis.emit('crypto.keyBackupStatus', false);
    }
    getKeyBackupEnabled() {
        if (!this.checkedForBackup) {
            return null;
        }
        return Boolean(this.algorithm);
    }
    prepareKeyBackupVersion(key, algorithm) {
        return __awaiter(this, void 0, void 0, function* () {
            const Algorithm = algorithm ? exports.algorithmsByName[algorithm] : exports.DefaultAlgorithm;
            if (!Algorithm) {
                throw new Error("Unknown backup algorithm");
            }
            const [privateKey, authData] = yield Algorithm.prepare(key);
            const recoveryKey = recoverykey_1.encodeRecoveryKey(privateKey);
            return {
                algorithm: Algorithm.algorithmName,
                auth_data: authData,
                recovery_key: recoveryKey,
                privateKey,
            };
        });
    }
    createKeyBackupVersion(info) {
        return __awaiter(this, void 0, void 0, function* () {
            this.algorithm = yield BackupManager.makeAlgorithm(info, this.getKey);
        });
    }
    /**
     * Check the server for an active key backup and
     * if one is present and has a valid signature from
     * one of the user's verified devices, start backing up
     * to it.
     */
    checkAndStart() {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log("Checking key backup status...");
            if (this.baseApis.isGuest()) {
                logger_1.logger.log("Skipping key backup check since user is guest");
                this.checkedForBackup = true;
                return null;
            }
            let backupInfo;
            try {
                backupInfo = yield this.baseApis.getKeyBackupVersion();
            }
            catch (e) {
                logger_1.logger.log("Error checking for active key backup", e);
                if (e.httpStatus === 404) {
                    // 404 is returned when the key backup does not exist, so that
                    // counts as successfully checking.
                    this.checkedForBackup = true;
                }
                return null;
            }
            this.checkedForBackup = true;
            const trustInfo = yield this.isKeyBackupTrusted(backupInfo);
            if (trustInfo.usable && !this.backupInfo) {
                logger_1.logger.log("Found usable key backup v" + backupInfo.version +
                    ": enabling key backups");
                yield this.enableKeyBackup(backupInfo);
            }
            else if (!trustInfo.usable && this.backupInfo) {
                logger_1.logger.log("No usable key backup: disabling key backup");
                this.disableKeyBackup();
            }
            else if (!trustInfo.usable && !this.backupInfo) {
                logger_1.logger.log("No usable key backup: not enabling key backup");
            }
            else if (trustInfo.usable && this.backupInfo) {
                // may not be the same version: if not, we should switch
                if (backupInfo.version !== this.backupInfo.version) {
                    logger_1.logger.log("On backup version " + this.backupInfo.version + " but found " +
                        "version " + backupInfo.version + ": switching.");
                    this.disableKeyBackup();
                    yield this.enableKeyBackup(backupInfo);
                    // We're now using a new backup, so schedule all the keys we have to be
                    // uploaded to the new backup. This is a bit of a workaround to upload
                    // keys to a new backup in *most* cases, but it won't cover all cases
                    // because we don't remember what backup version we uploaded keys to:
                    // see https://github.com/vector-im/element-web/issues/14833
                    yield this.scheduleAllGroupSessionsForBackup();
                }
                else {
                    logger_1.logger.log("Backup version " + backupInfo.version + " still current");
                }
            }
            return { backupInfo, trustInfo };
        });
    }
    /**
     * Forces a re-check of the key backup and enables/disables it
     * as appropriate.
     *
     * @return {Object} Object with backup info (as returned by
     *     getKeyBackupVersion) in backupInfo and
     *     trust information (as returned by isKeyBackupTrusted)
     *     in trustInfo.
     */
    checkKeyBackup() {
        return __awaiter(this, void 0, void 0, function* () {
            this.checkedForBackup = false;
            return this.checkAndStart();
        });
    }
    /**
     * Check if the given backup info is trusted.
     *
     * @param {IKeyBackupInfo} backupInfo key backup info dict from /room_keys/version
     * @return {object} {
     *     usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device
     *     sigs: [
     *         valid: [bool || null], // true: valid, false: invalid, null: cannot attempt validation
     *         deviceId: [string],
     *         device: [DeviceInfo || null],
     *     ]
     * }
     */
    isKeyBackupTrusted(backupInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            const ret = {
                usable: false,
                trusted_locally: false,
                sigs: [],
            };
            if (!backupInfo ||
                !backupInfo.algorithm ||
                !backupInfo.auth_data ||
                !backupInfo.auth_data.signatures) {
                logger_1.logger.info("Key backup is absent or missing required data");
                return ret;
            }
            const trustedPubkey = this.baseApis.crypto.sessionStore.getLocalTrustedBackupPubKey();
            if ("public_key" in backupInfo.auth_data && backupInfo.auth_data.public_key === trustedPubkey) {
                logger_1.logger.info("Backup public key " + trustedPubkey + " is trusted locally");
                ret.trusted_locally = true;
            }
            const mySigs = backupInfo.auth_data.signatures[this.baseApis.getUserId()] || [];
            for (const keyId of Object.keys(mySigs)) {
                const keyIdParts = keyId.split(':');
                if (keyIdParts[0] !== 'ed25519') {
                    logger_1.logger.log("Ignoring unknown signature type: " + keyIdParts[0]);
                    continue;
                }
                // Could be a cross-signing master key, but just say this is the device
                // ID for backwards compat
                const sigInfo = { deviceId: keyIdParts[1] };
                // first check to see if it's from our cross-signing key
                const crossSigningId = this.baseApis.crypto.crossSigningInfo.getId();
                if (crossSigningId === sigInfo.deviceId) {
                    sigInfo.crossSigningId = true;
                    try {
                        yield olmlib_1.verifySignature(this.baseApis.crypto.olmDevice, backupInfo.auth_data, this.baseApis.getUserId(), sigInfo.deviceId, crossSigningId);
                        sigInfo.valid = true;
                    }
                    catch (e) {
                        logger_1.logger.warn("Bad signature from cross signing key " + crossSigningId, e);
                        sigInfo.valid = false;
                    }
                    ret.sigs.push(sigInfo);
                    continue;
                }
                // Now look for a sig from a device
                // At some point this can probably go away and we'll just support
                // it being signed by the cross-signing master key
                const device = this.baseApis.crypto.deviceList.getStoredDevice(this.baseApis.getUserId(), sigInfo.deviceId);
                if (device) {
                    sigInfo.device = device;
                    sigInfo.deviceTrust = yield this.baseApis.checkDeviceTrust(this.baseApis.getUserId(), sigInfo.deviceId);
                    try {
                        yield olmlib_1.verifySignature(this.baseApis.crypto.olmDevice, backupInfo.auth_data, this.baseApis.getUserId(), device.deviceId, device.getFingerprint());
                        sigInfo.valid = true;
                    }
                    catch (e) {
                        logger_1.logger.info("Bad signature from key ID " + keyId + " userID " + this.baseApis.getUserId() +
                            " device ID " + device.deviceId + " fingerprint: " +
                            device.getFingerprint(), backupInfo.auth_data, e);
                        sigInfo.valid = false;
                    }
                }
                else {
                    sigInfo.valid = null; // Can't determine validity because we don't have the signing device
                    logger_1.logger.info("Ignoring signature from unknown key " + keyId);
                }
                ret.sigs.push(sigInfo);
            }
            ret.usable = ret.sigs.some((s) => {
                return (s.valid && ((s.device && s.deviceTrust.isVerified()) ||
                    (s.crossSigningId)));
            });
            ret.usable = ret.usable || ret.trusted_locally;
            return ret;
        });
    }
    /**
     * Schedules sending all keys waiting to be sent to the backup, if not already
     * scheduled. Retries if necessary.
     *
     * @param maxDelay Maximum delay to wait in ms. 0 means no delay.
     */
    scheduleKeyBackupSend(maxDelay = 10000) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.sendingBackups)
                return;
            this.sendingBackups = true;
            try {
                // wait between 0 and `maxDelay` seconds, to avoid backup
                // requests from different clients hitting the server all at
                // the same time when a new key is sent
                const delay = Math.random() * maxDelay;
                yield utils_1.sleep(delay, undefined);
                let numFailures = 0; // number of consecutive failures
                for (;;) {
                    if (!this.algorithm) {
                        return;
                    }
                    try {
                        const numBackedUp = yield this.backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST);
                        if (numBackedUp === 0) {
                            // no sessions left needing backup: we're done
                            return;
                        }
                        numFailures = 0;
                    }
                    catch (err) {
                        numFailures++;
                        logger_1.logger.log("Key backup request failed", err);
                        if (err.data) {
                            if (err.data.errcode == 'M_NOT_FOUND' ||
                                err.data.errcode == 'M_WRONG_ROOM_KEYS_VERSION') {
                                // Re-check key backup status on error, so we can be
                                // sure to present the current situation when asked.
                                yield this.checkKeyBackup();
                                // Backup version has changed or this backup version
                                // has been deleted
                                this.baseApis.crypto.emit("crypto.keyBackupFailed", err.data.errcode);
                                throw err;
                            }
                        }
                    }
                    if (numFailures) {
                        // exponential backoff if we have failures
                        yield utils_1.sleep(1000 * Math.pow(2, Math.min(numFailures - 1, 4)), undefined);
                    }
                }
            }
            finally {
                this.sendingBackups = false;
            }
        });
    }
    /**
     * Take some e2e keys waiting to be backed up and send them
     * to the backup.
     *
     * @param {integer} limit Maximum number of keys to back up
     * @returns {integer} Number of sessions backed up
     */
    backupPendingKeys(limit) {
        return __awaiter(this, void 0, void 0, function* () {
            const sessions = yield this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(limit);
            if (!sessions.length) {
                return 0;
            }
            let remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
            this.baseApis.crypto.emit("crypto.keyBackupSessionsRemaining", remaining);
            const data = {};
            for (const session of sessions) {
                const roomId = session.sessionData.room_id;
                if (data[roomId] === undefined) {
                    data[roomId] = { sessions: {} };
                }
                const sessionData = yield this.baseApis.crypto.olmDevice.exportInboundGroupSession(session.senderKey, session.sessionId, session.sessionData);
                sessionData.algorithm = olmlib_1.MEGOLM_ALGORITHM;
                const forwardedCount = (sessionData.forwarding_curve25519_key_chain || []).length;
                const userId = this.baseApis.crypto.deviceList.getUserByIdentityKey(olmlib_1.MEGOLM_ALGORITHM, session.senderKey);
                const device = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(olmlib_1.MEGOLM_ALGORITHM, session.senderKey);
                const verified = this.baseApis.crypto.checkDeviceInfoTrust(userId, device).isVerified();
                data[roomId]['sessions'][session.sessionId] = {
                    first_message_index: sessionData.first_known_index,
                    forwarded_count: forwardedCount,
                    is_verified: verified,
                    session_data: yield this.algorithm.encryptSession(sessionData),
                };
            }
            yield this.baseApis.sendKeyBackup(undefined, undefined, this.backupInfo.version, { rooms: data });
            yield this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(sessions);
            remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
            this.baseApis.crypto.emit("crypto.keyBackupSessionsRemaining", remaining);
            return sessions.length;
        });
    }
    backupGroupSession(senderKey, sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{
                    senderKey: senderKey,
                    sessionId: sessionId,
                }]);
            if (this.backupInfo) {
                // don't wait for this to complete: it will delay so
                // happens in the background
                this.scheduleKeyBackupSend();
            }
            // if this.backupInfo is not set, then the keys will be backed up when
            // this.enableKeyBackup is called
        });
    }
    /**
     * Marks all group sessions as needing to be backed up and schedules them to
     * upload in the background as soon as possible.
     */
    scheduleAllGroupSessionsForBackup() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.flagAllGroupSessionsForBackup();
            // Schedule keys to upload in the background as soon as possible.
            this.scheduleKeyBackupSend(0 /* maxDelay */);
        });
    }
    /**
     * Marks all group sessions as needing to be backed up without scheduling
     * them to upload in the background.
     * @returns {Promise<int>} Resolves to the number of sessions now requiring a backup
     *     (which will be equal to the number of sessions in the store).
     */
    flagAllGroupSessionsForBackup() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.baseApis.crypto.cryptoStore.doTxn('readwrite', [
                indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,
                indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_BACKUP,
            ], (txn) => {
                this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (session) => {
                    if (session !== null) {
                        this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([session], txn);
                    }
                });
            });
            const remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
            this.baseApis.emit("crypto.keyBackupSessionsRemaining", remaining);
            return remaining;
        });
    }
    /**
     * Counts the number of end to end session keys that are waiting to be backed up
     * @returns {Promise<int>} Resolves to the number of sessions requiring backup
     */
    countSessionsNeedingBackup() {
        return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
    }
}
exports.BackupManager = BackupManager;
class Curve25519 {
    constructor(authData, publicKey, // FIXME: PkEncryption
    getKey) {
        this.authData = authData;
        this.publicKey = publicKey;
        this.getKey = getKey;
    }
    static init(authData, getKey) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!authData || !("public_key" in authData)) {
                throw new Error("auth_data missing required information");
            }
            const publicKey = new global.Olm.PkEncryption();
            publicKey.set_recipient_key(authData.public_key);
            return new Curve25519(authData, publicKey, getKey);
        });
    }
    static prepare(key) {
        return __awaiter(this, void 0, void 0, function* () {
            const decryption = new global.Olm.PkDecryption();
            try {
                const authData = {};
                if (!key) {
                    authData.public_key = decryption.generate_key();
                }
                else if (key instanceof Uint8Array) {
                    authData.public_key = decryption.init_with_private_key(key);
                }
                else {
                    const derivation = yield key_passphrase_1.keyFromPassphrase(key);
                    authData.private_key_salt = derivation.salt;
                    authData.private_key_iterations = derivation.iterations;
                    authData.public_key = decryption.init_with_private_key(derivation.key);
                }
                const publicKey = new global.Olm.PkEncryption();
                publicKey.set_recipient_key(authData.public_key);
                return [
                    decryption.get_private_key(),
                    authData,
                ];
            }
            finally {
                decryption.free();
            }
        });
    }
    static checkBackupVersion(info) {
        if (!("public_key" in info.auth_data)) {
            throw new Error("Invalid backup data returned");
        }
    }
    get untrusted() { return true; }
    encryptSession(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const plainText = Object.assign({}, data);
            delete plainText.session_id;
            delete plainText.room_id;
            delete plainText.first_known_index;
            return this.publicKey.encrypt(JSON.stringify(plainText));
        });
    }
    decryptSessions(sessions) {
        return __awaiter(this, void 0, void 0, function* () {
            const privKey = yield this.getKey();
            const decryption = new global.Olm.PkDecryption();
            try {
                const backupPubKey = decryption.init_with_private_key(privKey);
                if (backupPubKey !== this.authData.public_key) {
                    // eslint-disable-next-line no-throw-literal
                    throw { errcode: client_1.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY };
                }
                const keys = [];
                for (const [sessionId, sessionData] of Object.entries(sessions)) {
                    try {
                        const decrypted = JSON.parse(decryption.decrypt(sessionData.session_data.ephemeral, sessionData.session_data.mac, sessionData.session_data.ciphertext));
                        decrypted.session_id = sessionId;
                        keys.push(decrypted);
                    }
                    catch (e) {
                        logger_1.logger.log("Failed to decrypt megolm session from backup", e, sessionData);
                    }
                }
                return keys;
            }
            finally {
                decryption.free();
            }
        });
    }
    keyMatches(key) {
        return __awaiter(this, void 0, void 0, function* () {
            const decryption = new global.Olm.PkDecryption();
            let pubKey;
            try {
                pubKey = decryption.init_with_private_key(key);
            }
            finally {
                decryption.free();
            }
            return pubKey === this.authData.public_key;
        });
    }
    free() {
        this.publicKey.free();
    }
}
exports.Curve25519 = Curve25519;
Curve25519.algorithmName = "m.megolm_backup.v1.curve25519-aes-sha2";
function randomBytes(size) {
    const crypto = utils_2.getCrypto();
    if (crypto) {
        // nodejs version
        return crypto.randomBytes(size);
    }
    if (window === null || window === void 0 ? void 0 : window.crypto) {
        // browser version
        const buf = new Uint8Array(size);
        window.crypto.getRandomValues(buf);
        return buf;
    }
    throw new Error("No usable crypto implementation");
}
const UNSTABLE_MSC3270_NAME = new NamespacedValue_1.UnstableValue(null, "org.matrix.msc3270.v1.aes-hmac-sha2");
class Aes256 {
    constructor(authData, key) {
        this.authData = authData;
        this.key = key;
    }
    static init(authData, getKey) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!authData) {
                throw new Error("auth_data missing");
            }
            const key = yield getKey();
            if (authData.mac) {
                const { mac } = yield aes_1.calculateKeyCheck(key, authData.iv);
                if (authData.mac.replace(/=+$/g, '') !== mac.replace(/=+/g, '')) {
                    throw new Error("Key does not match");
                }
            }
            return new Aes256(authData, key);
        });
    }
    static prepare(key) {
        return __awaiter(this, void 0, void 0, function* () {
            let outKey;
            const authData = {};
            if (!key) {
                outKey = randomBytes(32);
            }
            else if (key instanceof Uint8Array) {
                outKey = new Uint8Array(key);
            }
            else {
                const derivation = yield key_passphrase_1.keyFromPassphrase(key);
                authData.private_key_salt = derivation.salt;
                authData.private_key_iterations = derivation.iterations;
                outKey = derivation.key;
            }
            const { iv, mac } = yield aes_1.calculateKeyCheck(outKey);
            authData.iv = iv;
            authData.mac = mac;
            return [outKey, authData];
        });
    }
    static checkBackupVersion(info) {
        if (!("iv" in info.auth_data && "mac" in info.auth_data)) {
            throw new Error("Invalid backup data returned");
        }
    }
    get untrusted() { return false; }
    encryptSession(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const plainText = Object.assign({}, data);
            delete plainText.session_id;
            delete plainText.room_id;
            delete plainText.first_known_index;
            return yield aes_1.encryptAES(JSON.stringify(plainText), this.key, data.session_id);
        });
    }
    decryptSessions(sessions) {
        return __awaiter(this, void 0, void 0, function* () {
            const keys = [];
            for (const [sessionId, sessionData] of Object.entries(sessions)) {
                try {
                    const decrypted = JSON.parse(yield aes_1.decryptAES(sessionData.session_data, this.key, sessionId));
                    decrypted.session_id = sessionId;
                    keys.push(decrypted);
                }
                catch (e) {
                    logger_1.logger.log("Failed to decrypt megolm session from backup", e, sessionData);
                }
            }
            return keys;
        });
    }
    keyMatches(key) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.authData.mac) {
                const { mac } = yield aes_1.calculateKeyCheck(key, this.authData.iv);
                return this.authData.mac.replace(/=+$/g, '') === mac.replace(/=+/g, '');
            }
            else {
                // if we have no information, we have to assume the key is right
                return true;
            }
        });
    }
    free() {
        this.key.fill(0);
    }
}
exports.Aes256 = Aes256;
Aes256.algorithmName = UNSTABLE_MSC3270_NAME.name;
exports.algorithmsByName = {
    [Curve25519.algorithmName]: Curve25519,
    [Aes256.algorithmName]: Aes256,
};
exports.DefaultAlgorithm = Curve25519;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../NamespacedValue":60,"../client":64,"../logger":106,"../utils":137,"./aes":74,"./key_passphrase":84,"./olmlib":85,"./recoverykey":86,"./store/indexeddb-crypto-store":88}],81:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";
/*
Copyright 2020-2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DehydrationManager = exports.DEHYDRATION_ALGORITHM = void 0;
const olmlib_1 = require("./olmlib");
const indexeddb_crypto_store_1 = require("../crypto/store/indexeddb-crypto-store");
const aes_1 = require("./aes");
const another_json_1 = __importDefault(require("another-json"));
const logger_1 = require("../logger");
exports.DEHYDRATION_ALGORITHM = "org.matrix.msc2697.v1.olm.libolm_pickle";
const oneweek = 7 * 24 * 60 * 60 * 1000;
class DehydrationManager {
    constructor(crypto) {
        this.crypto = crypto;
        this.inProgress = false;
        this.getDehydrationKeyFromCache();
    }
    getDehydrationKeyFromCache() {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.crypto.cryptoStore.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                this.crypto.cryptoStore.getSecretStorePrivateKey(txn, (result) => __awaiter(this, void 0, void 0, function* () {
                    if (result) {
                        const { key, keyInfo, deviceDisplayName, time } = result;
                        const pickleKey = Buffer.from(this.crypto.olmDevice._pickleKey);
                        const decrypted = yield aes_1.decryptAES(key, pickleKey, exports.DEHYDRATION_ALGORITHM);
                        this.key = olmlib_1.decodeBase64(decrypted);
                        this.keyInfo = keyInfo;
                        this.deviceDisplayName = deviceDisplayName;
                        const now = Date.now();
                        const delay = Math.max(1, time + oneweek - now);
                        this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), delay);
                    }
                }), "dehydration");
            });
        });
    }
    /** set the key, and queue periodic dehydration to the server in the background */
    setKeyAndQueueDehydration(key, keyInfo = {}, deviceDisplayName = undefined) {
        return __awaiter(this, void 0, void 0, function* () {
            const matches = yield this.setKey(key, keyInfo, deviceDisplayName);
            if (!matches) {
                // start dehydration in the background
                this.dehydrateDevice();
            }
        });
    }
    setKey(key, keyInfo = {}, deviceDisplayName = undefined) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!key) {
                // unsetting the key -- cancel any pending dehydration task
                if (this.timeoutId) {
                    global.clearTimeout(this.timeoutId);
                    this.timeoutId = undefined;
                }
                // clear storage
                yield this.crypto.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                    this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, "dehydration", null);
                });
                this.key = undefined;
                this.keyInfo = undefined;
                return;
            }
            // Check to see if it's the same key as before.  If it's different,
            // dehydrate a new device.  If it's the same, we can keep the same
            // device.  (Assume that keyInfo and deviceDisplayName will be the
            // same if the key is the same.)
            let matches = this.key && key.length == this.key.length;
            for (let i = 0; matches && i < key.length; i++) {
                if (key[i] != this.key[i]) {
                    matches = false;
                }
            }
            if (!matches) {
                this.key = key;
                this.keyInfo = keyInfo;
                this.deviceDisplayName = deviceDisplayName;
            }
            return matches;
        });
    }
    /** returns the device id of the newly created dehydrated device */
    dehydrateDevice() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.inProgress) {
                logger_1.logger.log("Dehydration already in progress -- not starting new dehydration");
                return;
            }
            this.inProgress = true;
            if (this.timeoutId) {
                global.clearTimeout(this.timeoutId);
                this.timeoutId = undefined;
            }
            try {
                const pickleKey = Buffer.from(this.crypto.olmDevice._pickleKey);
                // update the crypto store with the timestamp
                const key = yield aes_1.encryptAES(olmlib_1.encodeBase64(this.key), pickleKey, exports.DEHYDRATION_ALGORITHM);
                yield this.crypto.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                    this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, "dehydration", {
                        keyInfo: this.keyInfo,
                        key,
                        deviceDisplayName: this.deviceDisplayName,
                        time: Date.now(),
                    });
                });
                logger_1.logger.log("Attempting to dehydrate device");
                logger_1.logger.log("Creating account");
                // create the account and all the necessary keys
                const account = new global.Olm.Account();
                account.create();
                const e2eKeys = JSON.parse(account.identity_keys());
                const maxKeys = account.max_number_of_one_time_keys();
                // FIXME: generate in small batches?
                account.generate_one_time_keys(maxKeys / 2);
                account.generate_fallback_key();
                const otks = JSON.parse(account.one_time_keys());
                const fallbacks = JSON.parse(account.fallback_key());
                account.mark_keys_as_published();
                // dehydrate the account and store it on the server
                const pickledAccount = account.pickle(new Uint8Array(this.key));
                const deviceData = {
                    algorithm: exports.DEHYDRATION_ALGORITHM,
                    account: pickledAccount,
                };
                if (this.keyInfo.passphrase) {
                    deviceData.passphrase = this.keyInfo.passphrase;
                }
                logger_1.logger.log("Uploading account to server");
                const dehydrateResult = yield this.crypto.baseApis.http.authedRequest(undefined, "PUT", "/dehydrated_device", undefined, {
                    device_data: deviceData,
                    initial_device_display_name: this.deviceDisplayName,
                }, {
                    prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2",
                });
                // send the keys to the server
                const deviceId = dehydrateResult.device_id;
                logger_1.logger.log("Preparing device keys", deviceId);
                const deviceKeys = {
                    algorithms: this.crypto.supportedAlgorithms,
                    device_id: deviceId,
                    user_id: this.crypto.userId,
                    keys: {
                        [`ed25519:${deviceId}`]: e2eKeys.ed25519,
                        [`curve25519:${deviceId}`]: e2eKeys.curve25519,
                    },
                };
                const deviceSignature = account.sign(another_json_1.default.stringify(deviceKeys));
                deviceKeys.signatures = {
                    [this.crypto.userId]: {
                        [`ed25519:${deviceId}`]: deviceSignature,
                    },
                };
                if (this.crypto.crossSigningInfo.getId("self_signing")) {
                    yield this.crypto.crossSigningInfo.signObject(deviceKeys, "self_signing");
                }
                logger_1.logger.log("Preparing one-time keys");
                const oneTimeKeys = {};
                for (const [keyId, key] of Object.entries(otks.curve25519)) {
                    const k = { key };
                    const signature = account.sign(another_json_1.default.stringify(k));
                    k.signatures = {
                        [this.crypto.userId]: {
                            [`ed25519:${deviceId}`]: signature,
                        },
                    };
                    oneTimeKeys[`signed_curve25519:${keyId}`] = k;
                }
                logger_1.logger.log("Preparing fallback keys");
                const fallbackKeys = {};
                for (const [keyId, key] of Object.entries(fallbacks.curve25519)) {
                    const k = { key, fallback: true };
                    const signature = account.sign(another_json_1.default.stringify(k));
                    k.signatures = {
                        [this.crypto.userId]: {
                            [`ed25519:${deviceId}`]: signature,
                        },
                    };
                    fallbackKeys[`signed_curve25519:${keyId}`] = k;
                }
                logger_1.logger.log("Uploading keys to server");
                yield this.crypto.baseApis.http.authedRequest(undefined, "POST", "/keys/upload/" + encodeURI(deviceId), undefined, {
                    "device_keys": deviceKeys,
                    "one_time_keys": oneTimeKeys,
                    "org.matrix.msc2732.fallback_keys": fallbackKeys,
                });
                logger_1.logger.log("Done dehydrating");
                // dehydrate again in a week
                this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), oneweek);
                return deviceId;
            }
            finally {
                this.inProgress = false;
            }
        });
    }
    stop() {
        if (this.timeoutId) {
            global.clearTimeout(this.timeoutId);
            this.timeoutId = undefined;
        }
    }
}
exports.DehydrationManager = DehydrationManager;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"../crypto/store/indexeddb-crypto-store":88,"../logger":106,"./aes":74,"./olmlib":85,"another-json":28,"buffer":34}],82:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeviceInfo = void 0;
var DeviceVerification;
(function (DeviceVerification) {
    DeviceVerification[DeviceVerification["Blocked"] = -1] = "Blocked";
    DeviceVerification[DeviceVerification["Unverified"] = 0] = "Unverified";
    DeviceVerification[DeviceVerification["Verified"] = 1] = "Verified";
})(DeviceVerification || (DeviceVerification = {}));
/**
  * Information about a user's device
  *
  * @constructor
  * @alias module:crypto/deviceinfo
  *
  * @property {string} deviceId the ID of this device
  *
  * @property {string[]} algorithms list of algorithms supported by this device
  *
  * @property {Object.<string,string>} keys a map from
  *      &lt;key type&gt;:&lt;id&gt; -> &lt;base64-encoded key&gt;>
  *
  * @property {module:crypto/deviceinfo.DeviceVerification} verified
  *     whether the device has been verified/blocked by the user
  *
  * @property {boolean} known
  *     whether the user knows of this device's existence (useful when warning
  *     the user that a user has added new devices)
  *
  * @property {Object} unsigned  additional data from the homeserver
  *
  * @param {string} deviceId id of the device
  */
class DeviceInfo {
    constructor(deviceId) {
        this.deviceId = deviceId;
        this.keys = {};
        this.verified = DeviceVerification.Unverified;
        this.known = false;
        this.unsigned = {};
        this.signatures = {};
    }
    /**
     * rehydrate a DeviceInfo from the session store
     *
     * @param {object} obj  raw object from session store
     * @param {string} deviceId id of the device
     *
     * @return {module:crypto~DeviceInfo} new DeviceInfo
     */
    static fromStorage(obj, deviceId) {
        const res = new DeviceInfo(deviceId);
        for (const prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                res[prop] = obj[prop];
            }
        }
        return res;
    }
    /**
     * Prepare a DeviceInfo for JSON serialisation in the session store
     *
     * @return {object} deviceinfo with non-serialised members removed
     */
    toStorage() {
        return {
            algorithms: this.algorithms,
            keys: this.keys,
            verified: this.verified,
            known: this.known,
            unsigned: this.unsigned,
            signatures: this.signatures,
        };
    }
    /**
     * Get the fingerprint for this device (ie, the Ed25519 key)
     *
     * @return {string} base64-encoded fingerprint of this device
     */
    getFingerprint() {
        return this.keys["ed25519:" + this.deviceId];
    }
    /**
     * Get the identity key for this device (ie, the Curve25519 key)
     *
     * @return {string} base64-encoded identity key of this device
     */
    getIdentityKey() {
        return this.keys["curve25519:" + this.deviceId];
    }
    /**
     * Get the configured display name for this device, if any
     *
     * @return {string?} displayname
     */
    getDisplayName() {
        return this.unsigned.device_display_name || null;
    }
    /**
     * Returns true if this device is blocked
     *
     * @return {Boolean} true if blocked
     */
    isBlocked() {
        return this.verified == DeviceVerification.Blocked;
    }
    /**
     * Returns true if this device is verified
     *
     * @return {Boolean} true if verified
     */
    isVerified() {
        return this.verified == DeviceVerification.Verified;
    }
    /**
     * Returns true if this device is unverified
     *
     * @return {Boolean} true if unverified
     */
    isUnverified() {
        return this.verified == DeviceVerification.Unverified;
    }
    /**
     * Returns true if the user knows about this device's existence
     *
     * @return {Boolean} true if known
     */
    isKnown() {
        return this.known === true;
    }
}
exports.DeviceInfo = DeviceInfo;
/**
 * @enum
 */
DeviceInfo.DeviceVerification = {
    VERIFIED: DeviceVerification.Verified,
    UNVERIFIED: DeviceVerification.Unverified,
    BLOCKED: DeviceVerification.Blocked,
};

},{}],83:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018-2019 New Vector Ltd
Copyright 2019-2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IncomingRoomKeyRequest = exports.fixBackupKey = exports.Crypto = exports.isCryptoAvailable = exports.verificationMethods = void 0;
/**
 * @module crypto
 */
const another_json_1 = __importDefault(require("another-json"));
const events_1 = require("events");
const ReEmitter_1 = require("../ReEmitter");
const logger_1 = require("../logger");
const OlmDevice_1 = require("./OlmDevice");
const olmlib = __importStar(require("./olmlib"));
const DeviceList_1 = require("./DeviceList");
const deviceinfo_1 = require("./deviceinfo");
const algorithms = __importStar(require("./algorithms"));
const CrossSigning_1 = require("./CrossSigning");
const EncryptionSetup_1 = require("./EncryptionSetup");
const SecretStorage_1 = require("./SecretStorage");
const OutgoingRoomKeyRequestManager_1 = require("./OutgoingRoomKeyRequestManager");
const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store");
const QRCode_1 = require("./verification/QRCode");
const SAS_1 = require("./verification/SAS");
const key_passphrase_1 = require("./key_passphrase");
const recoverykey_1 = require("./recoverykey");
const VerificationRequest_1 = require("./verification/request/VerificationRequest");
const InRoomChannel_1 = require("./verification/request/InRoomChannel");
const ToDeviceChannel_1 = require("./verification/request/ToDeviceChannel");
const IllegalMethod_1 = require("./verification/IllegalMethod");
const errors_1 = require("../errors");
const aes_1 = require("./aes");
const dehydration_1 = require("./dehydration");
const backup_1 = require("./backup");
const event_1 = require("../models/event");
const DeviceVerification = deviceinfo_1.DeviceInfo.DeviceVerification;
const defaultVerificationMethods = {
    [QRCode_1.ReciprocateQRCode.NAME]: QRCode_1.ReciprocateQRCode,
    [SAS_1.SAS.NAME]: SAS_1.SAS,
    // These two can't be used for actual verification, but we do
    // need to be able to define them here for the verification flows
    // to start.
    [QRCode_1.SHOW_QR_CODE_METHOD]: IllegalMethod_1.IllegalMethod,
    [QRCode_1.SCAN_QR_CODE_METHOD]: IllegalMethod_1.IllegalMethod,
};
/**
 * verification method names
 */
exports.verificationMethods = {
    RECIPROCATE_QR_CODE: QRCode_1.ReciprocateQRCode.NAME,
    SAS: SAS_1.SAS.NAME,
};
function isCryptoAvailable() {
    return Boolean(global.Olm);
}
exports.isCryptoAvailable = isCryptoAvailable;
const MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000;
class Crypto extends events_1.EventEmitter {
    /**
     * Cryptography bits
     *
     * This module is internal to the js-sdk; the public API is via MatrixClient.
     *
     * @constructor
     * @alias module:crypto
     *
     * @internal
     *
     * @param {MatrixClient} baseApis base matrix api interface
     *
     * @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore
     *    Store to be used for end-to-end crypto session data
     *
     * @param {string} userId The user ID for the local user
     *
     * @param {string} deviceId The identifier for this device.
     *
     * @param {Object} clientStore the MatrixClient data store.
     *
     * @param {module:crypto/store/base~CryptoStore} cryptoStore
     *    storage for the crypto layer.
     *
     * @param {RoomList} roomList An initialised RoomList object
     *
     * @param {Array} verificationMethods Array of verification methods to use.
     *    Each element can either be a string from MatrixClient.verificationMethods
     *    or a class that implements a verification method.
     */
    constructor(baseApis, sessionStore, userId, deviceId, clientStore, cryptoStore, roomList, verificationMethods) {
        super();
        this.baseApis = baseApis;
        this.sessionStore = sessionStore;
        this.userId = userId;
        this.deviceId = deviceId;
        this.clientStore = clientStore;
        this.cryptoStore = cryptoStore;
        this.roomList = roomList;
        this.trustCrossSignedDevices = true;
        // the last time we did a check for the number of one-time-keys on the server.
        this.lastOneTimeKeyCheck = null;
        this.oneTimeKeyCheckInProgress = false;
        // EncryptionAlgorithm instance for each room
        this.roomEncryptors = {};
        // map from algorithm to DecryptionAlgorithm instance, for each room
        this.roomDecryptors = {};
        this.deviceKeys = {}; // type: key
        this.globalBlacklistUnverifiedDevices = false;
        this.globalErrorOnUnknownDevices = true;
        // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations
        // we received in the current sync.
        this.receivedRoomKeyRequests = [];
        this.receivedRoomKeyRequestCancellations = [];
        // true if we are currently processing received room key requests
        this.processingRoomKeyRequests = false;
        // controls whether device tracking is delayed
        // until calling encryptEvent or trackRoomDevices,
        // or done immediately upon enabling room encryption.
        this.lazyLoadMembers = false;
        // in case lazyLoadMembers is true,
        // track if an initial tracking of all the room members
        // has happened for a given room. This is delayed
        // to avoid loading room members as long as possible.
        this.roomDeviceTrackingState = {}; // roomId: Promise<void
        // The timestamp of the last time we forced establishment
        // of a new session for each device, in milliseconds.
        // {
        //     userId: {
        //         deviceId: 1234567890000,
        //     },
        // }
        this.lastNewSessionForced = {};
        // This flag will be unset whilst the client processes a sync response
        // so that we don't start requesting keys until we've actually finished
        // processing the response.
        this.sendKeyRequestsImmediately = false;
        /*
         * Event handler for DeviceList's userNewDevices event
         */
        this.onDeviceListUserCrossSigningUpdated = (userId) => __awaiter(this, void 0, void 0, function* () {
            if (userId === this.userId) {
                // An update to our own cross-signing key.
                // Get the new key first:
                const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);
                const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null;
                const currentPubkey = this.crossSigningInfo.getId();
                const changed = currentPubkey !== seenPubkey;
                if (currentPubkey && seenPubkey && !changed) {
                    // If it's not changed, just make sure everything is up to date
                    yield this.checkOwnCrossSigningTrust();
                }
                else {
                    // We'll now be in a state where cross-signing on the account is not trusted
                    // because our locally stored cross-signing keys will not match the ones
                    // on the server for our account. So we clear our own stored cross-signing keys,
                    // effectively disabling cross-signing until the user gets verified by the device
                    // that reset the keys
                    this.storeTrustedSelfKeys(null);
                    // emit cross-signing has been disabled
                    this.emit("crossSigning.keysChanged", {});
                    // as the trust for our own user has changed,
                    // also emit an event for this
                    this.emit("userTrustStatusChanged", this.userId, this.checkUserTrust(userId));
                }
            }
            else {
                yield this.checkDeviceVerifications(userId);
                // Update verified before latch using the current state and save the new
                // latch value in the device list store.
                const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId);
                if (crossSigning) {
                    crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified());
                    this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage());
                }
                this.emit("userTrustStatusChanged", userId, this.checkUserTrust(userId));
            }
        });
        this.onToDeviceEvent = (event) => {
            try {
                logger_1.logger.log(`received to_device ${event.getType()} from: ` +
                    `${event.getSender()} id: ${event.getId()}`);
                if (event.getType() == "m.room_key"
                    || event.getType() == "m.forwarded_room_key") {
                    this.onRoomKeyEvent(event);
                }
                else if (event.getType() == "m.room_key_request") {
                    this.onRoomKeyRequestEvent(event);
                }
                else if (event.getType() === "m.secret.request") {
                    this.secretStorage.onRequestReceived(event);
                }
                else if (event.getType() === "m.secret.send") {
                    this.secretStorage.onSecretReceived(event);
                }
                else if (event.getType() === "org.matrix.room_key.withheld") {
                    this.onRoomKeyWithheldEvent(event);
                }
                else if (event.getContent().transaction_id) {
                    this.onKeyVerificationMessage(event);
                }
                else if (event.getContent().msgtype === "m.bad.encrypted") {
                    this.onToDeviceBadEncrypted(event);
                }
                else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
                    if (!event.isBeingDecrypted()) {
                        event.attemptDecryption(this);
                    }
                    // once the event has been decrypted, try again
                    event.once('Event.decrypted', (ev) => {
                        this.onToDeviceEvent(ev);
                    });
                }
            }
            catch (e) {
                logger_1.logger.error("Error handling toDeviceEvent:", e);
            }
        };
        /**
         * Handle key verification requests sent as timeline events
         *
         * @private
         * @param {module:models/event.MatrixEvent} event the timeline event
         * @param {module:models/Room} room not used
         * @param {boolean} atStart not used
         * @param {boolean} removed not used
         * @param {boolean} { liveEvent } whether this is a live event
         */
        this.onTimelineEvent = (event, room, atStart, removed, { liveEvent = true } = {}) => {
            if (!InRoomChannel_1.InRoomChannel.validateEvent(event, this.baseApis)) {
                return;
            }
            const createRequest = event => {
                const channel = new InRoomChannel_1.InRoomChannel(this.baseApis, event.getRoomId());
                return new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis);
            };
            this.handleVerificationEvent(event, this.inRoomVerificationRequests, createRequest, liveEvent);
        };
        this.reEmitter = new ReEmitter_1.ReEmitter(this);
        if (verificationMethods) {
            this.verificationMethods = new Map();
            for (const method of verificationMethods) {
                if (typeof method === "string") {
                    if (defaultVerificationMethods[method]) {
                        this.verificationMethods.set(method, defaultVerificationMethods[method]);
                    }
                }
                else if (method.NAME) {
                    this.verificationMethods.set(method.NAME, method);
                }
                else {
                    logger_1.logger.warn(`Excluding unknown verification method ${method}`);
                }
            }
        }
        else {
            this.verificationMethods = defaultVerificationMethods;
        }
        this.backupManager = new backup_1.BackupManager(baseApis, () => __awaiter(this, void 0, void 0, function* () {
            // try to get key from cache
            const cachedKey = yield this.getSessionBackupPrivateKey();
            if (cachedKey) {
                return cachedKey;
            }
            // try to get key from secret storage
            const storedKey = yield this.getSecret("m.megolm_backup.v1");
            if (storedKey) {
                // ensure that the key is in the right format.  If not, fix the key and
                // store the fixed version
                const fixedKey = fixBackupKey(storedKey);
                if (fixedKey) {
                    const [keyId] = yield this.getSecretStorageKey();
                    yield this.storeSecret("m.megolm_backup.v1", fixedKey, [keyId]);
                }
                return olmlib.decodeBase64(fixedKey || storedKey);
            }
            // try to get key from app
            if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) {
                return yield this.baseApis.cryptoCallbacks.getBackupKey();
            }
            throw new Error("Unable to get private key");
        }));
        this.olmDevice = new OlmDevice_1.OlmDevice(cryptoStore);
        this.deviceList = new DeviceList_1.DeviceList(baseApis, cryptoStore, this.olmDevice);
        // XXX: This isn't removed at any point, but then none of the event listeners
        // this class sets seem to be removed at any point... :/
        this.deviceList.on('userCrossSigningUpdated', this.onDeviceListUserCrossSigningUpdated);
        this.reEmitter.reEmit(this.deviceList, ["crypto.devicesUpdated", "crypto.willUpdateDevices"]);
        this.supportedAlgorithms = Object.keys(algorithms.DECRYPTION_CLASSES);
        this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager_1.OutgoingRoomKeyRequestManager(baseApis, this.deviceId, this.cryptoStore);
        this.toDeviceVerificationRequests = new ToDeviceChannel_1.ToDeviceRequests();
        this.inRoomVerificationRequests = new InRoomChannel_1.InRoomRequests();
        const cryptoCallbacks = this.baseApis.cryptoCallbacks || {};
        const cacheCallbacks = CrossSigning_1.createCryptoStoreCacheCallbacks(cryptoStore, this.olmDevice);
        this.crossSigningInfo = new CrossSigning_1.CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks);
        // Yes, we pass the client twice here: see SecretStorage
        this.secretStorage = new SecretStorage_1.SecretStorage(baseApis, cryptoCallbacks, baseApis);
        this.dehydrationManager = new dehydration_1.DehydrationManager(this);
        // Assuming no app-supplied callback, default to getting from SSSS.
        if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) {
            cryptoCallbacks.getCrossSigningKey = (type) => __awaiter(this, void 0, void 0, function* () {
                return CrossSigning_1.CrossSigningInfo.getFromSecretStorage(type, this.secretStorage);
            });
        }
    }
    /**
     * @return {string} The version of Olm.
     */
    static getOlmVersion() {
        return OlmDevice_1.OlmDevice.getOlmVersion();
    }
    /**
     * Initialise the crypto module so that it is ready for use
     *
     * Returns a promise which resolves once the crypto module is ready for use.
     *
     * @param {Object} opts keyword arguments.
     * @param {string} opts.exportedOlmDevice (Optional) data from exported device
     *     that must be re-created.
     */
    init({ exportedOlmDevice, pickleKey } = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log("Crypto: initialising Olm...");
            yield global.Olm.init();
            logger_1.logger.log(exportedOlmDevice
                ? "Crypto: initialising Olm device from exported device..."
                : "Crypto: initialising Olm device...");
            yield this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey });
            logger_1.logger.log("Crypto: loading device list...");
            yield this.deviceList.load();
            // build our device keys: these will later be uploaded
            this.deviceKeys["ed25519:" + this.deviceId] = this.olmDevice.deviceEd25519Key;
            this.deviceKeys["curve25519:" + this.deviceId] = this.olmDevice.deviceCurve25519Key;
            logger_1.logger.log("Crypto: fetching own devices...");
            let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId);
            if (!myDevices) {
                myDevices = {};
            }
            if (!myDevices[this.deviceId]) {
                // add our own deviceinfo to the cryptoStore
                logger_1.logger.log("Crypto: adding this device to the store...");
                const deviceInfo = {
                    keys: this.deviceKeys,
                    algorithms: this.supportedAlgorithms,
                    verified: DeviceVerification.VERIFIED,
                    known: true,
                };
                myDevices[this.deviceId] = deviceInfo;
                this.deviceList.storeDevicesForUser(this.userId, myDevices);
                this.deviceList.saveIfDirty();
            }
            yield this.cryptoStore.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                this.cryptoStore.getCrossSigningKeys(txn, (keys) => {
                    // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys
                    if (keys && Object.keys(keys).length !== 0) {
                        logger_1.logger.log("Loaded cross-signing public keys from crypto store");
                        this.crossSigningInfo.setKeys(keys);
                    }
                });
            });
            // make sure we are keeping track of our own devices
            // (this is important for key backups & things)
            this.deviceList.startTrackingDeviceList(this.userId);
            logger_1.logger.log("Crypto: checking for key backup...");
            this.backupManager.checkAndStart();
        });
    }
    /**
     * Whether to trust a others users signatures of their devices.
     * If false, devices will only be considered 'verified' if we have
     * verified that device individually (effectively disabling cross-signing).
     *
     * Default: true
     *
     * @return {boolean} True if trusting cross-signed devices
     */
    getCryptoTrustCrossSignedDevices() {
        return this.trustCrossSignedDevices;
    }
    /**
     * See getCryptoTrustCrossSignedDevices

     * This may be set before initCrypto() is called to ensure no races occur.
     *
     * @param {boolean} val True to trust cross-signed devices
     */
    setCryptoTrustCrossSignedDevices(val) {
        this.trustCrossSignedDevices = val;
        for (const userId of this.deviceList.getKnownUserIds()) {
            const devices = this.deviceList.getRawStoredDevicesForUser(userId);
            for (const deviceId of Object.keys(devices)) {
                const deviceTrust = this.checkDeviceTrust(userId, deviceId);
                // If the device is locally verified then isVerified() is always true,
                // so this will only have caused the value to change if the device is
                // cross-signing verified but not locally verified
                if (!deviceTrust.isLocallyVerified() &&
                    deviceTrust.isCrossSigningVerified()) {
                    const deviceObj = this.deviceList.getStoredDevice(userId, deviceId);
                    this.emit("deviceVerificationChanged", userId, deviceId, deviceObj);
                }
            }
        }
    }
    /**
     * Create a recovery key from a user-supplied passphrase.
     *
     * @param {string} password Passphrase string that can be entered by the user
     *     when restoring the backup as an alternative to entering the recovery key.
     *     Optional.
     * @returns {Promise<Object>} Object with public key metadata, encoded private
     *     recovery key which should be disposed of after displaying to the user,
     *     and raw private key to avoid round tripping if needed.
     */
    createRecoveryKeyFromPassphrase(password) {
        return __awaiter(this, void 0, void 0, function* () {
            const decryption = new global.Olm.PkDecryption();
            try {
                const keyInfo = {};
                if (password) {
                    const derivation = yield key_passphrase_1.keyFromPassphrase(password);
                    keyInfo.passphrase = {
                        algorithm: "m.pbkdf2",
                        iterations: derivation.iterations,
                        salt: derivation.salt,
                    };
                    keyInfo.pubkey = decryption.init_with_private_key(derivation.key);
                }
                else {
                    keyInfo.pubkey = decryption.generate_key();
                }
                const privateKey = decryption.get_private_key();
                const encodedPrivateKey = recoverykey_1.encodeRecoveryKey(privateKey);
                return {
                    keyInfo: keyInfo,
                    encodedPrivateKey,
                    privateKey,
                };
            }
            finally {
                if (decryption)
                    decryption.free();
            }
        });
    }
    /**
     * Checks whether cross signing:
     * - is enabled on this account and trusted by this device
     * - has private keys either cached locally or stored in secret storage
     *
     * If this function returns false, bootstrapCrossSigning() can be used
     * to fix things such that it returns true. That is to say, after
     * bootstrapCrossSigning() completes successfully, this function should
     * return true.
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @return {boolean} True if cross-signing is ready to be used on this device
     */
    isCrossSigningReady() {
        return __awaiter(this, void 0, void 0, function* () {
            const publicKeysOnDevice = this.crossSigningInfo.getId();
            const privateKeysExistSomewhere = ((yield this.crossSigningInfo.isStoredInKeyCache()) ||
                (yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage)));
            return !!(publicKeysOnDevice && privateKeysExistSomewhere);
        });
    }
    /**
     * Checks whether secret storage:
     * - is enabled on this account
     * - is storing cross-signing private keys
     * - is storing session backup key (if enabled)
     *
     * If this function returns false, bootstrapSecretStorage() can be used
     * to fix things such that it returns true. That is to say, after
     * bootstrapSecretStorage() completes successfully, this function should
     * return true.
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @return {boolean} True if secret storage is ready to be used on this device
     */
    isSecretStorageReady() {
        return __awaiter(this, void 0, void 0, function* () {
            const secretStorageKeyInAccount = yield this.secretStorage.hasKey();
            const privateKeysInStorage = yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);
            const sessionBackupInStorage = (!this.backupManager.getKeyBackupEnabled() ||
                (yield this.baseApis.isKeyBackupKeyStored()));
            return !!(secretStorageKeyInAccount &&
                privateKeysInStorage &&
                sessionBackupInStorage);
        });
    }
    /**
     * Bootstrap cross-signing by creating keys if needed. If everything is already
     * set up, then no changes are made, so this is safe to run to ensure
     * cross-signing is ready for use.
     *
     * This function:
     * - creates new cross-signing keys if they are not found locally cached nor in
     *   secret storage (if it has been setup)
     *
     * The cross-signing API is currently UNSTABLE and may change without notice.
     *
     * @param {function} opts.authUploadDeviceSigningKeys Function
     * called to await an interactive auth flow when uploading device signing keys.
     * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys
     * already exist.
     * Args:
     *     {function} A function that makes the request requiring auth. Receives the
     *     auth data as an object. Can be called multiple times, first with an empty
     *     authDict, to obtain the flows.
     */
    bootstrapCrossSigning({ authUploadDeviceSigningKeys, setupNewCrossSigning, } = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log("Bootstrapping cross-signing");
            const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;
            const builder = new EncryptionSetup_1.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);
            const crossSigningInfo = new CrossSigning_1.CrossSigningInfo(this.userId, builder.crossSigningCallbacks, builder.crossSigningCallbacks);
            // Reset the cross-signing keys
            const resetCrossSigning = () => __awaiter(this, void 0, void 0, function* () {
                crossSigningInfo.resetKeys();
                // Sign master key with device key
                yield this.signObject(crossSigningInfo.keys.master);
                // Store auth flow helper function, as we need to call it when uploading
                // to ensure we handle auth errors properly.
                builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys);
                // Cross-sign own device
                const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);
                const deviceSignature = yield crossSigningInfo.signDevice(this.userId, device);
                builder.addKeySignature(this.userId, this.deviceId, deviceSignature);
                // Sign message key backup with cross-signing master key
                if (this.backupManager.backupInfo) {
                    yield crossSigningInfo.signObject(this.backupManager.backupInfo.auth_data, "master");
                    builder.addSessionBackup(this.backupManager.backupInfo);
                }
            });
            const publicKeysOnDevice = this.crossSigningInfo.getId();
            const privateKeysInCache = yield this.crossSigningInfo.isStoredInKeyCache();
            const privateKeysInStorage = yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);
            const privateKeysExistSomewhere = (privateKeysInCache ||
                privateKeysInStorage);
            // Log all relevant state for easier parsing of debug logs.
            logger_1.logger.log({
                setupNewCrossSigning,
                publicKeysOnDevice,
                privateKeysInCache,
                privateKeysInStorage,
                privateKeysExistSomewhere,
            });
            if (!privateKeysExistSomewhere || setupNewCrossSigning) {
                logger_1.logger.log("Cross-signing private keys not found locally or in secret storage, " +
                    "creating new keys");
                // If a user has multiple devices, it important to only call bootstrap
                // as part of some UI flow (and not silently during startup), as they
                // may have setup cross-signing on a platform which has not saved keys
                // to secret storage, and this would reset them. In such a case, you
                // should prompt the user to verify any existing devices first (and
                // request private keys from those devices) before calling bootstrap.
                yield resetCrossSigning();
            }
            else if (publicKeysOnDevice && privateKeysInCache) {
                logger_1.logger.log("Cross-signing public keys trusted and private keys found locally");
            }
            else if (privateKeysInStorage) {
                logger_1.logger.log("Cross-signing private keys not found locally, but they are available " +
                    "in secret storage, reading storage and caching locally");
                yield this.checkOwnCrossSigningTrust({
                    allowPrivateKeyRequests: true,
                });
            }
            // Assuming no app-supplied callback, default to storing new private keys in
            // secret storage if it exists. If it does not, it is assumed this will be
            // done as part of setting up secret storage later.
            const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys;
            if (crossSigningPrivateKeys.size &&
                !this.baseApis.cryptoCallbacks.saveCrossSigningKeys) {
                const secretStorage = new SecretStorage_1.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks);
                if (yield secretStorage.hasKey()) {
                    logger_1.logger.log("Storing new cross-signing private keys in secret storage");
                    // This is writing to in-memory account data in
                    // builder.accountDataClientAdapter so won't fail
                    yield CrossSigning_1.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);
                }
            }
            const operation = builder.buildOperation();
            yield operation.apply(this);
            // This persists private keys and public keys as trusted,
            // only do this if apply succeeded for now as retry isn't in place yet
            yield builder.persist(this);
            logger_1.logger.log("Cross-signing ready");
        });
    }
    /**
     * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is
     * already set up, then no changes are made, so this is safe to run to ensure secret
     * storage is ready for use.
     *
     * This function
     * - creates a new Secure Secret Storage key if no default key exists
     *   - if a key backup exists, it is migrated to store the key in the Secret
     *     Storage
     * - creates a backup if none exists, and one is requested
     * - migrates Secure Secret Storage to use the latest algorithm, if an outdated
     *   algorithm is found
     *
     * The Secure Secret Storage API is currently UNSTABLE and may change without notice.
     *
     * @param {function} [opts.createSecretStorageKey] Optional. Function
     * called to await a secret storage key creation flow.
     * Returns:
     *     {Promise<Object>} Object with public key metadata, encoded private
     *     recovery key which should be disposed of after displaying to the user,
     *     and raw private key to avoid round tripping if needed.
     * @param {object} [opts.keyBackupInfo] The current key backup object. If passed,
     * the passphrase and recovery key from this backup will be used.
     * @param {boolean} [opts.setupNewKeyBackup] If true, a new key backup version will be
     * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo
     * is supplied.
     * @param {boolean} [opts.setupNewSecretStorage] Optional. Reset even if keys already exist.
     * @param {func} [opts.getKeyBackupPassphrase] Optional. Function called to get the user's
     *     current key backup passphrase. Should return a promise that resolves with a Buffer
     *     containing the key, or rejects if the key cannot be obtained.
     * Returns:
     *     {Promise} A promise which resolves to key creation data for
     *     SecretStorage#addKey: an object with `passphrase` etc fields.
     */
    // TODO this does not resolve with what it says it does
    bootstrapSecretStorage({ createSecretStorageKey = () => __awaiter(this, void 0, void 0, function* () { return ({}); }), keyBackupInfo, setupNewKeyBackup, setupNewSecretStorage, getKeyBackupPassphrase, } = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log("Bootstrapping Secure Secret Storage");
            const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;
            const builder = new EncryptionSetup_1.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);
            const secretStorage = new SecretStorage_1.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks);
            // the ID of the new SSSS key, if we create one
            let newKeyId = null;
            // create a new SSSS key and set it as default
            const createSSSS = (opts, privateKey) => __awaiter(this, void 0, void 0, function* () {
                opts = opts || {};
                if (privateKey) {
                    opts.key = privateKey;
                }
                const { keyId, keyInfo } = yield secretStorage.addKey(SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES, opts);
                if (privateKey) {
                    // make the private key available to encrypt 4S secrets
                    builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);
                }
                yield secretStorage.setDefaultKeyId(keyId);
                return keyId;
            });
            const ensureCanCheckPassphrase = (keyId, keyInfo) => __awaiter(this, void 0, void 0, function* () {
                if (!keyInfo.mac) {
                    const key = yield this.baseApis.cryptoCallbacks.getSecretStorageKey({ keys: { [keyId]: keyInfo } }, "");
                    if (key) {
                        const privateKey = key[1];
                        builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);
                        const { iv, mac } = yield aes_1.calculateKeyCheck(privateKey);
                        keyInfo.iv = iv;
                        keyInfo.mac = mac;
                        yield builder.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);
                    }
                }
            });
            const signKeyBackupWithCrossSigning = (keyBackupAuthData) => __awaiter(this, void 0, void 0, function* () {
                if (this.crossSigningInfo.getId() &&
                    (yield this.crossSigningInfo.isStoredInKeyCache("master"))) {
                    try {
                        logger_1.logger.log("Adding cross-signing signature to key backup");
                        yield this.crossSigningInfo.signObject(keyBackupAuthData, "master");
                    }
                    catch (e) {
                        // This step is not critical (just helpful), so we catch here
                        // and continue if it fails.
                        logger_1.logger.error("Signing key backup with cross-signing keys failed", e);
                    }
                }
                else {
                    logger_1.logger.warn("Cross-signing keys not available, skipping signature on key backup");
                }
            });
            const oldSSSSKey = yield this.getSecretStorageKey();
            const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null];
            const storageExists = (!setupNewSecretStorage &&
                oldKeyInfo &&
                oldKeyInfo.algorithm === SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES);
            // Log all relevant state for easier parsing of debug logs.
            logger_1.logger.log({
                keyBackupInfo,
                setupNewKeyBackup,
                setupNewSecretStorage,
                storageExists,
                oldKeyInfo,
            });
            if (!storageExists && !keyBackupInfo) {
                // either we don't have anything, or we've been asked to restart
                // from scratch
                logger_1.logger.log("Secret storage does not exist, creating new storage key");
                // if we already have a usable default SSSS key and aren't resetting
                // SSSS just use it. otherwise, create a new one
                // Note: we leave the old SSSS key in place: there could be other
                // secrets using it, in theory. We could move them to the new key but a)
                // that would mean we'd need to prompt for the old passphrase, and b)
                // it's not clear that would be the right thing to do anyway.
                const { keyInfo, privateKey } = yield createSecretStorageKey();
                newKeyId = yield createSSSS(keyInfo, privateKey);
            }
            else if (!storageExists && keyBackupInfo) {
                // we have an existing backup, but no SSSS
                logger_1.logger.log("Secret storage does not exist, using key backup key");
                // if we have the backup key already cached, use it; otherwise use the
                // callback to prompt for the key
                const backupKey = (yield this.getSessionBackupPrivateKey()) || (yield getKeyBackupPassphrase());
                // create a new SSSS key and use the backup key as the new SSSS key
                const opts = {}; // TODO types
                if (keyBackupInfo.auth_data.private_key_salt &&
                    keyBackupInfo.auth_data.private_key_iterations) {
                    // FIXME: ???
                    opts.passphrase = {
                        algorithm: "m.pbkdf2",
                        iterations: keyBackupInfo.auth_data.private_key_iterations,
                        salt: keyBackupInfo.auth_data.private_key_salt,
                        bits: 256,
                    };
                }
                newKeyId = yield createSSSS(opts, backupKey);
                // store the backup key in secret storage
                yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey), [newKeyId]);
                // The backup is trusted because the user provided the private key.
                // Sign the backup with the cross-signing key so the key backup can
                // be trusted via cross-signing.
                yield signKeyBackupWithCrossSigning(keyBackupInfo.auth_data);
                builder.addSessionBackup(keyBackupInfo);
            }
            else {
                // 4S is already set up
                logger_1.logger.log("Secret storage exists");
                if (oldKeyInfo && oldKeyInfo.algorithm === SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES) {
                    // make sure that the default key has the information needed to
                    // check the passphrase
                    yield ensureCanCheckPassphrase(oldKeyId, oldKeyInfo);
                }
            }
            // If we have cross-signing private keys cached, store them in secret
            // storage if they are not there already.
            if (!this.baseApis.cryptoCallbacks.saveCrossSigningKeys &&
                (yield this.isCrossSigningReady()) &&
                (newKeyId || !(yield this.crossSigningInfo.isStoredInSecretStorage(secretStorage)))) {
                logger_1.logger.log("Copying cross-signing private keys from cache to secret storage");
                const crossSigningPrivateKeys = yield this.crossSigningInfo.getCrossSigningKeysFromCache();
                // This is writing to in-memory account data in
                // builder.accountDataClientAdapter so won't fail
                yield CrossSigning_1.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);
            }
            if (setupNewKeyBackup && !keyBackupInfo) {
                logger_1.logger.log("Creating new message key backup version");
                const info = yield this.baseApis.prepareKeyBackupVersion(null /* random key */, 
                // don't write to secret storage, as it will write to this.secretStorage.
                // Here, we want to capture all the side-effects of bootstrapping,
                // and want to write to the local secretStorage object
                { secureSecretStorage: false });
                // write the key ourselves to 4S
                const privateKey = recoverykey_1.decodeRecoveryKey(info.recovery_key);
                yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(privateKey));
                // create keyBackupInfo object to add to builder
                const data = {
                    algorithm: info.algorithm,
                    auth_data: info.auth_data,
                };
                // Sign with cross-signing master key
                yield signKeyBackupWithCrossSigning(data.auth_data);
                // sign with the device fingerprint
                yield this.signObject(data.auth_data);
                builder.addSessionBackup(data);
            }
            // Cache the session backup key
            const sessionBackupKey = yield secretStorage.get('m.megolm_backup.v1');
            if (sessionBackupKey) {
                logger_1.logger.info("Got session backup key from secret storage: caching");
                // fix up the backup key if it's in the wrong format, and replace
                // in secret storage
                const fixedBackupKey = fixBackupKey(sessionBackupKey);
                if (fixedBackupKey) {
                    yield secretStorage.store("m.megolm_backup.v1", fixedBackupKey, [newKeyId || oldKeyId]);
                }
                const decodedBackupKey = new Uint8Array(olmlib.decodeBase64(fixedBackupKey || sessionBackupKey));
                yield builder.addSessionBackupPrivateKeyToCache(decodedBackupKey);
            }
            else if (this.backupManager.getKeyBackupEnabled()) {
                // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in
                // the cache or the user can provide one, and if so, write it to SSSS
                const backupKey = (yield this.getSessionBackupPrivateKey()) || (yield getKeyBackupPassphrase());
                if (!backupKey) {
                    // This will require user intervention to recover from since we don't have the key
                    // backup key anywhere. The user should probably just set up a new key backup and
                    // the key for the new backup will be stored. If we hit this scenario in the wild
                    // with any frequency, we should do more than just log an error.
                    logger_1.logger.error("Key backup is enabled but couldn't get key backup key!");
                    return;
                }
                logger_1.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS");
                yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey));
            }
            const operation = builder.buildOperation();
            yield operation.apply(this);
            // this persists private keys and public keys as trusted,
            // only do this if apply succeeded for now as retry isn't in place yet
            yield builder.persist(this);
            logger_1.logger.log("Secure Secret Storage ready");
        });
    }
    addSecretStorageKey(algorithm, opts, keyID) {
        return this.secretStorage.addKey(algorithm, opts, keyID);
    }
    hasSecretStorageKey(keyID) {
        return this.secretStorage.hasKey(keyID);
    }
    getSecretStorageKey(keyID) {
        return this.secretStorage.getKey(keyID);
    }
    storeSecret(name, secret, keys) {
        return this.secretStorage.store(name, secret, keys);
    }
    getSecret(name) {
        return this.secretStorage.get(name);
    }
    isSecretStored(name, checkKey) {
        return this.secretStorage.isStored(name, checkKey);
    }
    requestSecret(name, devices) {
        if (!devices) {
            devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId));
        }
        return this.secretStorage.request(name, devices);
    }
    getDefaultSecretStorageKeyId() {
        return this.secretStorage.getDefaultKeyId();
    }
    setDefaultSecretStorageKeyId(k) {
        return this.secretStorage.setDefaultKeyId(k);
    }
    checkSecretStorageKey(key, info) {
        return this.secretStorage.checkKey(key, info);
    }
    /**
     * Checks that a given secret storage private key matches a given public key.
     * This can be used by the getSecretStorageKey callback to verify that the
     * private key it is about to supply is the one that was requested.
     *
     * @param {Uint8Array} privateKey The private key
     * @param {string} expectedPublicKey The public key
     * @returns {boolean} true if the key matches, otherwise false
     */
    checkSecretStoragePrivateKey(privateKey, expectedPublicKey) {
        let decryption = null;
        try {
            decryption = new global.Olm.PkDecryption();
            const gotPubkey = decryption.init_with_private_key(privateKey);
            // make sure it agrees with the given pubkey
            return gotPubkey === expectedPublicKey;
        }
        finally {
            if (decryption)
                decryption.free();
        }
    }
    /**
     * Fetches the backup private key, if cached
     * @returns {Promise} the key, if any, or null
     */
    getSessionBackupPrivateKey() {
        return __awaiter(this, void 0, void 0, function* () {
            let key = yield new Promise((resolve) => {
                this.cryptoStore.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                    this.cryptoStore.getSecretStorePrivateKey(txn, resolve, "m.megolm_backup.v1");
                });
            });
            // make sure we have a Uint8Array, rather than a string
            if (key && typeof key === "string") {
                key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key));
                yield this.storeSessionBackupPrivateKey(key);
            }
            if (key && key.ciphertext) {
                const pickleKey = Buffer.from(this.olmDevice._pickleKey);
                const decrypted = yield aes_1.decryptAES(key, pickleKey, "m.megolm_backup.v1");
                key = olmlib.decodeBase64(decrypted);
            }
            return key;
        });
    }
    /**
     * Stores the session backup key to the cache
     * @param {Uint8Array} key the private key
     * @returns {Promise} so you can catch failures
     */
    storeSessionBackupPrivateKey(key) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!(key instanceof Uint8Array)) {
                throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`);
            }
            const pickleKey = Buffer.from(this.olmDevice._pickleKey);
            const encryptedKey = yield aes_1.encryptAES(olmlib.encodeBase64(key), pickleKey, "m.megolm_backup.v1");
            return this.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                this.cryptoStore.storeSecretStorePrivateKey(txn, "m.megolm_backup.v1", encryptedKey);
            });
        });
    }
    /**
     * Checks that a given cross-signing private key matches a given public key.
     * This can be used by the getCrossSigningKey callback to verify that the
     * private key it is about to supply is the one that was requested.
     *
     * @param {Uint8Array} privateKey The private key
     * @param {string} expectedPublicKey The public key
     * @returns {boolean} true if the key matches, otherwise false
     */
    checkCrossSigningPrivateKey(privateKey, expectedPublicKey) {
        let signing = null;
        try {
            signing = new global.Olm.PkSigning();
            const gotPubkey = signing.init_with_seed(privateKey);
            // make sure it agrees with the given pubkey
            return gotPubkey === expectedPublicKey;
        }
        finally {
            if (signing)
                signing.free();
        }
    }
    /**
     * Run various follow-up actions after cross-signing keys have changed locally
     * (either by resetting the keys for the account or by getting them from secret
     * storage), such as signing the current device, upgrading device
     * verifications, etc.
     */
    afterCrossSigningLocalKeyChange() {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.info("Starting cross-signing key change post-processing");
            // sign the current device with the new key, and upload to the server
            const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);
            const signedDevice = yield this.crossSigningInfo.signDevice(this.userId, device);
            logger_1.logger.info(`Starting background key sig upload for ${this.deviceId}`);
            const upload = ({ shouldEmit }) => {
                return this.baseApis.uploadKeySignatures({
                    [this.userId]: {
                        [this.deviceId]: signedDevice,
                    },
                }).then((response) => {
                    const { failures } = response || {};
                    if (Object.keys(failures || []).length > 0) {
                        if (shouldEmit) {
                            this.baseApis.emit("crypto.keySignatureUploadFailure", failures, "afterCrossSigningLocalKeyChange", upload);
                        }
                        throw new errors_1.KeySignatureUploadError("Key upload failed", { failures });
                    }
                    logger_1.logger.info(`Finished background key sig upload for ${this.deviceId}`);
                }).catch(e => {
                    logger_1.logger.error(`Error during background key sig upload for ${this.deviceId}`, e);
                });
            };
            upload({ shouldEmit: true });
            const shouldUpgradeCb = (this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications);
            if (shouldUpgradeCb) {
                logger_1.logger.info("Starting device verification upgrade");
                // Check all users for signatures if upgrade callback present
                // FIXME: do this in batches
                const users = {};
                for (const [userId, crossSigningInfo] of Object.entries(this.deviceList.crossSigningInfo)) {
                    const upgradeInfo = yield this.checkForDeviceVerificationUpgrade(userId, CrossSigning_1.CrossSigningInfo.fromStorage(crossSigningInfo, userId));
                    if (upgradeInfo) {
                        users[userId] = upgradeInfo;
                    }
                }
                if (Object.keys(users).length > 0) {
                    logger_1.logger.info(`Found ${Object.keys(users).length} verif users to upgrade`);
                    try {
                        const usersToUpgrade = yield shouldUpgradeCb({ users: users });
                        if (usersToUpgrade) {
                            for (const userId of usersToUpgrade) {
                                if (userId in users) {
                                    yield this.baseApis.setDeviceVerified(userId, users[userId].crossSigningInfo.getId());
                                }
                            }
                        }
                    }
                    catch (e) {
                        logger_1.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading", e);
                    }
                }
                logger_1.logger.info("Finished device verification upgrade");
            }
            logger_1.logger.info("Finished cross-signing key change post-processing");
        });
    }
    /**
     * Check if a user's cross-signing key is a candidate for upgrading from device
     * verification.
     *
     * @param {string} userId the user whose cross-signing information is to be checked
     * @param {object} crossSigningInfo the cross-signing information to check
     */
    checkForDeviceVerificationUpgrade(userId, crossSigningInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            // only upgrade if this is the first cross-signing key that we've seen for
            // them, and if their cross-signing key isn't already verified
            const trustLevel = this.crossSigningInfo.checkUserTrust(crossSigningInfo);
            if (crossSigningInfo.firstUse && !trustLevel.isVerified()) {
                const devices = this.deviceList.getRawStoredDevicesForUser(userId);
                const deviceIds = yield this.checkForValidDeviceSignature(userId, crossSigningInfo.keys.master, devices);
                if (deviceIds.length) {
                    return {
                        devices: deviceIds.map(deviceId => deviceinfo_1.DeviceInfo.fromStorage(devices[deviceId], deviceId)),
                        crossSigningInfo,
                    };
                }
            }
        });
    }
    /**
     * Check if the cross-signing key is signed by a verified device.
     *
     * @param {string} userId the user ID whose key is being checked
     * @param {object} key the key that is being checked
     * @param {object} devices the user's devices.  Should be a map from device ID
     *     to device info
     */
    checkForValidDeviceSignature(userId, key, // TODO types
    devices) {
        return __awaiter(this, void 0, void 0, function* () {
            const deviceIds = [];
            if (devices && key.signatures && key.signatures[userId]) {
                for (const signame of Object.keys(key.signatures[userId])) {
                    const [, deviceId] = signame.split(':', 2);
                    if (deviceId in devices
                        && devices[deviceId].verified === DeviceVerification.VERIFIED) {
                        try {
                            yield olmlib.verifySignature(this.olmDevice, key, userId, deviceId, devices[deviceId].keys[signame]);
                            deviceIds.push(deviceId);
                        }
                        catch (e) { }
                    }
                }
            }
            return deviceIds;
        });
    }
    /**
     * Get the user's cross-signing key ID.
     *
     * @param {string} [type=master] The type of key to get the ID of.  One of
     *     "master", "self_signing", or "user_signing".  Defaults to "master".
     *
     * @returns {string} the key ID
     */
    getCrossSigningId(type) {
        return this.crossSigningInfo.getId(type);
    }
    /**
     * Get the cross signing information for a given user.
     *
     * @param {string} userId the user ID to get the cross-signing info for.
     *
     * @returns {CrossSigningInfo} the cross signing information for the user.
     */
    getStoredCrossSigningForUser(userId) {
        return this.deviceList.getStoredCrossSigningForUser(userId);
    }
    /**
     * Check whether a given user is trusted.
     *
     * @param {string} userId The ID of the user to check.
     *
     * @returns {UserTrustLevel}
     */
    checkUserTrust(userId) {
        const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);
        if (!userCrossSigning) {
            return new CrossSigning_1.UserTrustLevel(false, false, false);
        }
        return this.crossSigningInfo.checkUserTrust(userCrossSigning);
    }
    /**
     * Check whether a given device is trusted.
     *
     * @param {string} userId The ID of the user whose devices is to be checked.
     * @param {string} deviceId The ID of the device to check
     *
     * @returns {DeviceTrustLevel}
     */
    checkDeviceTrust(userId, deviceId) {
        const device = this.deviceList.getStoredDevice(userId, deviceId);
        return this.checkDeviceInfoTrust(userId, device);
    }
    /**
     * Check whether a given deviceinfo is trusted.
     *
     * @param {string} userId The ID of the user whose devices is to be checked.
     * @param {module:crypto/deviceinfo?} device The device info object to check
     *
     * @returns {DeviceTrustLevel}
     */
    checkDeviceInfoTrust(userId, device) {
        const trustedLocally = !!(device && device.isVerified());
        const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);
        if (device && userCrossSigning) {
            // The trustCrossSignedDevices only affects trust of other people's cross-signing
            // signatures
            const trustCrossSig = this.trustCrossSignedDevices || userId === this.userId;
            return this.crossSigningInfo.checkDeviceTrust(userCrossSigning, device, trustedLocally, trustCrossSig);
        }
        else {
            return new CrossSigning_1.DeviceTrustLevel(false, false, trustedLocally, false);
        }
    }
    /**
     * Check the copy of our cross-signing key that we have in the device list and
     * see if we can get the private key. If so, mark it as trusted.
     */
    checkOwnCrossSigningTrust({ allowPrivateKeyRequests = false, } = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const userId = this.userId;
            // Before proceeding, ensure our cross-signing public keys have been
            // downloaded via the device list.
            yield this.downloadKeys([this.userId]);
            // Also check which private keys are locally cached.
            const crossSigningPrivateKeys = yield this.crossSigningInfo.getCrossSigningKeysFromCache();
            // If we see an update to our own master key, check it against the master
            // key we have and, if it matches, mark it as verified
            // First, get the new cross-signing info
            const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);
            if (!newCrossSigning) {
                logger_1.logger.error("Got cross-signing update event for user " + userId +
                    " but no new cross-signing information found!");
                return;
            }
            const seenPubkey = newCrossSigning.getId();
            const masterChanged = this.crossSigningInfo.getId() !== seenPubkey;
            const masterExistsNotLocallyCached = newCrossSigning.getId() && !crossSigningPrivateKeys.has("master");
            if (masterChanged) {
                logger_1.logger.info("Got new master public key", seenPubkey);
            }
            if (allowPrivateKeyRequests &&
                (masterChanged || masterExistsNotLocallyCached)) {
                logger_1.logger.info("Attempting to retrieve cross-signing master private key");
                let signing = null;
                // It's important for control flow that we leave any errors alone for
                // higher levels to handle so that e.g. cancelling access properly
                // aborts any larger operation as well.
                try {
                    const ret = yield this.crossSigningInfo.getCrossSigningKey('master', seenPubkey);
                    signing = ret[1];
                    logger_1.logger.info("Got cross-signing master private key");
                }
                finally {
                    if (signing)
                        signing.free();
                }
            }
            const oldSelfSigningId = this.crossSigningInfo.getId("self_signing");
            const oldUserSigningId = this.crossSigningInfo.getId("user_signing");
            // Update the version of our keys in our cross-signing object and the local store
            this.storeTrustedSelfKeys(newCrossSigning.keys);
            const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId("self_signing");
            const userSigningChanged = oldUserSigningId !== newCrossSigning.getId("user_signing");
            const selfSigningExistsNotLocallyCached = (newCrossSigning.getId("self_signing") &&
                !crossSigningPrivateKeys.has("self_signing"));
            const userSigningExistsNotLocallyCached = (newCrossSigning.getId("user_signing") &&
                !crossSigningPrivateKeys.has("user_signing"));
            const keySignatures = {};
            if (selfSigningChanged) {
                logger_1.logger.info("Got new self-signing key", newCrossSigning.getId("self_signing"));
            }
            if (allowPrivateKeyRequests &&
                (selfSigningChanged || selfSigningExistsNotLocallyCached)) {
                logger_1.logger.info("Attempting to retrieve cross-signing self-signing private key");
                let signing = null;
                try {
                    const ret = yield this.crossSigningInfo.getCrossSigningKey("self_signing", newCrossSigning.getId("self_signing"));
                    signing = ret[1];
                    logger_1.logger.info("Got cross-signing self-signing private key");
                }
                finally {
                    if (signing)
                        signing.free();
                }
                const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);
                const signedDevice = yield this.crossSigningInfo.signDevice(this.userId, device);
                keySignatures[this.deviceId] = signedDevice;
            }
            if (userSigningChanged) {
                logger_1.logger.info("Got new user-signing key", newCrossSigning.getId("user_signing"));
            }
            if (allowPrivateKeyRequests &&
                (userSigningChanged || userSigningExistsNotLocallyCached)) {
                logger_1.logger.info("Attempting to retrieve cross-signing user-signing private key");
                let signing = null;
                try {
                    const ret = yield this.crossSigningInfo.getCrossSigningKey("user_signing", newCrossSigning.getId("user_signing"));
                    signing = ret[1];
                    logger_1.logger.info("Got cross-signing user-signing private key");
                }
                finally {
                    if (signing)
                        signing.free();
                }
            }
            if (masterChanged) {
                const masterKey = this.crossSigningInfo.keys.master;
                yield this.signObject(masterKey);
                const deviceSig = masterKey.signatures[this.userId]["ed25519:" + this.deviceId];
                // Include only the _new_ device signature in the upload.
                // We may have existing signatures from deleted devices, which will cause
                // the entire upload to fail.
                keySignatures[this.crossSigningInfo.getId()] = Object.assign({}, masterKey, {
                    signatures: {
                        [this.userId]: {
                            ["ed25519:" + this.deviceId]: deviceSig,
                        },
                    },
                });
            }
            const keysToUpload = Object.keys(keySignatures);
            if (keysToUpload.length) {
                const upload = ({ shouldEmit }) => {
                    logger_1.logger.info(`Starting background key sig upload for ${keysToUpload}`);
                    return this.baseApis.uploadKeySignatures({ [this.userId]: keySignatures })
                        .then((response) => {
                        const { failures } = response || {};
                        logger_1.logger.info(`Finished background key sig upload for ${keysToUpload}`);
                        if (Object.keys(failures || []).length > 0) {
                            if (shouldEmit) {
                                this.baseApis.emit("crypto.keySignatureUploadFailure", failures, "checkOwnCrossSigningTrust", upload);
                            }
                            throw new errors_1.KeySignatureUploadError("Key upload failed", { failures });
                        }
                    }).catch(e => {
                        logger_1.logger.error(`Error during background key sig upload for ${keysToUpload}`, e);
                    });
                };
                upload({ shouldEmit: true });
            }
            this.emit("userTrustStatusChanged", userId, this.checkUserTrust(userId));
            if (masterChanged) {
                this.baseApis.emit("crossSigning.keysChanged", {});
                yield this.afterCrossSigningLocalKeyChange();
            }
            // Now we may be able to trust our key backup
            yield this.backupManager.checkKeyBackup();
            // FIXME: if we previously trusted the backup, should we automatically sign
            // the backup with the new key (if not already signed)?
        });
    }
    /**
     * Store a set of keys as our own, trusted, cross-signing keys.
     *
     * @param {object} keys The new trusted set of keys
     */
    storeTrustedSelfKeys(keys) {
        return __awaiter(this, void 0, void 0, function* () {
            if (keys) {
                this.crossSigningInfo.setKeys(keys);
            }
            else {
                this.crossSigningInfo.clearKeys();
            }
            yield this.cryptoStore.doTxn('readwrite', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
                this.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningInfo.keys);
            });
        });
    }
    /**
     * Check if the master key is signed by a verified device, and if so, prompt
     * the application to mark it as verified.
     *
     * @param {string} userId the user ID whose key should be checked
     */
    checkDeviceVerifications(userId) {
        return __awaiter(this, void 0, void 0, function* () {
            const shouldUpgradeCb = (this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications);
            if (!shouldUpgradeCb) {
                // Upgrading skipped when callback is not present.
                return;
            }
            logger_1.logger.info(`Starting device verification upgrade for ${userId}`);
            if (this.crossSigningInfo.keys.user_signing) {
                const crossSigningInfo = this.deviceList.getStoredCrossSigningForUser(userId);
                if (crossSigningInfo) {
                    const upgradeInfo = yield this.checkForDeviceVerificationUpgrade(userId, crossSigningInfo);
                    if (upgradeInfo) {
                        const usersToUpgrade = yield shouldUpgradeCb({
                            users: {
                                [userId]: upgradeInfo,
                            },
                        });
                        if (usersToUpgrade.includes(userId)) {
                            yield this.baseApis.setDeviceVerified(userId, crossSigningInfo.getId());
                        }
                    }
                }
            }
            logger_1.logger.info(`Finished device verification upgrade for ${userId}`);
        });
    }
    setTrustedBackupPubKey(trustedPubKey) {
        return __awaiter(this, void 0, void 0, function* () {
            // This should be redundant post cross-signing is a thing, so just
            // plonk it in localStorage for now.
            this.sessionStore.setLocalTrustedBackupPubKey(trustedPubKey);
            yield this.backupManager.checkKeyBackup();
        });
    }
    /**
     */
    enableLazyLoading() {
        this.lazyLoadMembers = true;
    }
    /**
     * Tell the crypto module to register for MatrixClient events which it needs to
     * listen for
     *
     * @param {external:EventEmitter} eventEmitter event source where we can register
     *    for event notifications
     */
    registerEventHandlers(eventEmitter) {
        eventEmitter.on("RoomMember.membership", (event, member, oldMembership) => {
            try {
                this.onRoomMembership(event, member, oldMembership);
            }
            catch (e) {
                logger_1.logger.error("Error handling membership change:", e);
            }
        });
        eventEmitter.on("toDeviceEvent", this.onToDeviceEvent);
        eventEmitter.on("Room.timeline", this.onTimelineEvent);
        eventEmitter.on("Event.decrypted", this.onTimelineEvent);
    }
    /** Start background processes related to crypto */
    start() {
        this.outgoingRoomKeyRequestManager.start();
    }
    /** Stop background processes related to crypto */
    stop() {
        this.outgoingRoomKeyRequestManager.stop();
        this.deviceList.stop();
        this.dehydrationManager.stop();
    }
    /**
     * Get the Ed25519 key for this device
     *
     * @return {string} base64-encoded ed25519 key.
     */
    getDeviceEd25519Key() {
        return this.olmDevice.deviceEd25519Key;
    }
    /**
     * Get the Curve25519 key for this device
     *
     * @return {string} base64-encoded curve25519 key.
     */
    getDeviceCurve25519Key() {
        return this.olmDevice.deviceCurve25519Key;
    }
    /**
     * Set the global override for whether the client should ever send encrypted
     * messages to unverified devices.  This provides the default for rooms which
     * do not specify a value.
     *
     * @param {boolean} value whether to blacklist all unverified devices by default
     */
    setGlobalBlacklistUnverifiedDevices(value) {
        this.globalBlacklistUnverifiedDevices = value;
    }
    /**
     * @return {boolean} whether to blacklist all unverified devices by default
     */
    getGlobalBlacklistUnverifiedDevices() {
        return this.globalBlacklistUnverifiedDevices;
    }
    /**
     * Set whether sendMessage in a room with unknown and unverified devices
     * should throw an error and not send them message. This has 'Global' for
     * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently
     * no room-level equivalent for this setting.
     *
     * This API is currently UNSTABLE and may change or be removed without notice.
     *
     * @param {boolean} value whether error on unknown devices
     */
    setGlobalErrorOnUnknownDevices(value) {
        this.globalErrorOnUnknownDevices = value;
    }
    /**
     * @return {boolean} whether to error on unknown devices
     *
     * This API is currently UNSTABLE and may change or be removed without notice.
     */
    getGlobalErrorOnUnknownDevices() {
        return this.globalErrorOnUnknownDevices;
    }
    /**
     * Upload the device keys to the homeserver.
     * @return {object} A promise that will resolve when the keys are uploaded.
     */
    uploadDeviceKeys() {
        const deviceKeys = {
            algorithms: this.supportedAlgorithms,
            device_id: this.deviceId,
            keys: this.deviceKeys,
            user_id: this.userId,
        };
        return this.signObject(deviceKeys).then(() => {
            return this.baseApis.uploadKeysRequest({
                device_keys: deviceKeys,
            });
        });
    }
    /**
     * Stores the current one_time_key count which will be handled later (in a call of
     * onSyncCompleted). The count is e.g. coming from a /sync response.
     *
     * @param {Number} currentCount The current count of one_time_keys to be stored
     */
    updateOneTimeKeyCount(currentCount) {
        if (isFinite(currentCount)) {
            this.oneTimeKeyCount = currentCount;
        }
        else {
            throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");
        }
    }
    setNeedsNewFallback(needsNewFallback) {
        this.needsNewFallback = !!needsNewFallback;
    }
    getNeedsNewFallback() {
        return this.needsNewFallback;
    }
    // check if it's time to upload one-time keys, and do so if so.
    maybeUploadOneTimeKeys() {
        // frequency with which to check & upload one-time keys
        const uploadPeriod = 1000 * 60; // one minute
        // max number of keys to upload at once
        // Creating keys can be an expensive operation so we limit the
        // number we generate in one go to avoid blocking the application
        // for too long.
        const maxKeysPerCycle = 5;
        if (this.oneTimeKeyCheckInProgress) {
            return;
        }
        const now = Date.now();
        if (this.lastOneTimeKeyCheck !== null &&
            now - this.lastOneTimeKeyCheck < uploadPeriod) {
            // we've done a key upload recently.
            return;
        }
        this.lastOneTimeKeyCheck = now;
        // We need to keep a pool of one time public keys on the server so that
        // other devices can start conversations with us. But we can only store
        // a finite number of private keys in the olm Account object.
        // To complicate things further then can be a delay between a device
        // claiming a public one time key from the server and it sending us a
        // message. We need to keep the corresponding private key locally until
        // we receive the message.
        // But that message might never arrive leaving us stuck with duff
        // private keys clogging up our local storage.
        // So we need some kind of engineering compromise to balance all of
        // these factors.
        // Check how many keys we can store in the Account object.
        const maxOneTimeKeys = this.olmDevice.maxNumberOfOneTimeKeys();
        // Try to keep at most half that number on the server. This leaves the
        // rest of the slots free to hold keys that have been claimed from the
        // server but we haven't received a message for.
        // If we run out of slots when generating new keys then olm will
        // discard the oldest private keys first. This will eventually clean
        // out stale private keys that won't receive a message.
        const keyLimit = Math.floor(maxOneTimeKeys / 2);
        const uploadLoop = (keyCount) => __awaiter(this, void 0, void 0, function* () {
            while (keyLimit > keyCount || this.getNeedsNewFallback()) {
                // Ask olm to generate new one time keys, then upload them to synapse.
                if (keyLimit > keyCount) {
                    logger_1.logger.info("generating oneTimeKeys");
                    const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle);
                    yield this.olmDevice.generateOneTimeKeys(keysThisLoop);
                }
                if (this.getNeedsNewFallback()) {
                    logger_1.logger.info("generating fallback key");
                    yield this.olmDevice.generateFallbackKey();
                }
                logger_1.logger.info("calling uploadOneTimeKeys");
                const res = yield this.uploadOneTimeKeys();
                if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) {
                    // if the response contains a more up to date value use this
                    // for the next loop
                    keyCount = res.one_time_key_counts.signed_curve25519;
                }
                else {
                    throw new Error("response for uploading keys does not contain " +
                        "one_time_key_counts.signed_curve25519");
                }
            }
        });
        this.oneTimeKeyCheckInProgress = true;
        Promise.resolve().then(() => {
            if (this.oneTimeKeyCount !== undefined) {
                // We already have the current one_time_key count from a /sync response.
                // Use this value instead of asking the server for the current key count.
                return Promise.resolve(this.oneTimeKeyCount);
            }
            // ask the server how many keys we have
            return this.baseApis.uploadKeysRequest({}).then((res) => {
                return res.one_time_key_counts.signed_curve25519 || 0;
            });
        }).then((keyCount) => {
            // Start the uploadLoop with the current keyCount. The function checks if
            // we need to upload new keys or not.
            // If there are too many keys on the server then we don't need to
            // create any more keys.
            return uploadLoop(keyCount);
        }).catch((e) => {
            logger_1.logger.error("Error uploading one-time keys", e.stack || e);
        }).finally(() => {
            // reset oneTimeKeyCount to prevent start uploading based on old data.
            // it will be set again on the next /sync-response
            this.oneTimeKeyCount = undefined;
            this.oneTimeKeyCheckInProgress = false;
        });
    }
    // returns a promise which resolves to the response
    uploadOneTimeKeys() {
        return __awaiter(this, void 0, void 0, function* () {
            const promises = [];
            const fallbackJson = {};
            if (this.getNeedsNewFallback()) {
                const fallbackKeys = yield this.olmDevice.getFallbackKey();
                for (const [keyId, key] of Object.entries(fallbackKeys.curve25519)) {
                    const k = { key, fallback: true };
                    fallbackJson["signed_curve25519:" + keyId] = k;
                    promises.push(this.signObject(k));
                }
                this.setNeedsNewFallback(false);
            }
            const oneTimeKeys = yield this.olmDevice.getOneTimeKeys();
            const oneTimeJson = {};
            for (const keyId in oneTimeKeys.curve25519) {
                if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {
                    const k = {
                        key: oneTimeKeys.curve25519[keyId],
                    };
                    oneTimeJson["signed_curve25519:" + keyId] = k;
                    promises.push(this.signObject(k));
                }
            }
            yield Promise.all(promises);
            const res = yield this.baseApis.uploadKeysRequest({
                "one_time_keys": oneTimeJson,
                "org.matrix.msc2732.fallback_keys": fallbackJson,
            });
            yield this.olmDevice.markKeysAsPublished();
            return res;
        });
    }
    /**
     * Download the keys for a list of users and stores the keys in the session
     * store.
     * @param {Array} userIds The users to fetch.
     * @param {boolean} forceDownload Always download the keys even if cached.
     *
     * @return {Promise} A promise which resolves to a map userId->deviceId->{@link
        * module:crypto/deviceinfo|DeviceInfo}.
     */
    downloadKeys(userIds, forceDownload) {
        return this.deviceList.downloadKeys(userIds, forceDownload);
    }
    /**
     * Get the stored device keys for a user id
     *
     * @param {string} userId the user to list keys for.
     *
     * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't
     * managed to get a list of devices for this user yet.
     */
    getStoredDevicesForUser(userId) {
        return this.deviceList.getStoredDevicesForUser(userId);
    }
    /**
     * Get the stored keys for a single device
     *
     * @param {string} userId
     * @param {string} deviceId
     *
     * @return {module:crypto/deviceinfo?} device, or undefined
     * if we don't know about this device
     */
    getStoredDevice(userId, deviceId) {
        return this.deviceList.getStoredDevice(userId, deviceId);
    }
    /**
     * Save the device list, if necessary
     *
     * @param {number} delay Time in ms before which the save actually happens.
     *     By default, the save is delayed for a short period in order to batch
     *     multiple writes, but this behaviour can be disabled by passing 0.
     *
     * @return {Promise<boolean>} true if the data was saved, false if
     *     it was not (eg. because no changes were pending). The promise
     *     will only resolve once the data is saved, so may take some time
     *     to resolve.
     */
    saveDeviceList(delay) {
        return this.deviceList.saveIfDirty(delay);
    }
    /**
     * Update the blocked/verified state of the given device
     *
     * @param {string} userId owner of the device
     * @param {string} deviceId unique identifier for the device or user's
     * cross-signing public key ID.
     *
     * @param {?boolean} verified whether to mark the device as verified. Null to
     *     leave unchanged.
     *
     * @param {?boolean} blocked whether to mark the device as blocked. Null to
     *      leave unchanged.
     *
     * @param {?boolean} known whether to mark that the user has been made aware of
     *      the existence of this device. Null to leave unchanged
     *
     * @return {Promise<module:crypto/deviceinfo>} updated DeviceInfo
     */
    setDeviceVerification(userId, deviceId, verified, blocked, known) {
        return __awaiter(this, void 0, void 0, function* () {
            // get rid of any `undefined`s here so we can just check
            // for null rather than null or undefined
            if (verified === undefined)
                verified = null;
            if (blocked === undefined)
                blocked = null;
            if (known === undefined)
                known = null;
            // Check if the 'device' is actually a cross signing key
            // The js-sdk's verification treats cross-signing keys as devices
            // and so uses this method to mark them verified.
            const xsk = this.deviceList.getStoredCrossSigningForUser(userId);
            if (xsk && xsk.getId() === deviceId) {
                if (blocked !== null || known !== null) {
                    throw new Error("Cannot set blocked or known for a cross-signing key");
                }
                if (!verified) {
                    throw new Error("Cannot set a cross-signing key as unverified");
                }
                if (!this.crossSigningInfo.getId() && userId === this.crossSigningInfo.userId) {
                    this.storeTrustedSelfKeys(xsk.keys);
                    // This will cause our own user trust to change, so emit the event
                    this.emit("userTrustStatusChanged", this.userId, this.checkUserTrust(userId));
                }
                // Now sign the master key with our user signing key (unless it's ourself)
                if (userId !== this.userId) {
                    logger_1.logger.info("Master key " + xsk.getId() + " for " + userId +
                        " marked verified. Signing...");
                    const device = yield this.crossSigningInfo.signUser(xsk);
                    if (device) {
                        const upload = ({ shouldEmit }) => __awaiter(this, void 0, void 0, function* () {
                            logger_1.logger.info("Uploading signature for " + userId + "...");
                            const response = yield this.baseApis.uploadKeySignatures({
                                [userId]: {
                                    [deviceId]: device,
                                },
                            });
                            const { failures } = response || {};
                            if (Object.keys(failures || []).length > 0) {
                                if (shouldEmit) {
                                    this.baseApis.emit("crypto.keySignatureUploadFailure", failures, "setDeviceVerification", upload);
                                }
                                /* Throwing here causes the process to be cancelled and the other
                                * user to be notified */
                                throw new errors_1.KeySignatureUploadError("Key upload failed", { failures });
                            }
                        });
                        yield upload({ shouldEmit: true });
                        // This will emit events when it comes back down the sync
                        // (we could do local echo to speed things up)
                    }
                    return device; // TODO types
                }
                else {
                    return xsk;
                }
            }
            const devices = this.deviceList.getRawStoredDevicesForUser(userId);
            if (!devices || !devices[deviceId]) {
                throw new Error("Unknown device " + userId + ":" + deviceId);
            }
            const dev = devices[deviceId];
            let verificationStatus = dev.verified;
            if (verified) {
                verificationStatus = DeviceVerification.VERIFIED;
            }
            else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) {
                verificationStatus = DeviceVerification.UNVERIFIED;
            }
            if (blocked) {
                verificationStatus = DeviceVerification.BLOCKED;
            }
            else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) {
                verificationStatus = DeviceVerification.UNVERIFIED;
            }
            let knownStatus = dev.known;
            if (known !== null) {
                knownStatus = known;
            }
            if (dev.verified !== verificationStatus || dev.known !== knownStatus) {
                dev.verified = verificationStatus;
                dev.known = knownStatus;
                this.deviceList.storeDevicesForUser(userId, devices);
                this.deviceList.saveIfDirty();
            }
            // do cross-signing
            if (verified && userId === this.userId) {
                logger_1.logger.info("Own device " + deviceId + " marked verified: signing");
                // Signing only needed if other device not already signed
                let device;
                const deviceTrust = this.checkDeviceTrust(userId, deviceId);
                if (deviceTrust.isCrossSigningVerified()) {
                    logger_1.logger.log(`Own device ${deviceId} already cross-signing verified`);
                }
                else {
                    device = yield this.crossSigningInfo.signDevice(userId, deviceinfo_1.DeviceInfo.fromStorage(dev, deviceId));
                }
                if (device) {
                    const upload = ({ shouldEmit }) => __awaiter(this, void 0, void 0, function* () {
                        logger_1.logger.info("Uploading signature for " + deviceId);
                        const response = yield this.baseApis.uploadKeySignatures({
                            [userId]: {
                                [deviceId]: device,
                            },
                        });
                        const { failures } = response || {};
                        if (Object.keys(failures || []).length > 0) {
                            if (shouldEmit) {
                                this.baseApis.emit("crypto.keySignatureUploadFailure", failures, "setDeviceVerification", upload);
                            }
                            throw new errors_1.KeySignatureUploadError("Key upload failed", { failures });
                        }
                    });
                    yield upload({ shouldEmit: true });
                    // XXX: we'll need to wait for the device list to be updated
                }
            }
            const deviceObj = deviceinfo_1.DeviceInfo.fromStorage(dev, deviceId);
            this.emit("deviceVerificationChanged", userId, deviceId, deviceObj);
            return deviceObj;
        });
    }
    findVerificationRequestDMInProgress(roomId) {
        return this.inRoomVerificationRequests.findRequestInProgress(roomId);
    }
    getVerificationRequestsToDeviceInProgress(userId) {
        return this.toDeviceVerificationRequests.getRequestsInProgress(userId);
    }
    requestVerificationDM(userId, roomId) {
        const existingRequest = this.inRoomVerificationRequests.findRequestInProgress(roomId);
        if (existingRequest) {
            return Promise.resolve(existingRequest);
        }
        const channel = new InRoomChannel_1.InRoomChannel(this.baseApis, roomId, userId);
        return this.requestVerificationWithChannel(userId, channel, this.inRoomVerificationRequests);
    }
    requestVerification(userId, devices) {
        if (!devices) {
            devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(userId));
        }
        const existingRequest = this.toDeviceVerificationRequests.findRequestInProgress(userId, devices);
        if (existingRequest) {
            return Promise.resolve(existingRequest);
        }
        const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, devices, ToDeviceChannel_1.ToDeviceChannel.makeTransactionId());
        return this.requestVerificationWithChannel(userId, channel, this.toDeviceVerificationRequests);
    }
    requestVerificationWithChannel(userId, channel, // TODO types
    requestsMap) {
        return __awaiter(this, void 0, void 0, function* () {
            let request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis);
            // if transaction id is already known, add request
            if (channel.transactionId) {
                requestsMap.setRequestByChannel(channel, request);
            }
            yield request.sendRequest();
            // don't replace the request created by a racing remote echo
            const racingRequest = requestsMap.getRequestByChannel(channel);
            if (racingRequest) {
                request = racingRequest;
            }
            else {
                logger_1.logger.log(`Crypto: adding new request to ` +
                    `requestsByTxnId with id ${channel.transactionId} ${channel.roomId}`);
                requestsMap.setRequestByChannel(channel, request);
            }
            return request;
        });
    }
    beginKeyVerification(method, userId, deviceId, transactionId = null) {
        let request;
        if (transactionId) {
            request = this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId);
            if (!request) {
                throw new Error(`No request found for user ${userId} with ` +
                    `transactionId ${transactionId}`);
            }
        }
        else {
            transactionId = ToDeviceChannel_1.ToDeviceChannel.makeTransactionId();
            const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);
            request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis);
            this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);
        }
        return request.beginKeyVerification(method, { userId, deviceId });
    }
    legacyDeviceVerification(userId, deviceId, method) {
        return __awaiter(this, void 0, void 0, function* () {
            const transactionId = ToDeviceChannel_1.ToDeviceChannel.makeTransactionId();
            const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);
            const request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis);
            this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);
            const verifier = request.beginKeyVerification(method, { userId, deviceId });
            // either reject by an error from verify() while sending .start
            // or resolve when the request receives the
            // local (fake remote) echo for sending the .start event
            yield Promise.race([
                verifier.verify(),
                request.waitFor(r => r.started),
            ]);
            return request;
        });
    }
    /**
     * Get information on the active olm sessions with a user
     * <p>
     * Returns a map from device id to an object with keys 'deviceIdKey' (the
     * device's curve25519 identity key) and 'sessions' (an array of objects in the
     * same format as that returned by
     * {@link module:crypto/OlmDevice#getSessionInfoForDevice}).
     * <p>
     * This method is provided for debugging purposes.
     *
     * @param {string} userId id of user to inspect
     *
     * @return {Promise<Object.<string, {deviceIdKey: string, sessions: object[]}>>}
     */
    getOlmSessionsForUser(userId) {
        return __awaiter(this, void 0, void 0, function* () {
            const devices = this.getStoredDevicesForUser(userId) || [];
            const result = {};
            for (let j = 0; j < devices.length; ++j) {
                const device = devices[j];
                const deviceKey = device.getIdentityKey();
                const sessions = yield this.olmDevice.getSessionInfoForDevice(deviceKey);
                result[device.deviceId] = {
                    deviceIdKey: deviceKey,
                    sessions: sessions,
                };
            }
            return result;
        });
    }
    /**
     * Get the device which sent an event
     *
     * @param {module:models/event.MatrixEvent} event event to be checked
     *
     * @return {module:crypto/deviceinfo?}
     */
    getEventSenderDeviceInfo(event) {
        const senderKey = event.getSenderKey();
        const algorithm = event.getWireContent().algorithm;
        if (!senderKey || !algorithm) {
            return null;
        }
        const forwardingChain = event.getForwardingCurve25519KeyChain();
        if (forwardingChain.length > 0) {
            // we got the key this event from somewhere else
            // TODO: check if we can trust the forwarders.
            return null;
        }
        if (event.isKeySourceUntrusted()) {
            // we got the key for this event from a source that we consider untrusted
            return null;
        }
        // senderKey is the Curve25519 identity key of the device which the event
        // was sent from. In the case of Megolm, it's actually the Curve25519
        // identity key of the device which set up the Megolm session.
        const device = this.deviceList.getDeviceByIdentityKey(algorithm, senderKey);
        if (device === null) {
            // we haven't downloaded the details of this device yet.
            return null;
        }
        // so far so good, but now we need to check that the sender of this event
        // hadn't advertised someone else's Curve25519 key as their own. We do that
        // by checking the Ed25519 claimed by the event (or, in the case of megolm,
        // the event which set up the megolm session), to check that it matches the
        // fingerprint of the purported sending device.
        //
        // (see https://github.com/vector-im/vector-web/issues/2215)
        const claimedKey = event.getClaimedEd25519Key();
        if (!claimedKey) {
            logger_1.logger.warn("Event " + event.getId() + " claims no ed25519 key: " +
                "cannot verify sending device");
            return null;
        }
        if (claimedKey !== device.getFingerprint()) {
            logger_1.logger.warn("Event " + event.getId() + " claims ed25519 key " + claimedKey +
                " but sender device has key " + device.getFingerprint());
            return null;
        }
        return device;
    }
    /**
     * Get information about the encryption of an event
     *
     * @param {module:models/event.MatrixEvent} event event to be checked
     *
     * @return {object} An object with the fields:
     *    - encrypted: whether the event is encrypted (if not encrypted, some of the
     *      other properties may not be set)
     *    - senderKey: the sender's key
     *    - algorithm: the algorithm used to encrypt the event
     *    - authenticated: whether we can be sure that the owner of the senderKey
     *      sent the event
     *    - sender: the sender's device information, if available
     *    - mismatchedSender: if the event's ed25519 and curve25519 keys don't match
     *      (only meaningful if `sender` is set)
     */
    getEventEncryptionInfo(event) {
        const ret = {};
        ret.senderKey = event.getSenderKey();
        ret.algorithm = event.getWireContent().algorithm;
        if (!ret.senderKey || !ret.algorithm) {
            ret.encrypted = false;
            return ret;
        }
        ret.encrypted = true;
        const forwardingChain = event.getForwardingCurve25519KeyChain();
        if (forwardingChain.length > 0 || event.isKeySourceUntrusted()) {
            // we got the key this event from somewhere else
            // TODO: check if we can trust the forwarders.
            ret.authenticated = false;
        }
        else {
            ret.authenticated = true;
        }
        // senderKey is the Curve25519 identity key of the device which the event
        // was sent from. In the case of Megolm, it's actually the Curve25519
        // identity key of the device which set up the Megolm session.
        ret.sender = this.deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey);
        // so far so good, but now we need to check that the sender of this event
        // hadn't advertised someone else's Curve25519 key as their own. We do that
        // by checking the Ed25519 claimed by the event (or, in the case of megolm,
        // the event which set up the megolm session), to check that it matches the
        // fingerprint of the purported sending device.
        //
        // (see https://github.com/vector-im/vector-web/issues/2215)
        const claimedKey = event.getClaimedEd25519Key();
        if (!claimedKey) {
            logger_1.logger.warn("Event " + event.getId() + " claims no ed25519 key: " +
                "cannot verify sending device");
            ret.mismatchedSender = true;
        }
        if (ret.sender && claimedKey !== ret.sender.getFingerprint()) {
            logger_1.logger.warn("Event " + event.getId() + " claims ed25519 key " + claimedKey +
                "but sender device has key " + ret.sender.getFingerprint());
            ret.mismatchedSender = true;
        }
        return ret;
    }
    /**
     * Forces the current outbound group session to be discarded such
     * that another one will be created next time an event is sent.
     *
     * @param {string} roomId The ID of the room to discard the session for
     *
     * This should not normally be necessary.
     */
    forceDiscardSession(roomId) {
        const alg = this.roomEncryptors[roomId];
        if (alg === undefined)
            throw new Error("Room not encrypted");
        if (alg.forceDiscardSession === undefined) {
            throw new Error("Room encryption algorithm doesn't support session discarding");
        }
        alg.forceDiscardSession();
    }
    /**
     * Configure a room to use encryption (ie, save a flag in the cryptoStore).
     *
     * @param {string} roomId The room ID to enable encryption in.
     *
     * @param {object} config The encryption config for the room.
     *
     * @param {boolean=} inhibitDeviceQuery true to suppress device list query for
     *   users in the room (for now). In case lazy loading is enabled,
     *   the device query is always inhibited as the members are not tracked.
     */
    setRoomEncryption(roomId, config, // TODO types
    inhibitDeviceQuery) {
        return __awaiter(this, void 0, void 0, function* () {
            // ignore crypto events with no algorithm defined
            // This will happen if a crypto event is redacted before we fetch the room state
            // It would otherwise just throw later as an unknown algorithm would, but we may
            // as well catch this here
            if (!config.algorithm) {
                logger_1.logger.log("Ignoring setRoomEncryption with no algorithm");
                return;
            }
            // if state is being replayed from storage, we might already have a configuration
            // for this room as they are persisted as well.
            // We just need to make sure the algorithm is initialized in this case.
            // However, if the new config is different,
            // we should bail out as room encryption can't be changed once set.
            const existingConfig = this.roomList.getRoomEncryption(roomId);
            if (existingConfig) {
                if (JSON.stringify(existingConfig) != JSON.stringify(config)) {
                    logger_1.logger.error("Ignoring m.room.encryption event which requests " +
                        "a change of config in " + roomId);
                    return;
                }
            }
            // if we already have encryption in this room, we should ignore this event,
            // as it would reset the encryption algorithm.
            // This is at least expected to be called twice, as sync calls onCryptoEvent
            // for both the timeline and state sections in the /sync response,
            // the encryption event would appear in both.
            // If it's called more than twice though,
            // it signals a bug on client or server.
            const existingAlg = this.roomEncryptors[roomId];
            if (existingAlg) {
                return;
            }
            // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption
            // because it first stores in memory. We should await the promise only
            // after all the in-memory state (roomEncryptors and _roomList) has been updated
            // to avoid races when calling this method multiple times. Hence keep a hold of the promise.
            let storeConfigPromise = null;
            if (!existingConfig) {
                storeConfigPromise = this.roomList.setRoomEncryption(roomId, config);
            }
            const AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm];
            if (!AlgClass) {
                throw new Error("Unable to encrypt with " + config.algorithm);
            }
            const alg = new AlgClass({
                userId: this.userId,
                deviceId: this.deviceId,
                crypto: this,
                olmDevice: this.olmDevice,
                baseApis: this.baseApis,
                roomId: roomId,
                config: config,
            });
            this.roomEncryptors[roomId] = alg;
            if (storeConfigPromise) {
                yield storeConfigPromise;
            }
            if (!this.lazyLoadMembers) {
                logger_1.logger.log("Enabling encryption in " + roomId + "; " +
                    "starting to track device lists for all users therein");
                yield this.trackRoomDevices(roomId);
                // TODO: this flag is only not used from MatrixClient::setRoomEncryption
                // which is never used (inside Element at least)
                // but didn't want to remove it as it technically would
                // be a breaking change.
                if (!inhibitDeviceQuery) {
                    this.deviceList.refreshOutdatedDeviceLists();
                }
            }
            else {
                logger_1.logger.log("Enabling encryption in " + roomId);
            }
        });
    }
    /**
     * Make sure we are tracking the device lists for all users in this room.
     *
     * @param {string} roomId The room ID to start tracking devices in.
     * @returns {Promise} when all devices for the room have been fetched and marked to track
     */
    trackRoomDevices(roomId) {
        const trackMembers = () => __awaiter(this, void 0, void 0, function* () {
            // not an encrypted room
            if (!this.roomEncryptors[roomId]) {
                return;
            }
            const room = this.clientStore.getRoom(roomId);
            if (!room) {
                throw new Error(`Unable to start tracking devices in unknown room ${roomId}`);
            }
            logger_1.logger.log(`Starting to track devices for room ${roomId} ...`);
            const members = yield room.getEncryptionTargetMembers();
            members.forEach((m) => {
                this.deviceList.startTrackingDeviceList(m.userId);
            });
        });
        let promise = this.roomDeviceTrackingState[roomId];
        if (!promise) {
            promise = trackMembers();
            this.roomDeviceTrackingState[roomId] = promise.catch(err => {
                this.roomDeviceTrackingState[roomId] = null;
                throw err;
            });
        }
        return promise;
    }
    /**
     * Try to make sure we have established olm sessions for all known devices for
     * the given users.
     *
     * @param {string[]} users list of user ids
     *
     * @return {Promise} resolves once the sessions are complete, to
     *    an Object mapping from userId to deviceId to
     *    {@link module:crypto~OlmSessionResult}
     */
    ensureOlmSessionsForUsers(users) {
        const devicesByUser = {};
        for (let i = 0; i < users.length; ++i) {
            const userId = users[i];
            devicesByUser[userId] = [];
            const devices = this.getStoredDevicesForUser(userId) || [];
            for (let j = 0; j < devices.length; ++j) {
                const deviceInfo = devices[j];
                const key = deviceInfo.getIdentityKey();
                if (key == this.olmDevice.deviceCurve25519Key) {
                    // don't bother setting up session to ourself
                    continue;
                }
                if (deviceInfo.verified == DeviceVerification.BLOCKED) {
                    // don't bother setting up sessions with blocked users
                    continue;
                }
                devicesByUser[userId].push(deviceInfo);
            }
        }
        return olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser);
    }
    /**
     * Get a list containing all of the room keys
     *
     * @return {module:crypto/OlmDevice.MegolmSessionData[]} a list of session export objects
     */
    exportRoomKeys() {
        return __awaiter(this, void 0, void 0, function* () {
            const exportedSessions = [];
            yield this.cryptoStore.doTxn('readonly', [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {
                this.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (s) => {
                    if (s === null)
                        return;
                    const sess = this.olmDevice.exportInboundGroupSession(s.senderKey, s.sessionId, s.sessionData);
                    delete sess.first_known_index;
                    sess.algorithm = olmlib.MEGOLM_ALGORITHM;
                    exportedSessions.push(sess);
                });
            });
            return exportedSessions;
        });
    }
    /**
     * Import a list of room keys previously exported by exportRoomKeys
     *
     * @param {Object[]} keys a list of session export objects
     * @param {Object} opts
     * @param {Function} opts.progressCallback called with an object which has a stage param
     * @return {Promise} a promise which resolves once the keys have been imported
     */
    importRoomKeys(keys, opts = {}) {
        let successes = 0;
        let failures = 0;
        const total = keys.length;
        function updateProgress() {
            opts.progressCallback({
                stage: "load_keys",
                successes,
                failures,
                total,
            });
        }
        return Promise.all(keys.map((key) => {
            if (!key.room_id || !key.algorithm) {
                logger_1.logger.warn("ignoring room key entry with missing fields", key);
                failures++;
                if (opts.progressCallback) {
                    updateProgress();
                }
                return null;
            }
            const alg = this.getRoomDecryptor(key.room_id, key.algorithm);
            return alg.importRoomKey(key, opts).finally(() => {
                successes++;
                if (opts.progressCallback) {
                    updateProgress();
                }
            });
        }));
    }
    /**
     * Counts the number of end to end session keys that are waiting to be backed up
     * @returns {Promise<number>} Resolves to the number of sessions requiring backup
     */
    countSessionsNeedingBackup() {
        return this.backupManager.countSessionsNeedingBackup();
    }
    /**
     * Perform any background tasks that can be done before a message is ready to
     * send, in order to speed up sending of the message.
     *
     * @param {module:models/room} room the room the event is in
     */
    prepareToEncrypt(room) {
        const alg = this.roomEncryptors[room.roomId];
        if (alg) {
            alg.prepareToEncrypt(room);
        }
    }
    /* eslint-disable valid-jsdoc */ //https://github.com/eslint/eslint/issues/7307
    /**
     * Encrypt an event according to the configuration of the room.
     *
     * @param {module:models/event.MatrixEvent} event  event to be sent
     *
     * @param {module:models/room} room destination room.
     *
     * @return {Promise?} Promise which resolves when the event has been
     *     encrypted, or null if nothing was needed
     */
    /* eslint-enable valid-jsdoc */
    // TODO this return type lies
    encryptEvent(event, room) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!room) {
                throw new Error("Cannot send encrypted messages in unknown rooms");
            }
            const roomId = event.getRoomId();
            const alg = this.roomEncryptors[roomId];
            if (!alg) {
                // MatrixClient has already checked that this room should be encrypted,
                // so this is an unexpected situation.
                throw new Error("Room was previously configured to use encryption, but is " +
                    "no longer. Perhaps the homeserver is hiding the " +
                    "configuration event.");
            }
            if (!this.roomDeviceTrackingState[roomId]) {
                this.trackRoomDevices(roomId);
            }
            // wait for all the room devices to be loaded
            yield this.roomDeviceTrackingState[roomId];
            let content = event.getContent();
            // If event has an m.relates_to then we need
            // to put this on the wrapping event instead
            const mRelatesTo = content['m.relates_to'];
            if (mRelatesTo) {
                // Clone content here so we don't remove `m.relates_to` from the local-echo
                content = Object.assign({}, content);
                delete content['m.relates_to'];
            }
            const encryptedContent = yield alg.encryptMessage(room, event.getType(), content);
            if (mRelatesTo) {
                encryptedContent['m.relates_to'] = mRelatesTo;
            }
            event.makeEncrypted("m.room.encrypted", encryptedContent, this.olmDevice.deviceCurve25519Key, this.olmDevice.deviceEd25519Key);
        });
    }
    /**
     * Decrypt a received event
     *
     * @param {MatrixEvent} event
     *
     * @return {Promise<module:crypto~EventDecryptionResult>} resolves once we have
     *  finished decrypting. Rejects with an `algorithms.DecryptionError` if there
     *  is a problem decrypting the event.
     */
    decryptEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (event.isRedacted()) {
                const redactionEvent = new event_1.MatrixEvent(event.getUnsigned().redacted_because);
                const decryptedEvent = yield this.decryptEvent(redactionEvent);
                return {
                    clearEvent: {
                        room_id: event.getRoomId(),
                        type: "m.room.message",
                        content: {},
                        unsigned: {
                            redacted_because: decryptedEvent.clearEvent,
                        },
                    },
                };
            }
            else {
                const content = event.getWireContent();
                const alg = this.getRoomDecryptor(event.getRoomId(), content.algorithm);
                return yield alg.decryptEvent(event);
            }
        });
    }
    /**
     * Handle the notification from /sync or /keys/changes that device lists have
     * been changed.
     *
     * @param {Object} syncData Object containing sync tokens associated with this sync
     * @param {Object} syncDeviceLists device_lists field from /sync, or response from
     * /keys/changes
     */
    handleDeviceListChanges(syncData, syncDeviceLists) {
        return __awaiter(this, void 0, void 0, function* () {
            // Initial syncs don't have device change lists. We'll either get the complete list
            // of changes for the interval or will have invalidated everything in willProcessSync
            if (!syncData.oldSyncToken)
                return;
            // Here, we're relying on the fact that we only ever save the sync data after
            // sucessfully saving the device list data, so we're guaranteed that the device
            // list store is at least as fresh as the sync token from the sync store, ie.
            // any device changes received in sync tokens prior to the 'next' token here
            // have been processed and are reflected in the current device list.
            // If we didn't make this assumption, we'd have to use the /keys/changes API
            // to get key changes between the sync token in the device list and the 'old'
            // sync token used here to make sure we didn't miss any.
            yield this.evalDeviceListChanges(syncDeviceLists);
        });
    }
    /**
     * Send a request for some room keys, if we have not already done so
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     * @param {Array<{userId: string, deviceId: string}>} recipients
     * @param {boolean} resend whether to resend the key request if there is
     *    already one
     *
     * @return {Promise} a promise that resolves when the key request is queued
     */
    requestRoomKey(requestBody, recipients, resend = false) {
        return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(requestBody, recipients, resend).then(() => {
            if (this.sendKeyRequestsImmediately) {
                this.outgoingRoomKeyRequestManager.sendQueuedRequests();
            }
        }).catch((e) => {
            // this normally means we couldn't talk to the store
            logger_1.logger.error('Error requesting key for event', e);
        });
    }
    /**
     * Cancel any earlier room key request
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    parameters to match for cancellation
     */
    cancelRoomKeyRequest(requestBody) {
        this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)
            .catch((e) => {
            logger_1.logger.warn("Error clearing pending room key requests", e);
        });
    }
    /**
     * Re-send any outgoing key requests, eg after verification
     * @returns {Promise}
     */
    cancelAndResendAllOutgoingKeyRequests() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests();
        });
    }
    /**
     * handle an m.room.encryption event
     *
     * @param {module:models/event.MatrixEvent} event encryption event
     */
    onCryptoEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const roomId = event.getRoomId();
            const content = event.getContent();
            try {
                // inhibit the device list refresh for now - it will happen once we've
                // finished processing the sync, in onSyncCompleted.
                yield this.setRoomEncryption(roomId, content, true);
            }
            catch (e) {
                logger_1.logger.error("Error configuring encryption in room " + roomId +
                    ":", e);
            }
        });
    }
    /**
     * Called before the result of a sync is processed
     *
     * @param {Object} syncData  the data from the 'MatrixClient.sync' event
     */
    onSyncWillProcess(syncData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!syncData.oldSyncToken) {
                // If there is no old sync token, we start all our tracking from
                // scratch, so mark everything as untracked. onCryptoEvent will
                // be called for all e2e rooms during the processing of the sync,
                // at which point we'll start tracking all the users of that room.
                logger_1.logger.log("Initial sync performed - resetting device tracking state");
                this.deviceList.stopTrackingAllDeviceLists();
                // we always track our own device list (for key backups etc)
                this.deviceList.startTrackingDeviceList(this.userId);
                this.roomDeviceTrackingState = {};
            }
            this.sendKeyRequestsImmediately = false;
        });
    }
    /**
     * handle the completion of a /sync
     *
     * This is called after the processing of each successful /sync response.
     * It is an opportunity to do a batch process on the information received.
     *
     * @param {Object} syncData  the data from the 'MatrixClient.sync' event
     */
    onSyncCompleted(syncData) {
        return __awaiter(this, void 0, void 0, function* () {
            this.deviceList.setSyncToken(syncData.nextSyncToken);
            this.deviceList.saveIfDirty();
            // we always track our own device list (for key backups etc)
            this.deviceList.startTrackingDeviceList(this.userId);
            this.deviceList.refreshOutdatedDeviceLists();
            // we don't start uploading one-time keys until we've caught up with
            // to-device messages, to help us avoid throwing away one-time-keys that we
            // are about to receive messages for
            // (https://github.com/vector-im/element-web/issues/2782).
            if (!syncData.catchingUp) {
                this.maybeUploadOneTimeKeys();
                this.processReceivedRoomKeyRequests();
                // likewise don't start requesting keys until we've caught up
                // on to_device messages, otherwise we'll request keys that we're
                // just about to get.
                this.outgoingRoomKeyRequestManager.sendQueuedRequests();
                // Sync has finished so send key requests straight away.
                this.sendKeyRequestsImmediately = true;
            }
        });
    }
    /**
     * Trigger the appropriate invalidations and removes for a given
     * device list
     *
     * @param {Object} deviceLists device_lists field from /sync, or response from
     * /keys/changes
     */
    evalDeviceListChanges(deviceLists) {
        return __awaiter(this, void 0, void 0, function* () {
            if (deviceLists.changed && Array.isArray(deviceLists.changed)) {
                deviceLists.changed.forEach((u) => {
                    this.deviceList.invalidateUserDeviceList(u);
                });
            }
            if (deviceLists.left && Array.isArray(deviceLists.left) &&
                deviceLists.left.length) {
                // Check we really don't share any rooms with these users
                // any more: the server isn't required to give us the
                // exact correct set.
                const e2eUserIds = new Set(yield this.getTrackedE2eUsers());
                deviceLists.left.forEach((u) => {
                    if (!e2eUserIds.has(u)) {
                        this.deviceList.stopTrackingDeviceList(u);
                    }
                });
            }
        });
    }
    /**
     * Get a list of all the IDs of users we share an e2e room with
     * for which we are tracking devices already
     *
     * @returns {string[]} List of user IDs
     */
    getTrackedE2eUsers() {
        return __awaiter(this, void 0, void 0, function* () {
            const e2eUserIds = [];
            for (const room of this.getTrackedE2eRooms()) {
                const members = yield room.getEncryptionTargetMembers();
                for (const member of members) {
                    e2eUserIds.push(member.userId);
                }
            }
            return e2eUserIds;
        });
    }
    /**
     * Get a list of the e2e-enabled rooms we are members of,
     * and for which we are already tracking the devices
     *
     * @returns {module:models.Room[]}
     */
    getTrackedE2eRooms() {
        return this.clientStore.getRooms().filter((room) => {
            // check for rooms with encryption enabled
            const alg = this.roomEncryptors[room.roomId];
            if (!alg) {
                return false;
            }
            if (!this.roomDeviceTrackingState[room.roomId]) {
                return false;
            }
            // ignore any rooms which we have left
            const myMembership = room.getMyMembership();
            return myMembership === "join" || myMembership === "invite";
        });
    }
    /**
     * Handle a key event
     *
     * @private
     * @param {module:models/event.MatrixEvent} event key event
     */
    onRoomKeyEvent(event) {
        const content = event.getContent();
        if (!content.room_id || !content.algorithm) {
            logger_1.logger.error("key event is missing fields");
            return;
        }
        if (!this.backupManager.checkedForBackup) {
            // don't bother awaiting on this - the important thing is that we retry if we
            // haven't managed to check before
            this.backupManager.checkAndStart();
        }
        const alg = this.getRoomDecryptor(content.room_id, content.algorithm);
        alg.onRoomKeyEvent(event);
    }
    /**
     * Handle a key withheld event
     *
     * @private
     * @param {module:models/event.MatrixEvent} event key withheld event
     */
    onRoomKeyWithheldEvent(event) {
        const content = event.getContent();
        if ((content.code !== "m.no_olm" && (!content.room_id || !content.session_id))
            || !content.algorithm || !content.sender_key) {
            logger_1.logger.error("key withheld event is missing fields");
            return;
        }
        logger_1.logger.info(`Got room key withheld event from ${event.getSender()} (${content.sender_key}) `
            + `for ${content.algorithm}/${content.room_id}/${content.session_id} `
            + `with reason ${content.code} (${content.reason})`);
        const alg = this.getRoomDecryptor(content.room_id, content.algorithm);
        if (alg.onRoomKeyWithheldEvent) {
            alg.onRoomKeyWithheldEvent(event);
        }
        if (!content.room_id) {
            // retry decryption for all events sent by the sender_key.  This will
            // update the events to show a message indicating that the olm session was
            // wedged.
            const roomDecryptors = this.getRoomDecryptors(content.algorithm);
            for (const decryptor of roomDecryptors) {
                decryptor.retryDecryptionFromSender(content.sender_key);
            }
        }
    }
    /**
     * Handle a general key verification event.
     *
     * @private
     * @param {module:models/event.MatrixEvent} event verification start event
     */
    onKeyVerificationMessage(event) {
        if (!ToDeviceChannel_1.ToDeviceChannel.validateEvent(event, this.baseApis)) {
            return;
        }
        const createRequest = event => {
            if (!ToDeviceChannel_1.ToDeviceChannel.canCreateRequest(ToDeviceChannel_1.ToDeviceChannel.getEventType(event))) {
                return;
            }
            const content = event.getContent();
            const deviceId = content && content.from_device;
            if (!deviceId) {
                return;
            }
            const userId = event.getSender();
            const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId]);
            return new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis);
        };
        this.handleVerificationEvent(event, this.toDeviceVerificationRequests, createRequest);
    }
    handleVerificationEvent(event, requestsMap, // TODO types
    createRequest, // TODO types
    isLiveEvent = true) {
        return __awaiter(this, void 0, void 0, function* () {
            let request = requestsMap.getRequest(event);
            let isNewRequest = false;
            if (!request) {
                request = createRequest(event);
                // a request could not be made from this event, so ignore event
                if (!request) {
                    logger_1.logger.log(`Crypto: could not find VerificationRequest for ` +
                        `${event.getType()}, and could not create one, so ignoring.`);
                    return;
                }
                isNewRequest = true;
                requestsMap.setRequest(event, request);
            }
            event.setVerificationRequest(request);
            try {
                yield request.channel.handleEvent(event, request, isLiveEvent);
            }
            catch (err) {
                logger_1.logger.error("error while handling verification event: " + err.message);
            }
            const shouldEmit = isNewRequest &&
                !request.initiatedByMe &&
                !request.invalid && // check it has enough events to pass the UNSENT stage
                !request.observeOnly;
            if (shouldEmit) {
                this.baseApis.emit("crypto.verification.request", request);
            }
        });
    }
    /**
     * Handle a toDevice event that couldn't be decrypted
     *
     * @private
     * @param {module:models/event.MatrixEvent} event undecryptable event
     */
    onToDeviceBadEncrypted(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const content = event.getWireContent();
            const sender = event.getSender();
            const algorithm = content.algorithm;
            const deviceKey = content.sender_key;
            // retry decryption for all events sent by the sender_key.  This will
            // update the events to show a message indicating that the olm session was
            // wedged.
            const retryDecryption = () => {
                const roomDecryptors = this.getRoomDecryptors(olmlib.MEGOLM_ALGORITHM);
                for (const decryptor of roomDecryptors) {
                    decryptor.retryDecryptionFromSender(deviceKey);
                }
            };
            if (sender === undefined || deviceKey === undefined || deviceKey === undefined) {
                return;
            }
            // check when we last forced a new session with this device: if we've already done so
            // recently, don't do it again.
            this.lastNewSessionForced[sender] = this.lastNewSessionForced[sender] || {};
            const lastNewSessionForced = this.lastNewSessionForced[sender][deviceKey] || 0;
            if (lastNewSessionForced + MIN_FORCE_SESSION_INTERVAL_MS > Date.now()) {
                logger_1.logger.debug("New session already forced with device " + sender + ":" + deviceKey +
                    " at " + lastNewSessionForced + ": not forcing another");
                yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", true);
                retryDecryption();
                return;
            }
            // establish a new olm session with this device since we're failing to decrypt messages
            // on a current session.
            // Note that an undecryptable message from another device could easily be spoofed -
            // is there anything we can do to mitigate this?
            let device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);
            if (!device) {
                // if we don't know about the device, fetch the user's devices again
                // and retry before giving up
                yield this.downloadKeys([sender], false);
                device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);
                if (!device) {
                    logger_1.logger.info("Couldn't find device for identity key " + deviceKey +
                        ": not re-establishing session");
                    yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", false);
                    retryDecryption();
                    return;
                }
            }
            const devicesByUser = {};
            devicesByUser[sender] = [device];
            yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, true);
            this.lastNewSessionForced[sender][deviceKey] = Date.now();
            // Now send a blank message on that session so the other side knows about it.
            // (The keyshare request is sent in the clear so that won't do)
            // We send this first such that, as long as the toDevice messages arrive in the
            // same order we sent them, the other end will get this first, set up the new session,
            // then get the keyshare request and send the key over this new session (because it
            // is the session it has most recently received a message on).
            const encryptedContent = {
                algorithm: olmlib.OLM_ALGORITHM,
                sender_key: this.olmDevice.deviceCurve25519Key,
                ciphertext: {},
            };
            yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, sender, device, { type: "m.dummy" });
            yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", true);
            retryDecryption();
            yield this.baseApis.sendToDevice("m.room.encrypted", {
                [sender]: {
                    [device.deviceId]: encryptedContent,
                },
            });
            // Most of the time this probably won't be necessary since we'll have queued up a key request when
            // we failed to decrypt the message and will be waiting a bit for the key to arrive before sending
            // it. This won't always be the case though so we need to re-send any that have already been sent
            // to avoid races.
            const requestsToResend = yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(sender, device.deviceId);
            for (const keyReq of requestsToResend) {
                this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true);
            }
        });
    }
    /**
     * Handle a change in the membership state of a member of a room
     *
     * @private
     * @param {module:models/event.MatrixEvent} event  event causing the change
     * @param {module:models/room-member} member  user whose membership changed
     * @param {string=} oldMembership  previous membership
     */
    onRoomMembership(event, member, oldMembership) {
        // this event handler is registered on the *client* (as opposed to the room
        // member itself), which means it is only called on changes to the *live*
        // membership state (ie, it is not called when we back-paginate, nor when
        // we load the state in the initialsync).
        //
        // Further, it is automatically registered and called when new members
        // arrive in the room.
        const roomId = member.roomId;
        const alg = this.roomEncryptors[roomId];
        if (!alg) {
            // not encrypting in this room
            return;
        }
        // only mark users in this room as tracked if we already started tracking in this room
        // this way we don't start device queries after sync on behalf of this room which we won't use
        // the result of anyway, as we'll need to do a query again once all the members are fetched
        // by calling _trackRoomDevices
        if (this.roomDeviceTrackingState[roomId]) {
            if (member.membership == 'join') {
                logger_1.logger.log('Join event for ' + member.userId + ' in ' + roomId);
                // make sure we are tracking the deviceList for this user
                this.deviceList.startTrackingDeviceList(member.userId);
            }
            else if (member.membership == 'invite' &&
                this.clientStore.getRoom(roomId).shouldEncryptForInvitedMembers()) {
                logger_1.logger.log('Invite event for ' + member.userId + ' in ' + roomId);
                this.deviceList.startTrackingDeviceList(member.userId);
            }
        }
        alg.onRoomMembership(event, member, oldMembership);
    }
    /**
     * Called when we get an m.room_key_request event.
     *
     * @private
     * @param {module:models/event.MatrixEvent} event key request event
     */
    onRoomKeyRequestEvent(event) {
        const content = event.getContent();
        if (content.action === "request") {
            // Queue it up for now, because they tend to arrive before the room state
            // events at initial sync, and we want to see if we know anything about the
            // room before passing them on to the app.
            const req = new IncomingRoomKeyRequest(event);
            this.receivedRoomKeyRequests.push(req);
        }
        else if (content.action === "request_cancellation") {
            const req = new IncomingRoomKeyRequestCancellation(event);
            this.receivedRoomKeyRequestCancellations.push(req);
        }
    }
    /**
     * Process any m.room_key_request events which were queued up during the
     * current sync.
     *
     * @private
     */
    processReceivedRoomKeyRequests() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.processingRoomKeyRequests) {
                // we're still processing last time's requests; keep queuing new ones
                // up for now.
                return;
            }
            this.processingRoomKeyRequests = true;
            try {
                // we need to grab and clear the queues in the synchronous bit of this method,
                // so that we don't end up racing with the next /sync.
                const requests = this.receivedRoomKeyRequests;
                this.receivedRoomKeyRequests = [];
                const cancellations = this.receivedRoomKeyRequestCancellations;
                this.receivedRoomKeyRequestCancellations = [];
                // Process all of the requests, *then* all of the cancellations.
                //
                // This makes sure that if we get a request and its cancellation in the
                // same /sync result, then we process the request before the
                // cancellation (and end up with a cancelled request), rather than the
                // cancellation before the request (and end up with an outstanding
                // request which should have been cancelled.)
                yield Promise.all(requests.map((req) => this.processReceivedRoomKeyRequest(req)));
                yield Promise.all(cancellations.map((cancellation) => this.processReceivedRoomKeyRequestCancellation(cancellation)));
            }
            catch (e) {
                logger_1.logger.error(`Error processing room key requsts: ${e}`);
            }
            finally {
                this.processingRoomKeyRequests = false;
            }
        });
    }
    /**
     * Helper for processReceivedRoomKeyRequests
     *
     * @param {IncomingRoomKeyRequest} req
     */
    processReceivedRoomKeyRequest(req) {
        return __awaiter(this, void 0, void 0, function* () {
            const userId = req.userId;
            const deviceId = req.deviceId;
            const body = req.requestBody;
            const roomId = body.room_id;
            const alg = body.algorithm;
            logger_1.logger.log(`m.room_key_request from ${userId}:${deviceId}` +
                ` for ${roomId} / ${body.session_id} (id ${req.requestId})`);
            if (userId !== this.userId) {
                if (!this.roomEncryptors[roomId]) {
                    logger_1.logger.debug(`room key request for unencrypted room ${roomId}`);
                    return;
                }
                const encryptor = this.roomEncryptors[roomId];
                const device = this.deviceList.getStoredDevice(userId, deviceId);
                if (!device) {
                    logger_1.logger.debug(`Ignoring keyshare for unknown device ${userId}:${deviceId}`);
                    return;
                }
                try {
                    yield encryptor.reshareKeyWithDevice(body.sender_key, body.session_id, userId, device);
                }
                catch (e) {
                    logger_1.logger.warn("Failed to re-share keys for session " + body.session_id +
                        " with device " + userId + ":" + device.deviceId, e);
                }
                return;
            }
            if (deviceId === this.deviceId) {
                // We'll always get these because we send room key requests to
                // '*' (ie. 'all devices') which includes the sending device,
                // so ignore requests from ourself because apart from it being
                // very silly, it won't work because an Olm session cannot send
                // messages to itself.
                // The log here is probably superfluous since we know this will
                // always happen, but let's log anyway for now just in case it
                // causes issues.
                logger_1.logger.log("Ignoring room key request from ourselves");
                return;
            }
            // todo: should we queue up requests we don't yet have keys for,
            // in case they turn up later?
            // if we don't have a decryptor for this room/alg, we don't have
            // the keys for the requested events, and can drop the requests.
            if (!this.roomDecryptors[roomId]) {
                logger_1.logger.log(`room key request for unencrypted room ${roomId}`);
                return;
            }
            const decryptor = this.roomDecryptors[roomId][alg];
            if (!decryptor) {
                logger_1.logger.log(`room key request for unknown alg ${alg} in room ${roomId}`);
                return;
            }
            if (!(yield decryptor.hasKeysForKeyRequest(req))) {
                logger_1.logger.log(`room key request for unknown session ${roomId} / ` +
                    body.session_id);
                return;
            }
            req.share = () => {
                decryptor.shareKeysWithDevice(req);
            };
            // if the device is verified already, share the keys
            if (this.checkDeviceTrust(userId, deviceId).isVerified()) {
                logger_1.logger.log('device is already verified: sharing keys');
                req.share();
                return;
            }
            this.emit("crypto.roomKeyRequest", req);
        });
    }
    /**
     * Helper for processReceivedRoomKeyRequests
     *
     * @param {IncomingRoomKeyRequestCancellation} cancellation
     */
    processReceivedRoomKeyRequestCancellation(cancellation) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.log(`m.room_key_request cancellation for ${cancellation.userId}:` +
                `${cancellation.deviceId} (id ${cancellation.requestId})`);
            // we should probably only notify the app of cancellations we told it
            // about, but we don't currently have a record of that, so we just pass
            // everything through.
            this.emit("crypto.roomKeyRequestCancellation", cancellation);
        });
    }
    /**
     * Get a decryptor for a given room and algorithm.
     *
     * If we already have a decryptor for the given room and algorithm, return
     * it. Otherwise try to instantiate it.
     *
     * @private
     *
     * @param {string?} roomId   room id for decryptor. If undefined, a temporary
     * decryptor is instantiated.
     *
     * @param {string} algorithm  crypto algorithm
     *
     * @return {module:crypto.algorithms.base.DecryptionAlgorithm}
     *
     * @raises {module:crypto.algorithms.DecryptionError} if the algorithm is
     * unknown
     */
    getRoomDecryptor(roomId, algorithm) {
        let decryptors;
        let alg;
        roomId = roomId || null;
        if (roomId) {
            decryptors = this.roomDecryptors[roomId];
            if (!decryptors) {
                this.roomDecryptors[roomId] = decryptors = {};
            }
            alg = decryptors[algorithm];
            if (alg) {
                return alg;
            }
        }
        const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];
        if (!AlgClass) {
            throw new algorithms.DecryptionError('UNKNOWN_ENCRYPTION_ALGORITHM', 'Unknown encryption algorithm "' + algorithm + '".');
        }
        alg = new AlgClass({
            userId: this.userId,
            crypto: this,
            olmDevice: this.olmDevice,
            baseApis: this.baseApis,
            roomId: roomId,
        });
        if (decryptors) {
            decryptors[algorithm] = alg;
        }
        return alg;
    }
    /**
     * Get all the room decryptors for a given encryption algorithm.
     *
     * @param {string} algorithm The encryption algorithm
     *
     * @return {array} An array of room decryptors
     */
    getRoomDecryptors(algorithm) {
        const decryptors = [];
        for (const d of Object.values(this.roomDecryptors)) {
            if (algorithm in d) {
                decryptors.push(d[algorithm]);
            }
        }
        return decryptors;
    }
    /**
     * sign the given object with our ed25519 key
     *
     * @param {Object} obj  Object to which we will add a 'signatures' property
     */
    signObject(obj) {
        return __awaiter(this, void 0, void 0, function* () {
            const sigs = obj.signatures || {};
            const unsigned = obj.unsigned;
            delete obj.signatures;
            delete obj.unsigned;
            sigs[this.userId] = sigs[this.userId] || {};
            sigs[this.userId]["ed25519:" + this.deviceId] = yield this.olmDevice.sign(another_json_1.default.stringify(obj));
            obj.signatures = sigs;
            if (unsigned !== undefined)
                obj.unsigned = unsigned;
        });
    }
}
exports.Crypto = Crypto;
/**
 * Fix up the backup key, that may be in the wrong format due to a bug in a
 * migration step.  Some backup keys were stored as a comma-separated list of
 * integers, rather than a base64-encoded byte array.  If this function is
 * passed a string that looks like a list of integers rather than a base64
 * string, it will attempt to convert it to the right format.
 *
 * @param {string} key the key to check
 * @returns {null | string} If the key is in the wrong format, then the fixed
 * key will be returned. Otherwise null will be returned.
 *
 */
function fixBackupKey(key) {
    if (typeof key !== "string" || key.indexOf(",") < 0) {
        return null;
    }
    const fixedKey = Uint8Array.from(key.split(","), x => parseInt(x));
    return olmlib.encodeBase64(fixedKey);
}
exports.fixBackupKey = fixBackupKey;
/**
 * The parameters of a room key request. The details of the request may
 * vary with the crypto algorithm, but the management and storage layers for
 * outgoing requests expect it to have 'room_id' and 'session_id' properties.
 *
 * @typedef {Object} RoomKeyRequestBody
 */
/**
 * Represents a received m.room_key_request event
 *
 * @property {string} userId    user requesting the key
 * @property {string} deviceId  device requesting the key
 * @property {string} requestId unique id for the request
 * @property {module:crypto~RoomKeyRequestBody} requestBody
 * @property {function()} share  callback which, when called, will ask
 *    the relevant crypto algorithm implementation to share the keys for
 *    this request.
 */
class IncomingRoomKeyRequest {
    constructor(event) {
        const content = event.getContent();
        this.userId = event.getSender();
        this.deviceId = content.requesting_device_id;
        this.requestId = content.request_id;
        this.requestBody = content.body || {};
        this.share = () => {
            throw new Error("don't know how to share keys for this request yet");
        };
    }
}
exports.IncomingRoomKeyRequest = IncomingRoomKeyRequest;
/**
 * Represents a received m.room_key_request cancellation
 *
 * @property {string} userId    user requesting the cancellation
 * @property {string} deviceId  device requesting the cancellation
 * @property {string} requestId unique id for the request to be cancelled
 */
class IncomingRoomKeyRequestCancellation {
    constructor(event) {
        const content = event.getContent();
        this.userId = event.getSender();
        this.deviceId = content.requesting_device_id;
        this.requestId = content.request_id;
    }
}
/**
 * The result of a (successful) call to decryptEvent.
 *
 * @typedef {Object} EventDecryptionResult
 *
 * @property {Object} clearEvent The plaintext payload for the event
 *     (typically containing <tt>type</tt> and <tt>content</tt> fields).
 *
 * @property {?string} senderCurve25519Key Key owned by the sender of this
 *    event.  See {@link module:models/event.MatrixEvent#getSenderKey}.
 *
 * @property {?string} claimedEd25519Key ed25519 key claimed by the sender of
 *    this event. See
 *    {@link module:models/event.MatrixEvent#getClaimedEd25519Key}.
 *
 * @property {?Array<string>} forwardingCurve25519KeyChain list of curve25519
 *     keys involved in telling us about the senderCurve25519Key and
 *     claimedEd25519Key. See
 *     {@link module:models/event.MatrixEvent#getForwardingCurve25519KeyChain}.
 */
/**
 * Fires when we receive a room key request
 *
 * @event module:client~MatrixClient#"crypto.roomKeyRequest"
 * @param {module:crypto~IncomingRoomKeyRequest} req  request details
 */
/**
 * Fires when we receive a room key request cancellation
 *
 * @event module:client~MatrixClient#"crypto.roomKeyRequestCancellation"
 * @param {module:crypto~IncomingRoomKeyRequestCancellation} req
 */
/**
 * Fires when the app may wish to warn the user about something related
 * the end-to-end crypto.
 *
 * @event module:client~MatrixClient#"crypto.warning"
 * @param {string} type One of the strings listed above
 */

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"../ReEmitter":61,"../errors":99,"../logger":106,"../models/event":113,"./CrossSigning":67,"./DeviceList":68,"./EncryptionSetup":69,"./OlmDevice":70,"./OutgoingRoomKeyRequestManager":71,"./SecretStorage":73,"./aes":74,"./algorithms":76,"./backup":80,"./dehydration":81,"./deviceinfo":82,"./key_passphrase":84,"./olmlib":85,"./recoverykey":86,"./store/indexeddb-crypto-store":88,"./verification/IllegalMethod":93,"./verification/QRCode":94,"./verification/SAS":95,"./verification/request/InRoomChannel":96,"./verification/request/ToDeviceChannel":97,"./verification/request/VerificationRequest":98,"another-json":28,"buffer":34,"events":36}],84:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deriveKey = exports.keyFromPassphrase = exports.keyFromAuthData = void 0;
const randomstring_1 = require("../randomstring");
const DEFAULT_ITERATIONS = 500000;
const DEFAULT_BITSIZE = 256;
function keyFromAuthData(authData, password) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!global.Olm) {
            throw new Error("Olm is not available");
        }
        if (!authData.private_key_salt || !authData.private_key_iterations) {
            throw new Error("Salt and/or iterations not found: " +
                "this backup cannot be restored with a passphrase");
        }
        return yield deriveKey(password, authData.private_key_salt, authData.private_key_iterations, authData.private_key_bits || DEFAULT_BITSIZE);
    });
}
exports.keyFromAuthData = keyFromAuthData;
function keyFromPassphrase(password) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!global.Olm) {
            throw new Error("Olm is not available");
        }
        const salt = randomstring_1.randomString(32);
        const key = yield deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE);
        return { key, salt, iterations: DEFAULT_ITERATIONS };
    });
}
exports.keyFromPassphrase = keyFromPassphrase;
function deriveKey(password, salt, iterations, numBits = DEFAULT_BITSIZE) {
    return __awaiter(this, void 0, void 0, function* () {
        const subtleCrypto = global.crypto.subtle;
        const TextEncoder = global.TextEncoder;
        if (!subtleCrypto || !TextEncoder) {
            // TODO: Implement this for node
            throw new Error("Password-based backup is not avaiable on this platform");
        }
        const key = yield subtleCrypto.importKey('raw', new TextEncoder().encode(password), { name: 'PBKDF2' }, false, ['deriveBits']);
        const keybits = yield subtleCrypto.deriveBits({
            name: 'PBKDF2',
            salt: new TextEncoder().encode(salt),
            iterations: iterations,
            hash: 'SHA-512',
        }, key, numBits);
        return new Uint8Array(keybits);
    });
}
exports.deriveKey = deriveKey;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../randomstring":123}],85:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeBase64 = exports.encodeUnpaddedBase64 = exports.encodeBase64 = exports.pkVerify = exports.pkSign = exports.verifySignature = exports.ensureOlmSessionsForDevices = exports.getExistingOlmSessions = exports.encryptMessageForDevice = exports.MEGOLM_BACKUP_ALGORITHM = exports.MEGOLM_ALGORITHM = exports.OLM_ALGORITHM = void 0;
/**
 * @module olmlib
 *
 * Utilities common to olm encryption algorithms
 */
const another_json_1 = __importDefault(require("another-json"));
const logger_1 = require("../logger");
const utils = __importStar(require("../utils"));
var Algorithm;
(function (Algorithm) {
    Algorithm["Olm"] = "m.olm.v1.curve25519-aes-sha2";
    Algorithm["Megolm"] = "m.megolm.v1.aes-sha2";
    Algorithm["MegolmBackup"] = "m.megolm_backup.v1.curve25519-aes-sha2";
})(Algorithm || (Algorithm = {}));
/**
 * matrix algorithm tag for olm
 */
exports.OLM_ALGORITHM = Algorithm.Olm;
/**
 * matrix algorithm tag for megolm
 */
exports.MEGOLM_ALGORITHM = Algorithm.Megolm;
/**
 * matrix algorithm tag for megolm backups
 */
exports.MEGOLM_BACKUP_ALGORITHM = Algorithm.MegolmBackup;
/**
 * Encrypt an event payload for an Olm device
 *
 * @param {Object<string, string>} resultsObject  The `ciphertext` property
 *   of the m.room.encrypted event to which to add our result
 *
 * @param {string} ourUserId
 * @param {string} ourDeviceId
 * @param {module:crypto/OlmDevice} olmDevice olm.js wrapper
 * @param {string} recipientUserId
 * @param {module:crypto/deviceinfo} recipientDevice
 * @param {object} payloadFields fields to include in the encrypted payload
 *
 * Returns a promise which resolves (to undefined) when the payload
 *    has been encrypted into `resultsObject`
 */
function encryptMessageForDevice(resultsObject, ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, payloadFields) {
    return __awaiter(this, void 0, void 0, function* () {
        const deviceKey = recipientDevice.getIdentityKey();
        const sessionId = yield olmDevice.getSessionIdForDevice(deviceKey);
        if (sessionId === null) {
            // If we don't have a session for a device then
            // we can't encrypt a message for it.
            return;
        }
        logger_1.logger.log("Using sessionid " + sessionId + " for device " +
            recipientUserId + ":" + recipientDevice.deviceId);
        const payload = {
            sender: ourUserId,
            // TODO this appears to no longer be used whatsoever
            sender_device: ourDeviceId,
            // Include the Ed25519 key so that the recipient knows what
            // device this message came from.
            // We don't need to include the curve25519 key since the
            // recipient will already know this from the olm headers.
            // When combined with the device keys retrieved from the
            // homeserver signed by the ed25519 key this proves that
            // the curve25519 key and the ed25519 key are owned by
            // the same device.
            keys: {
                "ed25519": olmDevice.deviceEd25519Key,
            },
            // include the recipient device details in the payload,
            // to avoid unknown key attacks, per
            // https://github.com/vector-im/vector-web/issues/2483
            recipient: recipientUserId,
            recipient_keys: {
                "ed25519": recipientDevice.getFingerprint(),
            },
        };
        // TODO: technically, a bunch of that stuff only needs to be included for
        // pre-key messages: after that, both sides know exactly which devices are
        // involved in the session. If we're looking to reduce data transfer in the
        // future, we could elide them for subsequent messages.
        utils.extend(payload, payloadFields);
        resultsObject[deviceKey] = yield olmDevice.encryptMessage(deviceKey, sessionId, JSON.stringify(payload));
    });
}
exports.encryptMessageForDevice = encryptMessageForDevice;
/**
 * Get the existing olm sessions for the given devices, and the devices that
 * don't have olm sessions.
 *
 * @param {module:crypto/OlmDevice} olmDevice
 *
 * @param {MatrixClient} baseApis
 *
 * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser
 *    map from userid to list of devices to ensure sessions for
 *
 * @return {Promise} resolves to an array.  The first element of the array is a
 *    a map of user IDs to arrays of deviceInfo, representing the devices that
 *    don't have established olm sessions.  The second element of the array is
 *    a map from userId to deviceId to {@link module:crypto~OlmSessionResult}
 */
function getExistingOlmSessions(olmDevice, baseApis, devicesByUser) {
    return __awaiter(this, void 0, void 0, function* () {
        const devicesWithoutSession = {};
        const sessions = {};
        const promises = [];
        for (const [userId, devices] of Object.entries(devicesByUser)) {
            for (const deviceInfo of devices) {
                const deviceId = deviceInfo.deviceId;
                const key = deviceInfo.getIdentityKey();
                promises.push((() => __awaiter(this, void 0, void 0, function* () {
                    const sessionId = yield olmDevice.getSessionIdForDevice(key, true);
                    if (sessionId === null) {
                        devicesWithoutSession[userId] = devicesWithoutSession[userId] || [];
                        devicesWithoutSession[userId].push(deviceInfo);
                    }
                    else {
                        sessions[userId] = sessions[userId] || {};
                        sessions[userId][deviceId] = {
                            device: deviceInfo,
                            sessionId: sessionId,
                        };
                    }
                }))());
            }
        }
        yield Promise.all(promises);
        return [devicesWithoutSession, sessions];
    });
}
exports.getExistingOlmSessions = getExistingOlmSessions;
/**
 * Try to make sure we have established olm sessions for the given devices.
 *
 * @param {module:crypto/OlmDevice} olmDevice
 *
 * @param {MatrixClient} baseApis
 *
 * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser
 *    map from userid to list of devices to ensure sessions for
 *
 * @param {boolean} [force=false] If true, establish a new session even if one
 *     already exists.
 *
 * @param {Number} [otkTimeout] The timeout in milliseconds when requesting
 *     one-time keys for establishing new olm sessions.
 *
 * @param {Array} [failedServers] An array to fill with remote servers that
 *     failed to respond to one-time-key requests.
 *
 * @param {Logger} [log] A possibly customised log
 *
 * @return {Promise} resolves once the sessions are complete, to
 *    an Object mapping from userId to deviceId to
 *    {@link module:crypto~OlmSessionResult}
 */
function ensureOlmSessionsForDevices(olmDevice, baseApis, devicesByUser, force = false, otkTimeout, failedServers, log = logger_1.logger) {
    return __awaiter(this, void 0, void 0, function* () {
        if (typeof force === "number") {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore - backwards compatibility
            log = failedServers;
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore - backwards compatibility
            failedServers = otkTimeout;
            otkTimeout = force;
            force = false;
        }
        const devicesWithoutSession = [
        // [userId, deviceId], ...
        ];
        const result = {};
        const resolveSession = {};
        // Mark all sessions this task intends to update as in progress. It is
        // important to do this for all devices this task cares about in a single
        // synchronous operation, as otherwise it is possible to have deadlocks
        // where multiple tasks wait indefinitely on another task to update some set
        // of common devices.
        for (const [, devices] of Object.entries(devicesByUser)) {
            for (const deviceInfo of devices) {
                const key = deviceInfo.getIdentityKey();
                if (key === olmDevice.deviceCurve25519Key) {
                    // We don't start sessions with ourself, so there's no need to
                    // mark it in progress.
                    continue;
                }
                if (!olmDevice._sessionsInProgress[key]) {
                    // pre-emptively mark the session as in-progress to avoid race
                    // conditions.  If we find that we already have a session, then
                    // we'll resolve
                    olmDevice._sessionsInProgress[key] = new Promise(resolve => {
                        resolveSession[key] = (v) => {
                            delete olmDevice._sessionsInProgress[key];
                            resolve(v);
                        };
                    });
                }
            }
        }
        for (const [userId, devices] of Object.entries(devicesByUser)) {
            result[userId] = {};
            for (const deviceInfo of devices) {
                const deviceId = deviceInfo.deviceId;
                const key = deviceInfo.getIdentityKey();
                if (key === olmDevice.deviceCurve25519Key) {
                    // We should never be trying to start a session with ourself.
                    // Apart from talking to yourself being the first sign of madness,
                    // olm sessions can't do this because they get confused when
                    // they get a message and see that the 'other side' has started a
                    // new chain when this side has an active sender chain.
                    // If you see this message being logged in the wild, we should find
                    // the thing that is trying to send Olm messages to itself and fix it.
                    log.info("Attempted to start session with ourself! Ignoring");
                    // We must fill in the section in the return value though, as callers
                    // expect it to be there.
                    result[userId][deviceId] = {
                        device: deviceInfo,
                        sessionId: null,
                    };
                    continue;
                }
                const forWhom = `for ${key} (${userId}:${deviceId})`;
                const sessionId = yield olmDevice.getSessionIdForDevice(key, resolveSession[key], log);
                if (sessionId !== null && resolveSession[key]) {
                    // we found a session, but we had marked the session as
                    // in-progress, so resolve it now, which will unmark it and
                    // unblock anything that was waiting
                    resolveSession[key]();
                }
                if (sessionId === null || force) {
                    if (force) {
                        log.info(`Forcing new Olm session ${forWhom}`);
                    }
                    else {
                        log.info(`Making new Olm session ${forWhom}`);
                    }
                    devicesWithoutSession.push([userId, deviceId]);
                }
                result[userId][deviceId] = {
                    device: deviceInfo,
                    sessionId: sessionId,
                };
            }
        }
        if (devicesWithoutSession.length === 0) {
            return result;
        }
        const oneTimeKeyAlgorithm = "signed_curve25519";
        let res;
        let taskDetail = `one-time keys for ${devicesWithoutSession.length} devices`;
        try {
            log.debug(`Claiming ${taskDetail}`);
            res = yield baseApis.claimOneTimeKeys(devicesWithoutSession, oneTimeKeyAlgorithm, otkTimeout);
            log.debug(`Claimed ${taskDetail}`);
        }
        catch (e) {
            for (const resolver of Object.values(resolveSession)) {
                resolver();
            }
            log.log(`Failed to claim ${taskDetail}`, e, devicesWithoutSession);
            throw e;
        }
        if (failedServers && "failures" in res) {
            failedServers.push(...Object.keys(res.failures));
        }
        const otkResult = res.one_time_keys || {};
        const promises = [];
        for (const [userId, devices] of Object.entries(devicesByUser)) {
            const userRes = otkResult[userId] || {};
            for (let j = 0; j < devices.length; j++) {
                const deviceInfo = devices[j];
                const deviceId = deviceInfo.deviceId;
                const key = deviceInfo.getIdentityKey();
                if (key === olmDevice.deviceCurve25519Key) {
                    // We've already logged about this above. Skip here too
                    // otherwise we'll log saying there are no one-time keys
                    // which will be confusing.
                    continue;
                }
                if (result[userId][deviceId].sessionId && !force) {
                    // we already have a result for this device
                    continue;
                }
                const deviceRes = userRes[deviceId] || {};
                let oneTimeKey = null;
                for (const keyId in deviceRes) {
                    if (keyId.indexOf(oneTimeKeyAlgorithm + ":") === 0) {
                        oneTimeKey = deviceRes[keyId];
                    }
                }
                if (!oneTimeKey) {
                    log.warn(`No one-time keys (alg=${oneTimeKeyAlgorithm}) ` +
                        `for device ${userId}:${deviceId}`);
                    if (resolveSession[key]) {
                        resolveSession[key]();
                    }
                    continue;
                }
                promises.push(_verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo).then((sid) => {
                    if (resolveSession[key]) {
                        resolveSession[key](sid);
                    }
                    result[userId][deviceId].sessionId = sid;
                }, (e) => {
                    if (resolveSession[key]) {
                        resolveSession[key]();
                    }
                    throw e;
                }));
            }
        }
        taskDetail = `Olm sessions for ${promises.length} devices`;
        log.debug(`Starting ${taskDetail}`);
        yield Promise.all(promises);
        log.debug(`Started ${taskDetail}`);
        return result;
    });
}
exports.ensureOlmSessionsForDevices = ensureOlmSessionsForDevices;
function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        const deviceId = deviceInfo.deviceId;
        try {
            yield verifySignature(olmDevice, oneTimeKey, userId, deviceId, deviceInfo.getFingerprint());
        }
        catch (e) {
            logger_1.logger.error("Unable to verify signature on one-time key for device " +
                userId + ":" + deviceId + ":", e);
            return null;
        }
        let sid;
        try {
            sid = yield olmDevice.createOutboundSession(deviceInfo.getIdentityKey(), oneTimeKey.key);
        }
        catch (e) {
            // possibly a bad key
            logger_1.logger.error("Error starting olm session with device " +
                userId + ":" + deviceId + ": " + e);
            return null;
        }
        logger_1.logger.log("Started new olm sessionid " + sid +
            " for device " + userId + ":" + deviceId);
        return sid;
    });
}
/**
 * Verify the signature on an object
 *
 * @param {module:crypto/OlmDevice} olmDevice olm wrapper to use for verify op
 *
 * @param {Object} obj object to check signature on.
 *
 * @param {string} signingUserId  ID of the user whose signature should be checked
 *
 * @param {string} signingDeviceId  ID of the device whose signature should be checked
 *
 * @param {string} signingKey   base64-ed ed25519 public key
 *
 * Returns a promise which resolves (to undefined) if the the signature is good,
 * or rejects with an Error if it is bad.
 */
function verifySignature(olmDevice, obj, signingUserId, signingDeviceId, signingKey) {
    return __awaiter(this, void 0, void 0, function* () {
        const signKeyId = "ed25519:" + signingDeviceId;
        const signatures = obj.signatures || {};
        const userSigs = signatures[signingUserId] || {};
        const signature = userSigs[signKeyId];
        if (!signature) {
            throw Error("No signature");
        }
        // prepare the canonical json: remove unsigned and signatures, and stringify with anotherjson
        const mangledObj = Object.assign({}, obj);
        if ("unsigned" in mangledObj) {
            delete mangledObj.unsigned;
        }
        delete mangledObj.signatures;
        const json = another_json_1.default.stringify(mangledObj);
        olmDevice.verifySignature(signingKey, json, signature);
    });
}
exports.verifySignature = verifySignature;
/**
 * Sign a JSON object using public key cryptography
 * @param {Object} obj Object to sign.  The object will be modified to include
 *     the new signature
 * @param {Olm.PkSigning|Uint8Array} key the signing object or the private key
 * seed
 * @param {string} userId The user ID who owns the signing key
 * @param {string} pubKey The public key (ignored if key is a seed)
 * @returns {string} the signature for the object
 */
function pkSign(obj, key, userId, pubKey) {
    let createdKey = false;
    if (key instanceof Uint8Array) {
        const keyObj = new global.Olm.PkSigning();
        pubKey = keyObj.init_with_seed(key);
        key = keyObj;
        createdKey = true;
    }
    const sigs = obj.signatures || {};
    delete obj.signatures;
    const unsigned = obj.unsigned;
    if (obj.unsigned)
        delete obj.unsigned;
    try {
        const mysigs = sigs[userId] || {};
        sigs[userId] = mysigs;
        return mysigs['ed25519:' + pubKey] = key.sign(another_json_1.default.stringify(obj));
    }
    finally {
        obj.signatures = sigs;
        if (unsigned)
            obj.unsigned = unsigned;
        if (createdKey) {
            key.free();
        }
    }
}
exports.pkSign = pkSign;
/**
 * Verify a signed JSON object
 * @param {Object} obj Object to verify
 * @param {string} pubKey The public key to use to verify
 * @param {string} userId The user ID who signed the object
 */
function pkVerify(obj, pubKey, userId) {
    const keyId = "ed25519:" + pubKey;
    if (!(obj.signatures && obj.signatures[userId] && obj.signatures[userId][keyId])) {
        throw new Error("No signature");
    }
    const signature = obj.signatures[userId][keyId];
    const util = new global.Olm.Utility();
    const sigs = obj.signatures;
    delete obj.signatures;
    const unsigned = obj.unsigned;
    if (obj.unsigned)
        delete obj.unsigned;
    try {
        util.ed25519_verify(pubKey, another_json_1.default.stringify(obj), signature);
    }
    finally {
        obj.signatures = sigs;
        if (unsigned)
            obj.unsigned = unsigned;
        util.free();
    }
}
exports.pkVerify = pkVerify;
/**
 * Encode a typed array of uint8 as base64.
 * @param {Uint8Array} uint8Array The data to encode.
 * @return {string} The base64.
 */
function encodeBase64(uint8Array) {
    return Buffer.from(uint8Array).toString("base64");
}
exports.encodeBase64 = encodeBase64;
/**
 * Encode a typed array of uint8 as unpadded base64.
 * @param {Uint8Array} uint8Array The data to encode.
 * @return {string} The unpadded base64.
 */
function encodeUnpaddedBase64(uint8Array) {
    return encodeBase64(uint8Array).replace(/=+$/g, '');
}
exports.encodeUnpaddedBase64 = encodeUnpaddedBase64;
/**
 * Decode a base64 string to a typed array of uint8.
 * @param {string} base64 The base64 to decode.
 * @return {Uint8Array} The decoded data.
 */
function decodeBase64(base64) {
    return Buffer.from(base64, "base64");
}
exports.decodeBase64 = decodeBase64;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"../logger":106,"../utils":137,"another-json":28,"buffer":34}],86:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";
/*
Copyright 2018 New Vector Ltd

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeRecoveryKey = exports.encodeRecoveryKey = void 0;
const bs58_1 = __importDefault(require("bs58"));
// picked arbitrarily but to try & avoid clashing with any bitcoin ones
// (which are also base58 encoded, but bitcoin's involve a lot more hashing)
const OLM_RECOVERY_KEY_PREFIX = [0x8B, 0x01];
function encodeRecoveryKey(key) {
    const buf = new Buffer(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1);
    buf.set(OLM_RECOVERY_KEY_PREFIX, 0);
    buf.set(key, OLM_RECOVERY_KEY_PREFIX.length);
    let parity = 0;
    for (let i = 0; i < buf.length - 1; ++i) {
        parity ^= buf[i];
    }
    buf[buf.length - 1] = parity;
    const base58key = bs58_1.default.encode(buf);
    return base58key.match(/.{1,4}/g).join(" ");
}
exports.encodeRecoveryKey = encodeRecoveryKey;
function decodeRecoveryKey(recoveryKey) {
    const result = bs58_1.default.decode(recoveryKey.replace(/ /g, ''));
    let parity = 0;
    for (const b of result) {
        parity ^= b;
    }
    if (parity !== 0) {
        throw new Error("Incorrect parity");
    }
    for (let i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) {
        if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) {
            throw new Error("Incorrect prefix");
        }
    }
    if (result.length !==
        OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH + 1) {
        throw new Error("Incorrect length");
    }
    return Uint8Array.from(result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH));
}
exports.decodeRecoveryKey = decodeRecoveryKey;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"bs58":33,"buffer":34}],87:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.upgradeDatabase = upgradeDatabase;
exports.Backend = exports.VERSION = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _logger = require("../../logger");

var utils = _interopRequireWildcard(require("../../utils"));

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var VERSION = 10;
exports.VERSION = VERSION;
var PROFILE_TRANSACTIONS = false;
/**
 * Implementation of a CryptoStore which is backed by an existing
 * IndexedDB connection. Generally you want IndexedDBCryptoStore
 * which connects to the database and defers to one of these.
 *
 * @implements {module:crypto/store/base~CryptoStore}
 */

var Backend = /*#__PURE__*/function () {
  /**
   * @param {IDBDatabase} db
   */
  function Backend(db) {
    var _this = this;

    (0, _classCallCheck2["default"])(this, Backend);
    this._db = db;
    this._nextTxnId = 0; // make sure we close the db on `onversionchange` - otherwise
    // attempts to delete the database will block (and subsequent
    // attempts to re-create it will also block).

    db.onversionchange = function (ev) {
      _logger.logger.log("versionchange for indexeddb ".concat(_this._dbName, ": closing"));

      db.close();
    };
  }
  /**
   * Look for an existing outgoing room key request, and if none is found,
   * add a new one
   *
   * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
   *
   * @returns {Promise} resolves to
   *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
   *    same instance as passed in, or the existing one.
   */


  (0, _createClass2["default"])(Backend, [{
    key: "getOrAddOutgoingRoomKeyRequest",
    value: function getOrAddOutgoingRoomKeyRequest(request) {
      var _this2 = this;

      var requestBody = request.requestBody;
      return new Promise(function (resolve, reject) {
        var txn = _this2._db.transaction("outgoingRoomKeyRequests", "readwrite");

        txn.onerror = reject; // first see if we already have an entry for this request.

        _this2._getOutgoingRoomKeyRequest(txn, requestBody, function (existing) {
          if (existing) {
            // this entry matches the request - return it.
            _logger.logger.log("already have key request outstanding for " + "".concat(requestBody.room_id, " / ").concat(requestBody.session_id, ": ") + "not sending another");

            resolve(existing);
            return;
          } // we got to the end of the list without finding a match
          // - add the new request.


          _logger.logger.log("enqueueing key request for ".concat(requestBody.room_id, " / ") + requestBody.session_id);

          txn.oncomplete = function () {
            resolve(request);
          };

          var store = txn.objectStore("outgoingRoomKeyRequests");
          store.add(request);
        });
      });
    }
    /**
     * Look for an existing room key request
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    existing request to look for
     *
     * @return {Promise} resolves to the matching
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    not found
     */

  }, {
    key: "getOutgoingRoomKeyRequest",
    value: function getOutgoingRoomKeyRequest(requestBody) {
      var _this3 = this;

      return new Promise(function (resolve, reject) {
        var txn = _this3._db.transaction("outgoingRoomKeyRequests", "readonly");

        txn.onerror = reject;

        _this3._getOutgoingRoomKeyRequest(txn, requestBody, function (existing) {
          resolve(existing);
        });
      });
    }
    /**
     * look for an existing room key request in the db
     *
     * @private
     * @param {IDBTransaction} txn  database transaction
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    existing request to look for
     * @param {Function} callback  function to call with the results of the
     *    search. Either passed a matching
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    not found.
     */

  }, {
    key: "_getOutgoingRoomKeyRequest",
    value: function _getOutgoingRoomKeyRequest(txn, requestBody, callback) {
      var store = txn.objectStore("outgoingRoomKeyRequests");
      var idx = store.index("session");
      var cursorReq = idx.openCursor([requestBody.room_id, requestBody.session_id]);

      cursorReq.onsuccess = function (ev) {
        var cursor = ev.target.result;

        if (!cursor) {
          // no match found
          callback(null);
          return;
        }

        var existing = cursor.value;

        if (utils.deepCompare(existing.requestBody, requestBody)) {
          // got a match
          callback(existing);
          return;
        } // look at the next entry in the index


        cursor["continue"]();
      };
    }
    /**
     * Look for room key requests by state
     *
     * @param {Array<Number>} wantedStates list of acceptable states
     *
     * @return {Promise} resolves to the a
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    there are no pending requests in those states. If there are multiple
     *    requests in those states, an arbitrary one is chosen.
     */

  }, {
    key: "getOutgoingRoomKeyRequestByState",
    value: function getOutgoingRoomKeyRequestByState(wantedStates) {
      if (wantedStates.length === 0) {
        return Promise.resolve(null);
      } // this is a bit tortuous because we need to make sure we do the lookup
      // in a single transaction, to avoid having a race with the insertion
      // code.
      // index into the wantedStates array


      var stateIndex = 0;
      var result;

      function onsuccess(ev) {
        var cursor = ev.target.result;

        if (cursor) {
          // got a match
          result = cursor.value;
          return;
        } // try the next state in the list


        stateIndex++;

        if (stateIndex >= wantedStates.length) {
          // no matches
          return;
        }

        var wantedState = wantedStates[stateIndex];
        var cursorReq = ev.target.source.openCursor(wantedState);
        cursorReq.onsuccess = onsuccess;
      }

      var txn = this._db.transaction("outgoingRoomKeyRequests", "readonly");

      var store = txn.objectStore("outgoingRoomKeyRequests");
      var wantedState = wantedStates[stateIndex];
      var cursorReq = store.index("state").openCursor(wantedState);
      cursorReq.onsuccess = onsuccess;
      return promiseifyTxn(txn).then(function () {
        return result;
      });
    }
    /**
     *
     * @param {Number} wantedState
     * @return {Promise<Array<*>>} All elements in a given state
     */

  }, {
    key: "getAllOutgoingRoomKeyRequestsByState",
    value: function getAllOutgoingRoomKeyRequestsByState(wantedState) {
      var _this4 = this;

      return new Promise(function (resolve, reject) {
        var txn = _this4._db.transaction("outgoingRoomKeyRequests", "readonly");

        var store = txn.objectStore("outgoingRoomKeyRequests");
        var index = store.index("state");
        var request = index.getAll(wantedState);

        request.onsuccess = function (ev) {
          return resolve(ev.target.result);
        };

        request.onerror = function (ev) {
          return reject(ev.target.error);
        };
      });
    }
  }, {
    key: "getOutgoingRoomKeyRequestsByTarget",
    value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {
      var stateIndex = 0;
      var results = [];

      function onsuccess(ev) {
        var cursor = ev.target.result;

        if (cursor) {
          var keyReq = cursor.value;

          if (keyReq.recipients.includes({
            userId: userId,
            deviceId: deviceId
          })) {
            results.push(keyReq);
          }

          cursor["continue"]();
        } else {
          // try the next state in the list
          stateIndex++;

          if (stateIndex >= wantedStates.length) {
            // no matches
            return;
          }

          var _wantedState = wantedStates[stateIndex];

          var _cursorReq = ev.target.source.openCursor(_wantedState);

          _cursorReq.onsuccess = onsuccess;
        }
      }

      var txn = this._db.transaction("outgoingRoomKeyRequests", "readonly");

      var store = txn.objectStore("outgoingRoomKeyRequests");
      var wantedState = wantedStates[stateIndex];
      var cursorReq = store.index("state").openCursor(wantedState);
      cursorReq.onsuccess = onsuccess;
      return promiseifyTxn(txn).then(function () {
        return results;
      });
    }
    /**
     * Look for an existing room key request by id and state, and update it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     * @param {Object} updates        name/value map of updates to apply
     *
     * @returns {Promise} resolves to
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
     *    updated request, or null if no matching row was found
     */

  }, {
    key: "updateOutgoingRoomKeyRequest",
    value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {
      var result = null;

      function onsuccess(ev) {
        var cursor = ev.target.result;

        if (!cursor) {
          return;
        }

        var data = cursor.value;

        if (data.state != expectedState) {
          _logger.logger.warn("Cannot update room key request from ".concat(expectedState, " ") + "as it was already updated to ".concat(data.state));

          return;
        }

        Object.assign(data, updates);
        cursor.update(data);
        result = data;
      }

      var txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite");

      var cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId);
      cursorReq.onsuccess = onsuccess;
      return promiseifyTxn(txn).then(function () {
        return result;
      });
    }
    /**
     * Look for an existing room key request by id and state, and delete it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     *
     * @returns {Promise} resolves once the operation is completed
     */

  }, {
    key: "deleteOutgoingRoomKeyRequest",
    value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) {
      var txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite");

      var cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId);

      cursorReq.onsuccess = function (ev) {
        var cursor = ev.target.result;

        if (!cursor) {
          return;
        }

        var data = cursor.value;

        if (data.state != expectedState) {
          _logger.logger.warn("Cannot delete room key request in state ".concat(data.state, " ") + "(expected ".concat(expectedState, ")"));

          return;
        }

        cursor["delete"]();
      };

      return promiseifyTxn(txn);
    } // Olm Account

  }, {
    key: "getAccount",
    value: function getAccount(txn, func) {
      var objectStore = txn.objectStore("account");
      var getReq = objectStore.get("-");

      getReq.onsuccess = function () {
        try {
          func(getReq.result || null);
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "storeAccount",
    value: function storeAccount(txn, newData) {
      var objectStore = txn.objectStore("account");
      objectStore.put(newData, "-");
    }
  }, {
    key: "getCrossSigningKeys",
    value: function getCrossSigningKeys(txn, func) {
      var objectStore = txn.objectStore("account");
      var getReq = objectStore.get("crossSigningKeys");

      getReq.onsuccess = function () {
        try {
          func(getReq.result || null);
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "getSecretStorePrivateKey",
    value: function getSecretStorePrivateKey(txn, func, type) {
      var objectStore = txn.objectStore("account");
      var getReq = objectStore.get("ssss_cache:".concat(type));

      getReq.onsuccess = function () {
        try {
          func(getReq.result || null);
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "storeCrossSigningKeys",
    value: function storeCrossSigningKeys(txn, keys) {
      var objectStore = txn.objectStore("account");
      objectStore.put(keys, "crossSigningKeys");
    }
  }, {
    key: "storeSecretStorePrivateKey",
    value: function storeSecretStorePrivateKey(txn, type, key) {
      var objectStore = txn.objectStore("account");
      objectStore.put(key, "ssss_cache:".concat(type));
    } // Olm Sessions

  }, {
    key: "countEndToEndSessions",
    value: function countEndToEndSessions(txn, func) {
      var objectStore = txn.objectStore("sessions");
      var countReq = objectStore.count();

      countReq.onsuccess = function () {
        try {
          func(countReq.result);
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "getEndToEndSessions",
    value: function getEndToEndSessions(deviceKey, txn, func) {
      var objectStore = txn.objectStore("sessions");
      var idx = objectStore.index("deviceKey");
      var getReq = idx.openCursor(deviceKey);
      var results = {};

      getReq.onsuccess = function () {
        var cursor = getReq.result;

        if (cursor) {
          results[cursor.value.sessionId] = {
            session: cursor.value.session,
            lastReceivedMessageTs: cursor.value.lastReceivedMessageTs
          };
          cursor["continue"]();
        } else {
          try {
            func(results);
          } catch (e) {
            abortWithException(txn, e);
          }
        }
      };
    }
  }, {
    key: "getEndToEndSession",
    value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
      var objectStore = txn.objectStore("sessions");
      var getReq = objectStore.get([deviceKey, sessionId]);

      getReq.onsuccess = function () {
        try {
          if (getReq.result) {
            func({
              session: getReq.result.session,
              lastReceivedMessageTs: getReq.result.lastReceivedMessageTs
            });
          } else {
            func(null);
          }
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "getAllEndToEndSessions",
    value: function getAllEndToEndSessions(txn, func) {
      var objectStore = txn.objectStore("sessions");
      var getReq = objectStore.openCursor();

      getReq.onsuccess = function () {
        try {
          var cursor = getReq.result;

          if (cursor) {
            func(cursor.value);
            cursor["continue"]();
          } else {
            func(null);
          }
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "storeEndToEndSession",
    value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
      var objectStore = txn.objectStore("sessions");
      objectStore.put({
        deviceKey: deviceKey,
        sessionId: sessionId,
        session: sessionInfo.session,
        lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs
      });
    }
  }, {
    key: "storeEndToEndSessionProblem",
    value: function () {
      var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(deviceKey, type, fixed) {
        var txn, objectStore;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                txn = this._db.transaction("session_problems", "readwrite");
                objectStore = txn.objectStore("session_problems");
                objectStore.put({
                  deviceKey: deviceKey,
                  type: type,
                  fixed: fixed,
                  time: Date.now()
                });
                return _context.abrupt("return", promiseifyTxn(txn));

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function storeEndToEndSessionProblem(_x, _x2, _x3) {
        return _storeEndToEndSessionProblem.apply(this, arguments);
      }

      return storeEndToEndSessionProblem;
    }()
  }, {
    key: "getEndToEndSessionProblem",
    value: function () {
      var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, timestamp) {
        var result, txn, objectStore, index, req;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                txn = this._db.transaction("session_problems", "readwrite");
                objectStore = txn.objectStore("session_problems");
                index = objectStore.index("deviceKey");
                req = index.getAll(deviceKey);

                req.onsuccess = function (event) {
                  var problems = req.result;

                  if (!problems.length) {
                    result = null;
                    return;
                  }

                  problems.sort(function (a, b) {
                    return a.time - b.time;
                  });
                  var lastProblem = problems[problems.length - 1];

                  var _iterator = _createForOfIteratorHelper(problems),
                      _step;

                  try {
                    for (_iterator.s(); !(_step = _iterator.n()).done;) {
                      var problem = _step.value;

                      if (problem.time > timestamp) {
                        result = Object.assign({}, problem, {
                          fixed: lastProblem.fixed
                        });
                        return;
                      }
                    }
                  } catch (err) {
                    _iterator.e(err);
                  } finally {
                    _iterator.f();
                  }

                  if (lastProblem.fixed) {
                    result = null;
                  } else {
                    result = lastProblem;
                  }
                };

                _context2.next = 7;
                return promiseifyTxn(txn);

              case 7:
                return _context2.abrupt("return", result);

              case 8:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function getEndToEndSessionProblem(_x4, _x5) {
        return _getEndToEndSessionProblem.apply(this, arguments);
      }

      return getEndToEndSessionProblem;
    }() // FIXME: we should probably prune this when devices get deleted

  }, {
    key: "filterOutNotifiedErrorDevices",
    value: function () {
      var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(devices) {
        var txn, objectStore, ret;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                txn = this._db.transaction("notified_error_devices", "readwrite");
                objectStore = txn.objectStore("notified_error_devices");
                ret = [];
                _context3.next = 5;
                return Promise.all(devices.map(function (device) {
                  return new Promise(function (resolve) {
                    var userId = device.userId,
                        deviceInfo = device.deviceInfo;
                    var getReq = objectStore.get([userId, deviceInfo.deviceId]);

                    getReq.onsuccess = function () {
                      if (!getReq.result) {
                        objectStore.put({
                          userId: userId,
                          deviceId: deviceInfo.deviceId
                        });
                        ret.push(device);
                      }

                      resolve();
                    };
                  });
                }));

              case 5:
                return _context3.abrupt("return", ret);

              case 6:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function filterOutNotifiedErrorDevices(_x6) {
        return _filterOutNotifiedErrorDevices.apply(this, arguments);
      }

      return filterOutNotifiedErrorDevices;
    }() // Inbound group sessions

  }, {
    key: "getEndToEndInboundGroupSession",
    value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
      var session = false;
      var withheld = false;
      var objectStore = txn.objectStore("inbound_group_sessions");
      var getReq = objectStore.get([senderCurve25519Key, sessionId]);

      getReq.onsuccess = function () {
        try {
          if (getReq.result) {
            session = getReq.result.session;
          } else {
            session = null;
          }

          if (withheld !== false) {
            func(session, withheld);
          }
        } catch (e) {
          abortWithException(txn, e);
        }
      };

      var withheldObjectStore = txn.objectStore("inbound_group_sessions_withheld");
      var withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);

      withheldGetReq.onsuccess = function () {
        try {
          if (withheldGetReq.result) {
            withheld = withheldGetReq.result.session;
          } else {
            withheld = null;
          }

          if (session !== false) {
            func(session, withheld);
          }
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "getAllEndToEndInboundGroupSessions",
    value: function getAllEndToEndInboundGroupSessions(txn, func) {
      var objectStore = txn.objectStore("inbound_group_sessions");
      var getReq = objectStore.openCursor();

      getReq.onsuccess = function () {
        var cursor = getReq.result;

        if (cursor) {
          try {
            func({
              senderKey: cursor.value.senderCurve25519Key,
              sessionId: cursor.value.sessionId,
              sessionData: cursor.value.session
            });
          } catch (e) {
            abortWithException(txn, e);
          }

          cursor["continue"]();
        } else {
          try {
            func(null);
          } catch (e) {
            abortWithException(txn, e);
          }
        }
      };
    }
  }, {
    key: "addEndToEndInboundGroupSession",
    value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      var objectStore = txn.objectStore("inbound_group_sessions");
      var addReq = objectStore.add({
        senderCurve25519Key: senderCurve25519Key,
        sessionId: sessionId,
        session: sessionData
      });

      addReq.onerror = function (ev) {
        if (addReq.error.name === 'ConstraintError') {
          // This stops the error from triggering the txn's onerror
          ev.stopPropagation(); // ...and this stops it from aborting the transaction

          ev.preventDefault();

          _logger.logger.log("Ignoring duplicate inbound group session: " + senderCurve25519Key + " / " + sessionId);
        } else {
          abortWithException(txn, new Error("Failed to add inbound group session: " + addReq.error));
        }
      };
    }
  }, {
    key: "storeEndToEndInboundGroupSession",
    value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      var objectStore = txn.objectStore("inbound_group_sessions");
      objectStore.put({
        senderCurve25519Key: senderCurve25519Key,
        sessionId: sessionId,
        session: sessionData
      });
    }
  }, {
    key: "storeEndToEndInboundGroupSessionWithheld",
    value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) {
      var objectStore = txn.objectStore("inbound_group_sessions_withheld");
      objectStore.put({
        senderCurve25519Key: senderCurve25519Key,
        sessionId: sessionId,
        session: sessionData
      });
    }
  }, {
    key: "getEndToEndDeviceData",
    value: function getEndToEndDeviceData(txn, func) {
      var objectStore = txn.objectStore("device_data");
      var getReq = objectStore.get("-");

      getReq.onsuccess = function () {
        try {
          func(getReq.result || null);
        } catch (e) {
          abortWithException(txn, e);
        }
      };
    }
  }, {
    key: "storeEndToEndDeviceData",
    value: function storeEndToEndDeviceData(deviceData, txn) {
      var objectStore = txn.objectStore("device_data");
      objectStore.put(deviceData, "-");
    }
  }, {
    key: "storeEndToEndRoom",
    value: function storeEndToEndRoom(roomId, roomInfo, txn) {
      var objectStore = txn.objectStore("rooms");
      objectStore.put(roomInfo, roomId);
    }
  }, {
    key: "getEndToEndRooms",
    value: function getEndToEndRooms(txn, func) {
      var rooms = {};
      var objectStore = txn.objectStore("rooms");
      var getReq = objectStore.openCursor();

      getReq.onsuccess = function () {
        var cursor = getReq.result;

        if (cursor) {
          rooms[cursor.key] = cursor.value;
          cursor["continue"]();
        } else {
          try {
            func(rooms);
          } catch (e) {
            abortWithException(txn, e);
          }
        }
      };
    } // session backups

  }, {
    key: "getSessionsNeedingBackup",
    value: function getSessionsNeedingBackup(limit) {
      var _this5 = this;

      return new Promise(function (resolve, reject) {
        var sessions = [];

        var txn = _this5._db.transaction(["sessions_needing_backup", "inbound_group_sessions"], "readonly");

        txn.onerror = reject;

        txn.oncomplete = function () {
          resolve(sessions);
        };

        var objectStore = txn.objectStore("sessions_needing_backup");
        var sessionStore = txn.objectStore("inbound_group_sessions");
        var getReq = objectStore.openCursor();

        getReq.onsuccess = function () {
          var cursor = getReq.result;

          if (cursor) {
            var sessionGetReq = sessionStore.get(cursor.key);

            sessionGetReq.onsuccess = function () {
              sessions.push({
                senderKey: sessionGetReq.result.senderCurve25519Key,
                sessionId: sessionGetReq.result.sessionId,
                sessionData: sessionGetReq.result.session
              });
            };

            if (!limit || sessions.length < limit) {
              cursor["continue"]();
            }
          }
        };
      });
    }
  }, {
    key: "countSessionsNeedingBackup",
    value: function countSessionsNeedingBackup(txn) {
      if (!txn) {
        txn = this._db.transaction("sessions_needing_backup", "readonly");
      }

      var objectStore = txn.objectStore("sessions_needing_backup");
      return new Promise(function (resolve, reject) {
        var req = objectStore.count();
        req.onerror = reject;

        req.onsuccess = function () {
          return resolve(req.result);
        };
      });
    }
  }, {
    key: "unmarkSessionsNeedingBackup",
    value: function unmarkSessionsNeedingBackup(sessions, txn) {
      if (!txn) {
        txn = this._db.transaction("sessions_needing_backup", "readwrite");
      }

      var objectStore = txn.objectStore("sessions_needing_backup");
      return Promise.all(sessions.map(function (session) {
        return new Promise(function (resolve, reject) {
          var req = objectStore["delete"]([session.senderKey, session.sessionId]);
          req.onsuccess = resolve;
          req.onerror = reject;
        });
      }));
    }
  }, {
    key: "markSessionsNeedingBackup",
    value: function markSessionsNeedingBackup(sessions, txn) {
      if (!txn) {
        txn = this._db.transaction("sessions_needing_backup", "readwrite");
      }

      var objectStore = txn.objectStore("sessions_needing_backup");
      return Promise.all(sessions.map(function (session) {
        return new Promise(function (resolve, reject) {
          var req = objectStore.put({
            senderCurve25519Key: session.senderKey,
            sessionId: session.sessionId
          });
          req.onsuccess = resolve;
          req.onerror = reject;
        });
      }));
    }
  }, {
    key: "addSharedHistoryInboundGroupSession",
    value: function addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {
      if (!txn) {
        txn = this._db.transaction("shared_history_inbound_group_sessions", "readwrite");
      }

      var objectStore = txn.objectStore("shared_history_inbound_group_sessions");
      var req = objectStore.get([roomId]);

      req.onsuccess = function () {
        var _ref = req.result || {
          sessions: []
        },
            sessions = _ref.sessions;

        sessions.push([senderKey, sessionId]);
        objectStore.put({
          roomId: roomId,
          sessions: sessions
        });
      };
    }
  }, {
    key: "getSharedHistoryInboundGroupSessions",
    value: function getSharedHistoryInboundGroupSessions(roomId, txn) {
      if (!txn) {
        txn = this._db.transaction("shared_history_inbound_group_sessions", "readonly");
      }

      var objectStore = txn.objectStore("shared_history_inbound_group_sessions");
      var req = objectStore.get([roomId]);
      return new Promise(function (resolve, reject) {
        req.onsuccess = function () {
          var _ref2 = req.result || {
            sessions: []
          },
              sessions = _ref2.sessions;

          resolve(sessions);
        };

        req.onerror = reject;
      });
    }
  }, {
    key: "doTxn",
    value: function doTxn(mode, stores, func) {
      var log = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _logger.logger;
      var startTime;
      var description;

      if (PROFILE_TRANSACTIONS) {
        var txnId = this._nextTxnId++;
        startTime = Date.now();
        description = "".concat(mode, " crypto store transaction ").concat(txnId, " in ").concat(stores);
        log.debug("Starting ".concat(description));
      }

      var txn = this._db.transaction(stores, mode);

      var promise = promiseifyTxn(txn);
      var result = func(txn);

      if (PROFILE_TRANSACTIONS) {
        promise.then(function () {
          var elapsedTime = Date.now() - startTime;
          log.debug("Finished ".concat(description, ", took ").concat(elapsedTime, " ms"));
        }, function () {
          var elapsedTime = Date.now() - startTime;
          log.error("Failed ".concat(description, ", took ").concat(elapsedTime, " ms"));
        });
      }

      return promise.then(function () {
        return result;
      });
    }
  }]);
  return Backend;
}();

exports.Backend = Backend;

function upgradeDatabase(db, oldVersion) {
  _logger.logger.log("Upgrading IndexedDBCryptoStore from version ".concat(oldVersion) + " to ".concat(VERSION));

  if (oldVersion < 1) {
    // The database did not previously exist.
    createDatabase(db);
  }

  if (oldVersion < 2) {
    db.createObjectStore("account");
  }

  if (oldVersion < 3) {
    var sessionsStore = db.createObjectStore("sessions", {
      keyPath: ["deviceKey", "sessionId"]
    });
    sessionsStore.createIndex("deviceKey", "deviceKey");
  }

  if (oldVersion < 4) {
    db.createObjectStore("inbound_group_sessions", {
      keyPath: ["senderCurve25519Key", "sessionId"]
    });
  }

  if (oldVersion < 5) {
    db.createObjectStore("device_data");
  }

  if (oldVersion < 6) {
    db.createObjectStore("rooms");
  }

  if (oldVersion < 7) {
    db.createObjectStore("sessions_needing_backup", {
      keyPath: ["senderCurve25519Key", "sessionId"]
    });
  }

  if (oldVersion < 8) {
    db.createObjectStore("inbound_group_sessions_withheld", {
      keyPath: ["senderCurve25519Key", "sessionId"]
    });
  }

  if (oldVersion < 9) {
    var problemsStore = db.createObjectStore("session_problems", {
      keyPath: ["deviceKey", "time"]
    });
    problemsStore.createIndex("deviceKey", "deviceKey");
    db.createObjectStore("notified_error_devices", {
      keyPath: ["userId", "deviceId"]
    });
  }

  if (oldVersion < 10) {
    db.createObjectStore("shared_history_inbound_group_sessions", {
      keyPath: ["roomId"]
    });
  } // Expand as needed.

}

function createDatabase(db) {
  var outgoingRoomKeyRequestsStore = db.createObjectStore("outgoingRoomKeyRequests", {
    keyPath: "requestId"
  }); // we assume that the RoomKeyRequestBody will have room_id and session_id
  // properties, to make the index efficient.

  outgoingRoomKeyRequestsStore.createIndex("session", ["requestBody.room_id", "requestBody.session_id"]);
  outgoingRoomKeyRequestsStore.createIndex("state", "state");
}
/*
 * Aborts a transaction with a given exception
 * The transaction promise will be rejected with this exception.
 */


function abortWithException(txn, e) {
  // We cheekily stick our exception onto the transaction object here
  // We could alternatively make the thing we pass back to the app
  // an object containing the transaction and exception.
  txn._mx_abortexception = e;

  try {
    txn.abort();
  } catch (e) {// sometimes we won't be able to abort the transaction
    // (ie. if it's aborted or completed)
  }
}

function promiseifyTxn(txn) {
  return new Promise(function (resolve, reject) {
    txn.oncomplete = function () {
      if (txn._mx_abortexception !== undefined) {
        reject(txn._mx_abortexception);
      }

      resolve();
    };

    txn.onerror = function (event) {
      if (txn._mx_abortexception !== undefined) {
        reject(txn._mx_abortexception);
      } else {
        _logger.logger.log("Error performing indexeddb txn", event);

        reject(event.target.error);
      }
    };

    txn.onabort = function (event) {
      if (txn._mx_abortexception !== undefined) {
        reject(txn._mx_abortexception);
      } else {
        _logger.logger.log("Error performing indexeddb txn", event);

        reject(event.target.error);
      }
    };
  });
}

},{"../../logger":106,"../../utils":137,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],88:[function(require,module,exports){
(function (global){(function (){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IndexedDBCryptoStore = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _logger = require("../../logger");

var _localStorageCryptoStore = require("./localStorage-crypto-store");

var _memoryCryptoStore = require("./memory-crypto-store");

var IndexedDBCryptoStoreBackend = _interopRequireWildcard(require("./indexeddb-crypto-store-backend"));

var _errors = require("../../errors");

var IndexedDBHelpers = _interopRequireWildcard(require("../../indexeddb-helpers"));

/*
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.

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

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

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

/**
 * Internal module. indexeddb storage for e2e.
 *
 * @module
 */

/**
 * An implementation of CryptoStore, which is normally backed by an indexeddb,
 * but with fallback to MemoryCryptoStore.
 *
 * @implements {module:crypto/store/base~CryptoStore}
 */
var IndexedDBCryptoStore = /*#__PURE__*/function () {
  /**
   * Create a new IndexedDBCryptoStore
   *
   * @param {IDBFactory} indexedDB  global indexedDB instance
   * @param {string} dbName   name of db to connect to
   */
  function IndexedDBCryptoStore(indexedDB, dbName) {
    (0, _classCallCheck2["default"])(this, IndexedDBCryptoStore);
    this._indexedDB = indexedDB;
    this._dbName = dbName;
    this._backendPromise = null;
    this._backend = null;
  }

  (0, _createClass2["default"])(IndexedDBCryptoStore, [{
    key: "startup",

    /**
     * Ensure the database exists and is up-to-date, or fall back to
     * a local storage or in-memory store.
     *
     * This must be called before the store can be used.
     *
     * @return {Promise} resolves to either an IndexedDBCryptoStoreBackend.Backend,
     * or a MemoryCryptoStore
     */
    value: function startup() {
      var _this = this;

      if (this._backendPromise) {
        return this._backendPromise;
      }

      this._backendPromise = new Promise(function (resolve, reject) {
        if (!_this._indexedDB) {
          reject(new Error('no indexeddb support available'));
          return;
        }

        _logger.logger.log("connecting to indexeddb ".concat(_this._dbName));

        var req = _this._indexedDB.open(_this._dbName, IndexedDBCryptoStoreBackend.VERSION);

        req.onupgradeneeded = function (ev) {
          var db = ev.target.result;
          var oldVersion = ev.oldVersion;
          IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion);
        };

        req.onblocked = function () {
          _logger.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere");
        };

        req.onerror = function (ev) {
          _logger.logger.log("Error connecting to indexeddb", ev);

          reject(ev.target.error);
        };

        req.onsuccess = function (r) {
          var db = r.target.result;

          _logger.logger.log("connected to indexeddb ".concat(_this._dbName));

          resolve(new IndexedDBCryptoStoreBackend.Backend(db));
        };
      }).then(function (backend) {
        // Edge has IndexedDB but doesn't support compund keys which we use fairly extensively.
        // Try a dummy query which will fail if the browser doesn't support compund keys, so
        // we can fall back to a different backend.
        return backend.doTxn('readonly', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) {
          backend.getEndToEndInboundGroupSession('', '', txn, function () {});
        }).then(function () {
          return backend;
        });
      })["catch"](function (e) {
        if (e.name === 'VersionError') {
          _logger.logger.warn("Crypto DB is too new for us to use!", e); // don't fall back to a different store: the user has crypto data
          // in this db so we should use it or nothing at all.


          throw new _errors.InvalidCryptoStoreError(_errors.InvalidCryptoStoreError.TOO_NEW);
        }

        _logger.logger.warn("unable to connect to indexeddb ".concat(_this._dbName) + ": falling back to localStorage store: ".concat(e));

        try {
          return new _localStorageCryptoStore.LocalStorageCryptoStore(global.localStorage);
        } catch (e) {
          _logger.logger.warn("unable to open localStorage: falling back to in-memory store: ".concat(e));

          return new _memoryCryptoStore.MemoryCryptoStore();
        }
      }).then(function (backend) {
        _this._backend = backend;
      });
      return this._backendPromise;
    }
    /**
     * Delete all data from this store.
     *
     * @returns {Promise} resolves when the store has been cleared.
     */

  }, {
    key: "deleteAllData",
    value: function deleteAllData() {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        if (!_this2._indexedDB) {
          reject(new Error('no indexeddb support available'));
          return;
        }

        _logger.logger.log("Removing indexeddb instance: ".concat(_this2._dbName));

        var req = _this2._indexedDB.deleteDatabase(_this2._dbName);

        req.onblocked = function () {
          _logger.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere");
        };

        req.onerror = function (ev) {
          _logger.logger.log("Error deleting data from indexeddb", ev);

          reject(ev.target.error);
        };

        req.onsuccess = function () {
          _logger.logger.log("Removed indexeddb instance: ".concat(_this2._dbName));

          resolve();
        };
      })["catch"](function (e) {
        // in firefox, with indexedDB disabled, this fails with a
        // DOMError. We treat this as non-fatal, so that people can
        // still use the app.
        _logger.logger.warn("unable to delete IndexedDBCryptoStore: ".concat(e));
      });
    }
    /**
     * Look for an existing outgoing room key request, and if none is found,
     * add a new one
     *
     * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
     *
     * @returns {Promise} resolves to
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
     *    same instance as passed in, or the existing one.
     */

  }, {
    key: "getOrAddOutgoingRoomKeyRequest",
    value: function getOrAddOutgoingRoomKeyRequest(request) {
      return this._backend.getOrAddOutgoingRoomKeyRequest(request);
    }
    /**
     * Look for an existing room key request
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    existing request to look for
     *
     * @return {Promise} resolves to the matching
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    not found
     */

  }, {
    key: "getOutgoingRoomKeyRequest",
    value: function getOutgoingRoomKeyRequest(requestBody) {
      return this._backend.getOutgoingRoomKeyRequest(requestBody);
    }
    /**
     * Look for room key requests by state
     *
     * @param {Array<Number>} wantedStates list of acceptable states
     *
     * @return {Promise} resolves to the a
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    there are no pending requests in those states. If there are multiple
     *    requests in those states, an arbitrary one is chosen.
     */

  }, {
    key: "getOutgoingRoomKeyRequestByState",
    value: function getOutgoingRoomKeyRequestByState(wantedStates) {
      return this._backend.getOutgoingRoomKeyRequestByState(wantedStates);
    }
    /**
     * Look for room key requests by state –
     * unlike above, return a list of all entries in one state.
     *
     * @param {Number} wantedState
     * @return {Promise<Array<*>>} Returns an array of requests in the given state
     */

  }, {
    key: "getAllOutgoingRoomKeyRequestsByState",
    value: function getAllOutgoingRoomKeyRequestsByState(wantedState) {
      return this._backend.getAllOutgoingRoomKeyRequestsByState(wantedState);
    }
    /**
     * Look for room key requests by target device and state
     *
     * @param {string} userId Target user ID
     * @param {string} deviceId Target device ID
     * @param {Array<Number>} wantedStates list of acceptable states
     *
     * @return {Promise} resolves to a list of all the
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
     */

  }, {
    key: "getOutgoingRoomKeyRequestsByTarget",
    value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {
      return this._backend.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates);
    }
    /**
     * Look for an existing room key request by id and state, and update it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     * @param {Object} updates        name/value map of updates to apply
     *
     * @returns {Promise} resolves to
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
     *    updated request, or null if no matching row was found
     */

  }, {
    key: "updateOutgoingRoomKeyRequest",
    value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {
      return this._backend.updateOutgoingRoomKeyRequest(requestId, expectedState, updates);
    }
    /**
     * Look for an existing room key request by id and state, and delete it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     *
     * @returns {Promise} resolves once the operation is completed
     */

  }, {
    key: "deleteOutgoingRoomKeyRequest",
    value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) {
      return this._backend.deleteOutgoingRoomKeyRequest(requestId, expectedState);
    } // Olm Account

    /*
     * Get the account pickle from the store.
     * This requires an active transaction. See doTxn().
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(string)} func Called with the account pickle
     */

  }, {
    key: "getAccount",
    value: function getAccount(txn, func) {
      this._backend.getAccount(txn, func);
    }
    /**
     * Write the account pickle to the store.
     * This requires an active transaction. See doTxn().
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {string} newData The new account pickle to store.
     */

  }, {
    key: "storeAccount",
    value: function storeAccount(txn, newData) {
      this._backend.storeAccount(txn, newData);
    }
    /**
     * Get the public part of the cross-signing keys (eg. self-signing key,
     * user signing key).
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(string)} func Called with the account keys object:
     *        { key_type: base64 encoded seed } where key type = user_signing_key_seed or self_signing_key_seed
     */

  }, {
    key: "getCrossSigningKeys",
    value: function getCrossSigningKeys(txn, func) {
      this._backend.getCrossSigningKeys(txn, func);
    }
    /**
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(string)} func Called with the private key
     * @param {string} type A key type
     */

  }, {
    key: "getSecretStorePrivateKey",
    value: function getSecretStorePrivateKey(txn, func, type) {
      this._backend.getSecretStorePrivateKey(txn, func, type);
    }
    /**
     * Write the cross-signing keys back to the store
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {string} keys keys object as getCrossSigningKeys()
     */

  }, {
    key: "storeCrossSigningKeys",
    value: function storeCrossSigningKeys(txn, keys) {
      this._backend.storeCrossSigningKeys(txn, keys);
    }
    /**
     * Write the cross-signing private keys back to the store
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {string} type The type of cross-signing private key to store
     * @param {string} key keys object as getCrossSigningKeys()
     */

  }, {
    key: "storeSecretStorePrivateKey",
    value: function storeSecretStorePrivateKey(txn, type, key) {
      this._backend.storeSecretStorePrivateKey(txn, type, key);
    } // Olm sessions

    /**
     * Returns the number of end-to-end sessions in the store
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(int)} func Called with the count of sessions
     */

  }, {
    key: "countEndToEndSessions",
    value: function countEndToEndSessions(txn, func) {
      this._backend.countEndToEndSessions(txn, func);
    }
    /**
     * Retrieve a specific end-to-end session between the logged-in user
     * and another device.
     * @param {string} deviceKey The public key of the other device.
     * @param {string} sessionId The ID of the session to retrieve
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(object)} func Called with A map from sessionId
     *     to session information object with 'session' key being the
     *     Base64 end-to-end session and lastReceivedMessageTs being the
     *     timestamp in milliseconds at which the session last received
     *     a message.
     */

  }, {
    key: "getEndToEndSession",
    value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
      this._backend.getEndToEndSession(deviceKey, sessionId, txn, func);
    }
    /**
     * Retrieve the end-to-end sessions between the logged-in user and another
     * device.
     * @param {string} deviceKey The public key of the other device.
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(object)} func Called with A map from sessionId
     *     to session information object with 'session' key being the
     *     Base64 end-to-end session and lastReceivedMessageTs being the
     *     timestamp in milliseconds at which the session last received
     *     a message.
     */

  }, {
    key: "getEndToEndSessions",
    value: function getEndToEndSessions(deviceKey, txn, func) {
      this._backend.getEndToEndSessions(deviceKey, txn, func);
    }
    /**
     * Retrieve all end-to-end sessions
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(object)} func Called one for each session with
     *     an object with, deviceKey, lastReceivedMessageTs, sessionId
     *     and session keys.
     */

  }, {
    key: "getAllEndToEndSessions",
    value: function getAllEndToEndSessions(txn, func) {
      this._backend.getAllEndToEndSessions(txn, func);
    }
    /**
     * Store a session between the logged-in user and another device
     * @param {string} deviceKey The public key of the other device.
     * @param {string} sessionId The ID for this end-to-end session.
     * @param {string} sessionInfo Session information object
     * @param {*} txn An active transaction. See doTxn().
     */

  }, {
    key: "storeEndToEndSession",
    value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
      this._backend.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn);
    }
  }, {
    key: "storeEndToEndSessionProblem",
    value: function storeEndToEndSessionProblem(deviceKey, type, fixed) {
      return this._backend.storeEndToEndSessionProblem(deviceKey, type, fixed);
    }
  }, {
    key: "getEndToEndSessionProblem",
    value: function getEndToEndSessionProblem(deviceKey, timestamp) {
      return this._backend.getEndToEndSessionProblem(deviceKey, timestamp);
    }
  }, {
    key: "filterOutNotifiedErrorDevices",
    value: function filterOutNotifiedErrorDevices(devices) {
      return this._backend.filterOutNotifiedErrorDevices(devices);
    } // Inbound group sessions

    /**
     * Retrieve the end-to-end inbound group session for a given
     * server key and session ID
     * @param {string} senderCurve25519Key The sender's curve 25519 key
     * @param {string} sessionId The ID of the session
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(object)} func Called with A map from sessionId
     *     to Base64 end-to-end session.
     */

  }, {
    key: "getEndToEndInboundGroupSession",
    value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
      this._backend.getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func);
    }
    /**
     * Fetches all inbound group sessions in the store
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(object)} func Called once for each group session
     *     in the store with an object having keys {senderKey, sessionId,
     *     sessionData}, then once with null to indicate the end of the list.
     */

  }, {
    key: "getAllEndToEndInboundGroupSessions",
    value: function getAllEndToEndInboundGroupSessions(txn, func) {
      this._backend.getAllEndToEndInboundGroupSessions(txn, func);
    }
    /**
     * Adds an end-to-end inbound group session to the store.
     * If there already exists an inbound group session with the same
     * senderCurve25519Key and sessionID, the session will not be added.
     * @param {string} senderCurve25519Key The sender's curve 25519 key
     * @param {string} sessionId The ID of the session
     * @param {object} sessionData The session data structure
     * @param {*} txn An active transaction. See doTxn().
     */

  }, {
    key: "addEndToEndInboundGroupSession",
    value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      this._backend.addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
    }
    /**
     * Writes an end-to-end inbound group session to the store.
     * If there already exists an inbound group session with the same
     * senderCurve25519Key and sessionID, it will be overwritten.
     * @param {string} senderCurve25519Key The sender's curve 25519 key
     * @param {string} sessionId The ID of the session
     * @param {object} sessionData The session data structure
     * @param {*} txn An active transaction. See doTxn().
     */

  }, {
    key: "storeEndToEndInboundGroupSession",
    value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      this._backend.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
    }
  }, {
    key: "storeEndToEndInboundGroupSessionWithheld",
    value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) {
      this._backend.storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn);
    } // End-to-end device tracking

    /**
     * Store the state of all tracked devices
     * This contains devices for each user, a tracking state for each user
     * and a sync token matching the point in time the snapshot represents.
     * These all need to be written out in full each time such that the snapshot
     * is always consistent, so they are stored in one object.
     *
     * @param {Object} deviceData
     * @param {*} txn An active transaction. See doTxn().
     */

  }, {
    key: "storeEndToEndDeviceData",
    value: function storeEndToEndDeviceData(deviceData, txn) {
      this._backend.storeEndToEndDeviceData(deviceData, txn);
    }
    /**
     * Get the state of all tracked devices
     *
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(Object)} func Function called with the
     *     device data
     */

  }, {
    key: "getEndToEndDeviceData",
    value: function getEndToEndDeviceData(txn, func) {
      this._backend.getEndToEndDeviceData(txn, func);
    } // End to End Rooms

    /**
     * Store the end-to-end state for a room.
     * @param {string} roomId The room's ID.
     * @param {object} roomInfo The end-to-end info for the room.
     * @param {*} txn An active transaction. See doTxn().
     */

  }, {
    key: "storeEndToEndRoom",
    value: function storeEndToEndRoom(roomId, roomInfo, txn) {
      this._backend.storeEndToEndRoom(roomId, roomInfo, txn);
    }
    /**
     * Get an object of roomId->roomInfo for all e2e rooms in the store
     * @param {*} txn An active transaction. See doTxn().
     * @param {function(Object)} func Function called with the end to end encrypted rooms
     */

  }, {
    key: "getEndToEndRooms",
    value: function getEndToEndRooms(txn, func) {
      this._backend.getEndToEndRooms(txn, func);
    } // session backups

    /**
     * Get the inbound group sessions that need to be backed up.
     * @param {integer} limit The maximum number of sessions to retrieve.  0
     * for no limit.
     * @returns {Promise} resolves to an array of inbound group sessions
     */

  }, {
    key: "getSessionsNeedingBackup",
    value: function getSessionsNeedingBackup(limit) {
      return this._backend.getSessionsNeedingBackup(limit);
    }
    /**
     * Count the inbound group sessions that need to be backed up.
     * @param {*} txn An active transaction. See doTxn(). (optional)
     * @returns {Promise} resolves to the number of sessions
     */

  }, {
    key: "countSessionsNeedingBackup",
    value: function countSessionsNeedingBackup(txn) {
      return this._backend.countSessionsNeedingBackup(txn);
    }
    /**
     * Unmark sessions as needing to be backed up.
     * @param {Array<object>} sessions The sessions that need to be backed up.
     * @param {*} txn An active transaction. See doTxn(). (optional)
     * @returns {Promise} resolves when the sessions are unmarked
     */

  }, {
    key: "unmarkSessionsNeedingBackup",
    value: function unmarkSessionsNeedingBackup(sessions, txn) {
      return this._backend.unmarkSessionsNeedingBackup(sessions, txn);
    }
    /**
     * Mark sessions as needing to be backed up.
     * @param {Array<object>} sessions The sessions that need to be backed up.
     * @param {*} txn An active transaction. See doTxn(). (optional)
     * @returns {Promise} resolves when the sessions are marked
     */

  }, {
    key: "markSessionsNeedingBackup",
    value: function markSessionsNeedingBackup(sessions, txn) {
      return this._backend.markSessionsNeedingBackup(sessions, txn);
    }
    /**
     * Add a shared-history group session for a room.
     * @param {string} roomId The room that the key belongs to
     * @param {string} senderKey The sender's curve 25519 key
     * @param {string} sessionId The ID of the session
     * @param {*} txn An active transaction. See doTxn(). (optional)
     */

  }, {
    key: "addSharedHistoryInboundGroupSession",
    value: function addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {
      this._backend.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn);
    }
    /**
     * Get the shared-history group session for a room.
     * @param {string} roomId The room that the key belongs to
     * @param {*} txn An active transaction. See doTxn(). (optional)
     * @returns {Promise} Resolves to an array of [senderKey, sessionId]
     */

  }, {
    key: "getSharedHistoryInboundGroupSessions",
    value: function getSharedHistoryInboundGroupSessions(roomId, txn) {
      return this._backend.getSharedHistoryInboundGroupSessions(roomId, txn);
    }
    /**
     * Perform a transaction on the crypto store. Any store methods
     * that require a transaction (txn) object to be passed in may
     * only be called within a callback of either this function or
     * one of the store functions operating on the same transaction.
     *
     * @param {string} mode 'readwrite' if you need to call setter
     *     functions with this transaction. Otherwise, 'readonly'.
     * @param {string[]} stores List IndexedDBCryptoStore.STORE_*
     *     options representing all types of object that will be
     *     accessed or written to with this transaction.
     * @param {function(*)} func Function called with the
     *     transaction object: an opaque object that should be passed
     *     to store functions.
     * @param {Logger} [log] A possibly customised log
     * @return {Promise} Promise that resolves with the result of the `func`
     *     when the transaction is complete. If the backend is
     *     async (ie. the indexeddb backend) any of the callback
     *     functions throwing an exception will cause this promise to
     *     reject with that exception. On synchronous backends, the
     *     exception will propagate to the caller of the getFoo method.
     */

  }, {
    key: "doTxn",
    value: function doTxn(mode, stores, func, log) {
      return this._backend.doTxn(mode, stores, func, log);
    }
  }], [{
    key: "exists",
    value: function exists(indexedDB, dbName) {
      return IndexedDBHelpers.exists(indexedDB, dbName);
    }
  }]);
  return IndexedDBCryptoStore;
}();

exports.IndexedDBCryptoStore = IndexedDBCryptoStore;
IndexedDBCryptoStore.STORE_ACCOUNT = 'account';
IndexedDBCryptoStore.STORE_SESSIONS = 'sessions';
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions';
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD = 'inbound_group_sessions_withheld';
IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS = 'shared_history_inbound_group_sessions';
IndexedDBCryptoStore.STORE_DEVICE_DATA = 'device_data';
IndexedDBCryptoStore.STORE_ROOMS = 'rooms';
IndexedDBCryptoStore.STORE_BACKUP = 'sessions_needing_backup';

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../../errors":99,"../../indexeddb-helpers":104,"../../logger":106,"./indexeddb-crypto-store-backend":87,"./localStorage-crypto-store":89,"./memory-crypto-store":90,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13}],89:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LocalStorageCryptoStore = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _logger = require("../../logger");

var _memoryCryptoStore = require("./memory-crypto-store");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

/**
 * Internal module. Partial localStorage backed storage for e2e.
 * This is not a full crypto store, just the in-memory store with
 * some things backed by localStorage. It exists because indexedDB
 * is broken in Firefox private mode or set to, "will not remember
 * history".
 *
 * @module
 */
var E2E_PREFIX = "crypto.";
var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
var KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + "cross_signing_keys";
var KEY_NOTIFIED_ERROR_DEVICES = E2E_PREFIX + "notified_error_devices";
var KEY_DEVICE_DATA = E2E_PREFIX + "device_data";
var KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + "inboundgroupsessions/";
var KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + "inboundgroupsessions.withheld/";
var KEY_ROOMS_PREFIX = E2E_PREFIX + "rooms/";
var KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + "sessionsneedingbackup";

function keyEndToEndSessions(deviceKey) {
  return E2E_PREFIX + "sessions/" + deviceKey;
}

function keyEndToEndSessionProblems(deviceKey) {
  return E2E_PREFIX + "session.problems/" + deviceKey;
}

function keyEndToEndInboundGroupSession(senderKey, sessionId) {
  return KEY_INBOUND_SESSION_PREFIX + senderKey + "/" + sessionId;
}

function keyEndToEndInboundGroupSessionWithheld(senderKey, sessionId) {
  return KEY_INBOUND_SESSION_WITHHELD_PREFIX + senderKey + "/" + sessionId;
}

function keyEndToEndRoomsPrefix(roomId) {
  return KEY_ROOMS_PREFIX + roomId;
}
/**
 * @implements {module:crypto/store/base~CryptoStore}
 */


var LocalStorageCryptoStore = /*#__PURE__*/function (_MemoryCryptoStore) {
  (0, _inherits2["default"])(LocalStorageCryptoStore, _MemoryCryptoStore);

  var _super = _createSuper(LocalStorageCryptoStore);

  function LocalStorageCryptoStore(webStore) {
    var _this;

    (0, _classCallCheck2["default"])(this, LocalStorageCryptoStore);
    _this = _super.call(this);
    _this.store = webStore;
    return _this;
  }

  (0, _createClass2["default"])(LocalStorageCryptoStore, [{
    key: "countEndToEndSessions",
    // Olm Sessions
    value: function countEndToEndSessions(txn, func) {
      var count = 0;

      for (var i = 0; i < this.store.length; ++i) {
        if (this.store.key(i).startsWith(keyEndToEndSessions(''))) ++count;
      }

      func(count);
    }
  }, {
    key: "_getEndToEndSessions",
    value: function _getEndToEndSessions(deviceKey, txn, func) {
      var sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey));
      var fixedSessions = {}; // fix up any old sessions to be objects rather than just the base64 pickle

      for (var _i = 0, _Object$entries = Object.entries(sessions || {}); _i < _Object$entries.length; _i++) {
        var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2),
            sid = _Object$entries$_i[0],
            val = _Object$entries$_i[1];

        if (typeof val === 'string') {
          fixedSessions[sid] = {
            session: val
          };
        } else {
          fixedSessions[sid] = val;
        }
      }

      return fixedSessions;
    }
  }, {
    key: "getEndToEndSession",
    value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
      var sessions = this._getEndToEndSessions(deviceKey);

      func(sessions[sessionId] || {});
    }
  }, {
    key: "getEndToEndSessions",
    value: function getEndToEndSessions(deviceKey, txn, func) {
      func(this._getEndToEndSessions(deviceKey) || {});
    }
  }, {
    key: "getAllEndToEndSessions",
    value: function getAllEndToEndSessions(txn, func) {
      for (var i = 0; i < this.store.length; ++i) {
        if (this.store.key(i).startsWith(keyEndToEndSessions(''))) {
          var deviceKey = this.store.key(i).split('/')[1];

          for (var _i2 = 0, _Object$values = Object.values(this._getEndToEndSessions(deviceKey)); _i2 < _Object$values.length; _i2++) {
            var sess = _Object$values[_i2];
            func(sess);
          }
        }
      }
    }
  }, {
    key: "storeEndToEndSession",
    value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
      var sessions = this._getEndToEndSessions(deviceKey) || {};
      sessions[sessionId] = sessionInfo;
      setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions);
    }
  }, {
    key: "storeEndToEndSessionProblem",
    value: function () {
      var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(deviceKey, type, fixed) {
        var key, problems;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                key = keyEndToEndSessionProblems(deviceKey);
                problems = getJsonItem(this.store, key) || [];
                problems.push({
                  type: type,
                  fixed: fixed,
                  time: Date.now()
                });
                problems.sort(function (a, b) {
                  return a.time - b.time;
                });
                setJsonItem(this.store, key, problems);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function storeEndToEndSessionProblem(_x, _x2, _x3) {
        return _storeEndToEndSessionProblem.apply(this, arguments);
      }

      return storeEndToEndSessionProblem;
    }()
  }, {
    key: "getEndToEndSessionProblem",
    value: function () {
      var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, timestamp) {
        var key, problems, lastProblem, _iterator, _step, problem;

        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                key = keyEndToEndSessionProblems(deviceKey);
                problems = getJsonItem(this.store, key) || [];

                if (problems.length) {
                  _context2.next = 4;
                  break;
                }

                return _context2.abrupt("return", null);

              case 4:
                lastProblem = problems[problems.length - 1];
                _iterator = _createForOfIteratorHelper(problems);
                _context2.prev = 6;

                _iterator.s();

              case 8:
                if ((_step = _iterator.n()).done) {
                  _context2.next = 14;
                  break;
                }

                problem = _step.value;

                if (!(problem.time > timestamp)) {
                  _context2.next = 12;
                  break;
                }

                return _context2.abrupt("return", Object.assign({}, problem, {
                  fixed: lastProblem.fixed
                }));

              case 12:
                _context2.next = 8;
                break;

              case 14:
                _context2.next = 19;
                break;

              case 16:
                _context2.prev = 16;
                _context2.t0 = _context2["catch"](6);

                _iterator.e(_context2.t0);

              case 19:
                _context2.prev = 19;

                _iterator.f();

                return _context2.finish(19);

              case 22:
                if (!lastProblem.fixed) {
                  _context2.next = 26;
                  break;
                }

                return _context2.abrupt("return", null);

              case 26:
                return _context2.abrupt("return", lastProblem);

              case 27:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[6, 16, 19, 22]]);
      }));

      function getEndToEndSessionProblem(_x4, _x5) {
        return _getEndToEndSessionProblem.apply(this, arguments);
      }

      return getEndToEndSessionProblem;
    }()
  }, {
    key: "filterOutNotifiedErrorDevices",
    value: function () {
      var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(devices) {
        var notifiedErrorDevices, ret, _iterator2, _step2, device, userId, deviceInfo;

        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                notifiedErrorDevices = getJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES) || {};
                ret = [];
                _iterator2 = _createForOfIteratorHelper(devices);

                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    device = _step2.value;
                    userId = device.userId, deviceInfo = device.deviceInfo;

                    if (userId in notifiedErrorDevices) {
                      if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {
                        ret.push(device);
                        notifiedErrorDevices[userId][deviceInfo.deviceId] = true;
                      }
                    } else {
                      ret.push(device);
                      notifiedErrorDevices[userId] = (0, _defineProperty2["default"])({}, deviceInfo.deviceId, true);
                    }
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }

                setJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES, notifiedErrorDevices);
                return _context3.abrupt("return", ret);

              case 6:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function filterOutNotifiedErrorDevices(_x6) {
        return _filterOutNotifiedErrorDevices.apply(this, arguments);
      }

      return filterOutNotifiedErrorDevices;
    }() // Inbound Group Sessions

  }, {
    key: "getEndToEndInboundGroupSession",
    value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
      func(getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)), getJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId)));
    }
  }, {
    key: "getAllEndToEndInboundGroupSessions",
    value: function getAllEndToEndInboundGroupSessions(txn, func) {
      for (var i = 0; i < this.store.length; ++i) {
        var key = this.store.key(i);

        if (key.startsWith(KEY_INBOUND_SESSION_PREFIX)) {
          // we can't use split, as the components we are trying to split out
          // might themselves contain '/' characters. We rely on the
          // senderKey being a (32-byte) curve25519 key, base64-encoded
          // (hence 43 characters long).
          func({
            senderKey: key.substr(KEY_INBOUND_SESSION_PREFIX.length, 43),
            sessionId: key.substr(KEY_INBOUND_SESSION_PREFIX.length + 44),
            sessionData: getJsonItem(this.store, key)
          });
        }
      }

      func(null);
    }
  }, {
    key: "addEndToEndInboundGroupSession",
    value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      var existing = getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId));

      if (!existing) {
        this.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
      }
    }
  }, {
    key: "storeEndToEndInboundGroupSession",
    value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData);
    }
  }, {
    key: "storeEndToEndInboundGroupSessionWithheld",
    value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) {
      setJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId), sessionData);
    }
  }, {
    key: "getEndToEndDeviceData",
    value: function getEndToEndDeviceData(txn, func) {
      func(getJsonItem(this.store, KEY_DEVICE_DATA));
    }
  }, {
    key: "storeEndToEndDeviceData",
    value: function storeEndToEndDeviceData(deviceData, txn) {
      setJsonItem(this.store, KEY_DEVICE_DATA, deviceData);
    }
  }, {
    key: "storeEndToEndRoom",
    value: function storeEndToEndRoom(roomId, roomInfo, txn) {
      setJsonItem(this.store, keyEndToEndRoomsPrefix(roomId), roomInfo);
    }
  }, {
    key: "getEndToEndRooms",
    value: function getEndToEndRooms(txn, func) {
      var result = {};
      var prefix = keyEndToEndRoomsPrefix('');

      for (var i = 0; i < this.store.length; ++i) {
        var key = this.store.key(i);

        if (key.startsWith(prefix)) {
          var roomId = key.substr(prefix.length);
          result[roomId] = getJsonItem(this.store, key);
        }
      }

      func(result);
    }
  }, {
    key: "getSessionsNeedingBackup",
    value: function getSessionsNeedingBackup(limit) {
      var _this2 = this;

      var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};
      var sessions = [];

      for (var session in sessionsNeedingBackup) {
        if (Object.prototype.hasOwnProperty.call(sessionsNeedingBackup, session)) {
          var _ret = function () {
            // see getAllEndToEndInboundGroupSessions for the magic number explanations
            var senderKey = session.substr(0, 43);
            var sessionId = session.substr(44);

            _this2.getEndToEndInboundGroupSession(senderKey, sessionId, null, function (sessionData) {
              sessions.push({
                senderKey: senderKey,
                sessionId: sessionId,
                sessionData: sessionData
              });
            });

            if (limit && session.length >= limit) {
              return "break";
            }
          }();

          if (_ret === "break") break;
        }
      }

      return Promise.resolve(sessions);
    }
  }, {
    key: "countSessionsNeedingBackup",
    value: function countSessionsNeedingBackup() {
      var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};
      return Promise.resolve(Object.keys(sessionsNeedingBackup).length);
    }
  }, {
    key: "unmarkSessionsNeedingBackup",
    value: function unmarkSessionsNeedingBackup(sessions) {
      var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};

      var _iterator3 = _createForOfIteratorHelper(sessions),
          _step3;

      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var session = _step3.value;
          delete sessionsNeedingBackup[session.senderKey + '/' + session.sessionId];
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }

      setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup);
      return Promise.resolve();
    }
  }, {
    key: "markSessionsNeedingBackup",
    value: function markSessionsNeedingBackup(sessions) {
      var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};

      var _iterator4 = _createForOfIteratorHelper(sessions),
          _step4;

      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var session = _step4.value;
          sessionsNeedingBackup[session.senderKey + '/' + session.sessionId] = true;
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }

      setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup);
      return Promise.resolve();
    }
    /**
     * Delete all data from this store.
     *
     * @returns {Promise} Promise which resolves when the store has been cleared.
     */

  }, {
    key: "deleteAllData",
    value: function deleteAllData() {
      this.store.removeItem(KEY_END_TO_END_ACCOUNT);
      return Promise.resolve();
    } // Olm account

  }, {
    key: "getAccount",
    value: function getAccount(txn, func) {
      var account = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT);
      func(account);
    }
  }, {
    key: "storeAccount",
    value: function storeAccount(txn, newData) {
      setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, newData);
    }
  }, {
    key: "getCrossSigningKeys",
    value: function getCrossSigningKeys(txn, func) {
      var keys = getJsonItem(this.store, KEY_CROSS_SIGNING_KEYS);
      func(keys);
    }
  }, {
    key: "getSecretStorePrivateKey",
    value: function getSecretStorePrivateKey(txn, func, type) {
      var key = getJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type));
      func(key);
    }
  }, {
    key: "storeCrossSigningKeys",
    value: function storeCrossSigningKeys(txn, keys) {
      setJsonItem(this.store, KEY_CROSS_SIGNING_KEYS, keys);
    }
  }, {
    key: "storeSecretStorePrivateKey",
    value: function storeSecretStorePrivateKey(txn, type, key) {
      setJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type), key);
    }
  }, {
    key: "doTxn",
    value: function doTxn(mode, stores, func) {
      return Promise.resolve(func(null));
    }
  }], [{
    key: "exists",
    value: function exists(webStore) {
      var length = webStore.length;

      for (var i = 0; i < length; i++) {
        if (webStore.key(i).startsWith(E2E_PREFIX)) {
          return true;
        }
      }

      return false;
    }
  }]);
  return LocalStorageCryptoStore;
}(_memoryCryptoStore.MemoryCryptoStore);

exports.LocalStorageCryptoStore = LocalStorageCryptoStore;

function getJsonItem(store, key) {
  try {
    // if the key is absent, store.getItem() returns null, and
    // JSON.parse(null) === null, so this returns null.
    return JSON.parse(store.getItem(key));
  } catch (e) {
    _logger.logger.log("Error: Failed to get key %s: %s", key, e.stack || e);

    _logger.logger.log(e.stack);
  }

  return null;
}

function setJsonItem(store, key, val) {
  store.setItem(key, JSON.stringify(val));
}

},{"../../logger":106,"./memory-crypto-store":90,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],90:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MemoryCryptoStore = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _logger = require("../../logger");

var utils = _interopRequireWildcard(require("../../utils"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

/**
 * Internal module. in-memory storage for e2e.
 *
 * @module
 */

/**
 * @implements {module:crypto/store/base~CryptoStore}
 */
var MemoryCryptoStore = /*#__PURE__*/function () {
  function MemoryCryptoStore() {
    (0, _classCallCheck2["default"])(this, MemoryCryptoStore);
    this._outgoingRoomKeyRequests = [];
    this._account = null;
    this._crossSigningKeys = null;
    this._privateKeys = {};
    this._backupKeys = {}; // Map of {devicekey -> {sessionId -> session pickle}}

    this._sessions = {}; // Map of {devicekey -> array of problems}

    this._sessionProblems = {}; // Map of {userId -> deviceId -> true}

    this._notifiedErrorDevices = {}; // Map of {senderCurve25519Key+'/'+sessionId -> session data object}

    this._inboundGroupSessions = {};
    this._inboundGroupSessionsWithheld = {}; // Opaque device data object

    this._deviceData = null; // roomId -> Opaque roomInfo object

    this._rooms = {}; // Set of {senderCurve25519Key+'/'+sessionId}

    this._sessionsNeedingBackup = {}; // roomId -> array of [senderKey, sessionId]

    this._sharedHistoryInboundGroupSessions = {};
  }
  /**
   * Ensure the database exists and is up-to-date.
   *
   * This must be called before the store can be used.
   *
   * @return {Promise} resolves to the store.
   */


  (0, _createClass2["default"])(MemoryCryptoStore, [{
    key: "startup",
    value: function () {
      var _startup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt("return", this);

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function startup() {
        return _startup.apply(this, arguments);
      }

      return startup;
    }()
    /**
     * Delete all data from this store.
     *
     * @returns {Promise} Promise which resolves when the store has been cleared.
     */

  }, {
    key: "deleteAllData",
    value: function deleteAllData() {
      return Promise.resolve();
    }
    /**
     * Look for an existing outgoing room key request, and if none is found,
     * add a new one
     *
     * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
     *
     * @returns {Promise} resolves to
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
     *    same instance as passed in, or the existing one.
     */

  }, {
    key: "getOrAddOutgoingRoomKeyRequest",
    value: function getOrAddOutgoingRoomKeyRequest(request) {
      var _this = this;

      var requestBody = request.requestBody;
      return utils.promiseTry(function () {
        // first see if we already have an entry for this request.
        var existing = _this._getOutgoingRoomKeyRequest(requestBody);

        if (existing) {
          // this entry matches the request - return it.
          _logger.logger.log("already have key request outstanding for " + "".concat(requestBody.room_id, " / ").concat(requestBody.session_id, ": ") + "not sending another");

          return existing;
        } // we got to the end of the list without finding a match
        // - add the new request.


        _logger.logger.log("enqueueing key request for ".concat(requestBody.room_id, " / ") + requestBody.session_id);

        _this._outgoingRoomKeyRequests.push(request);

        return request;
      });
    }
    /**
     * Look for an existing room key request
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    existing request to look for
     *
     * @return {Promise} resolves to the matching
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    not found
     */

  }, {
    key: "getOutgoingRoomKeyRequest",
    value: function getOutgoingRoomKeyRequest(requestBody) {
      return Promise.resolve(this._getOutgoingRoomKeyRequest(requestBody));
    }
    /**
     * Looks for existing room key request, and returns the result synchronously.
     *
     * @internal
     *
     * @param {module:crypto~RoomKeyRequestBody} requestBody
     *    existing request to look for
     *
     * @return {module:crypto/store/base~OutgoingRoomKeyRequest?}
     *    the matching request, or null if not found
     */

  }, {
    key: "_getOutgoingRoomKeyRequest",
    value: function _getOutgoingRoomKeyRequest(requestBody) {
      var _iterator = _createForOfIteratorHelper(this._outgoingRoomKeyRequests),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var existing = _step.value;

          if (utils.deepCompare(existing.requestBody, requestBody)) {
            return existing;
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return null;
    }
    /**
     * Look for room key requests by state
     *
     * @param {Array<Number>} wantedStates list of acceptable states
     *
     * @return {Promise} resolves to the a
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
     *    there are no pending requests in those states
     */

  }, {
    key: "getOutgoingRoomKeyRequestByState",
    value: function getOutgoingRoomKeyRequestByState(wantedStates) {
      var _iterator2 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var req = _step2.value;

          var _iterator3 = _createForOfIteratorHelper(wantedStates),
              _step3;

          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var state = _step3.value;

              if (req.state === state) {
                return Promise.resolve(req);
              }
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      return Promise.resolve(null);
    }
    /**
     *
     * @param {Number} wantedState
     * @return {Promise<Array<*>>} All OutgoingRoomKeyRequests in state
     */

  }, {
    key: "getAllOutgoingRoomKeyRequestsByState",
    value: function getAllOutgoingRoomKeyRequestsByState(wantedState) {
      return Promise.resolve(this._outgoingRoomKeyRequests.filter(function (r) {
        return r.state == wantedState;
      }));
    }
  }, {
    key: "getOutgoingRoomKeyRequestsByTarget",
    value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {
      var results = [];

      var _iterator4 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests),
          _step4;

      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var req = _step4.value;

          var _iterator5 = _createForOfIteratorHelper(wantedStates),
              _step5;

          try {
            for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
              var state = _step5.value;

              if (req.state === state && req.recipients.includes({
                userId: userId,
                deviceId: deviceId
              })) {
                results.push(req);
              }
            }
          } catch (err) {
            _iterator5.e(err);
          } finally {
            _iterator5.f();
          }
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }

      return Promise.resolve(results);
    }
    /**
     * Look for an existing room key request by id and state, and update it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     * @param {Object} updates        name/value map of updates to apply
     *
     * @returns {Promise} resolves to
     *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
     *    updated request, or null if no matching row was found
     */

  }, {
    key: "updateOutgoingRoomKeyRequest",
    value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {
      var _iterator6 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests),
          _step6;

      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var req = _step6.value;

          if (req.requestId !== requestId) {
            continue;
          }

          if (req.state != expectedState) {
            _logger.logger.warn("Cannot update room key request from ".concat(expectedState, " ") + "as it was already updated to ".concat(req.state));

            return Promise.resolve(null);
          }

          Object.assign(req, updates);
          return Promise.resolve(req);
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }

      return Promise.resolve(null);
    }
    /**
     * Look for an existing room key request by id and state, and delete it if
     * found
     *
     * @param {string} requestId      ID of request to update
     * @param {number} expectedState  state we expect to find the request in
     *
     * @returns {Promise} resolves once the operation is completed
     */

  }, {
    key: "deleteOutgoingRoomKeyRequest",
    value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) {
      for (var i = 0; i < this._outgoingRoomKeyRequests.length; i++) {
        var req = this._outgoingRoomKeyRequests[i];

        if (req.requestId !== requestId) {
          continue;
        }

        if (req.state != expectedState) {
          _logger.logger.warn("Cannot delete room key request in state ".concat(req.state, " ") + "(expected ".concat(expectedState, ")"));

          return Promise.resolve(null);
        }

        this._outgoingRoomKeyRequests.splice(i, 1);

        return Promise.resolve(req);
      }

      return Promise.resolve(null);
    } // Olm Account

  }, {
    key: "getAccount",
    value: function getAccount(txn, func) {
      func(this._account);
    }
  }, {
    key: "storeAccount",
    value: function storeAccount(txn, newData) {
      this._account = newData;
    }
  }, {
    key: "getCrossSigningKeys",
    value: function getCrossSigningKeys(txn, func) {
      func(this._crossSigningKeys);
    }
  }, {
    key: "getSecretStorePrivateKey",
    value: function getSecretStorePrivateKey(txn, func, type) {
      var result = this._privateKeys[type];
      return func(result || null);
    }
  }, {
    key: "storeCrossSigningKeys",
    value: function storeCrossSigningKeys(txn, keys) {
      this._crossSigningKeys = keys;
    }
  }, {
    key: "storeSecretStorePrivateKey",
    value: function storeSecretStorePrivateKey(txn, type, key) {
      this._privateKeys[type] = key;
    } // Olm Sessions

  }, {
    key: "countEndToEndSessions",
    value: function countEndToEndSessions(txn, func) {
      return Object.keys(this._sessions).length;
    }
  }, {
    key: "getEndToEndSession",
    value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
      var deviceSessions = this._sessions[deviceKey] || {};
      func(deviceSessions[sessionId] || null);
    }
  }, {
    key: "getEndToEndSessions",
    value: function getEndToEndSessions(deviceKey, txn, func) {
      func(this._sessions[deviceKey] || {});
    }
  }, {
    key: "getAllEndToEndSessions",
    value: function getAllEndToEndSessions(txn, func) {
      Object.entries(this._sessions).forEach(function (_ref) {
        var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
            deviceKey = _ref2[0],
            deviceSessions = _ref2[1];

        Object.entries(deviceSessions).forEach(function (_ref3) {
          var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
              sessionId = _ref4[0],
              session = _ref4[1];

          func(_objectSpread(_objectSpread({}, session), {}, {
            deviceKey: deviceKey,
            sessionId: sessionId
          }));
        });
      });
    }
  }, {
    key: "storeEndToEndSession",
    value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
      var deviceSessions = this._sessions[deviceKey];

      if (deviceSessions === undefined) {
        deviceSessions = {};
        this._sessions[deviceKey] = deviceSessions;
      }

      deviceSessions[sessionId] = sessionInfo;
    }
  }, {
    key: "storeEndToEndSessionProblem",
    value: function () {
      var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, type, fixed) {
        var problems;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                problems = this._sessionProblems[deviceKey] = this._sessionProblems[deviceKey] || [];
                problems.push({
                  type: type,
                  fixed: fixed,
                  time: Date.now()
                });
                problems.sort(function (a, b) {
                  return a.time - b.time;
                });

              case 3:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function storeEndToEndSessionProblem(_x, _x2, _x3) {
        return _storeEndToEndSessionProblem.apply(this, arguments);
      }

      return storeEndToEndSessionProblem;
    }()
  }, {
    key: "getEndToEndSessionProblem",
    value: function () {
      var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(deviceKey, timestamp) {
        var problems, lastProblem, _iterator7, _step7, problem;

        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                problems = this._sessionProblems[deviceKey] || [];

                if (problems.length) {
                  _context3.next = 3;
                  break;
                }

                return _context3.abrupt("return", null);

              case 3:
                lastProblem = problems[problems.length - 1];
                _iterator7 = _createForOfIteratorHelper(problems);
                _context3.prev = 5;

                _iterator7.s();

              case 7:
                if ((_step7 = _iterator7.n()).done) {
                  _context3.next = 13;
                  break;
                }

                problem = _step7.value;

                if (!(problem.time > timestamp)) {
                  _context3.next = 11;
                  break;
                }

                return _context3.abrupt("return", Object.assign({}, problem, {
                  fixed: lastProblem.fixed
                }));

              case 11:
                _context3.next = 7;
                break;

              case 13:
                _context3.next = 18;
                break;

              case 15:
                _context3.prev = 15;
                _context3.t0 = _context3["catch"](5);

                _iterator7.e(_context3.t0);

              case 18:
                _context3.prev = 18;

                _iterator7.f();

                return _context3.finish(18);

              case 21:
                if (!lastProblem.fixed) {
                  _context3.next = 25;
                  break;
                }

                return _context3.abrupt("return", null);

              case 25:
                return _context3.abrupt("return", lastProblem);

              case 26:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this, [[5, 15, 18, 21]]);
      }));

      function getEndToEndSessionProblem(_x4, _x5) {
        return _getEndToEndSessionProblem.apply(this, arguments);
      }

      return getEndToEndSessionProblem;
    }()
  }, {
    key: "filterOutNotifiedErrorDevices",
    value: function () {
      var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(devices) {
        var notifiedErrorDevices, ret, _iterator8, _step8, device, userId, deviceInfo;

        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                notifiedErrorDevices = this._notifiedErrorDevices;
                ret = [];
                _iterator8 = _createForOfIteratorHelper(devices);

                try {
                  for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
                    device = _step8.value;
                    userId = device.userId, deviceInfo = device.deviceInfo;

                    if (userId in notifiedErrorDevices) {
                      if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {
                        ret.push(device);
                        notifiedErrorDevices[userId][deviceInfo.deviceId] = true;
                      }
                    } else {
                      ret.push(device);
                      notifiedErrorDevices[userId] = (0, _defineProperty2["default"])({}, deviceInfo.deviceId, true);
                    }
                  }
                } catch (err) {
                  _iterator8.e(err);
                } finally {
                  _iterator8.f();
                }

                return _context4.abrupt("return", ret);

              case 5:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function filterOutNotifiedErrorDevices(_x6) {
        return _filterOutNotifiedErrorDevices.apply(this, arguments);
      }

      return filterOutNotifiedErrorDevices;
    }() // Inbound Group Sessions

  }, {
    key: "getEndToEndInboundGroupSession",
    value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
      var k = senderCurve25519Key + '/' + sessionId;
      func(this._inboundGroupSessions[k] || null, this._inboundGroupSessionsWithheld[k] || null);
    }
  }, {
    key: "getAllEndToEndInboundGroupSessions",
    value: function getAllEndToEndInboundGroupSessions(txn, func) {
      for (var _i = 0, _Object$keys = Object.keys(this._inboundGroupSessions); _i < _Object$keys.length; _i++) {
        var key = _Object$keys[_i];
        // we can't use split, as the components we are trying to split out
        // might themselves contain '/' characters. We rely on the
        // senderKey being a (32-byte) curve25519 key, base64-encoded
        // (hence 43 characters long).
        func({
          senderKey: key.substr(0, 43),
          sessionId: key.substr(44),
          sessionData: this._inboundGroupSessions[key]
        });
      }

      func(null);
    }
  }, {
    key: "addEndToEndInboundGroupSession",
    value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      var k = senderCurve25519Key + '/' + sessionId;

      if (this._inboundGroupSessions[k] === undefined) {
        this._inboundGroupSessions[k] = sessionData;
      }
    }
  }, {
    key: "storeEndToEndInboundGroupSession",
    value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
      this._inboundGroupSessions[senderCurve25519Key + '/' + sessionId] = sessionData;
    }
  }, {
    key: "storeEndToEndInboundGroupSessionWithheld",
    value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) {
      var k = senderCurve25519Key + '/' + sessionId;
      this._inboundGroupSessionsWithheld[k] = sessionData;
    } // Device Data

  }, {
    key: "getEndToEndDeviceData",
    value: function getEndToEndDeviceData(txn, func) {
      func(this._deviceData);
    }
  }, {
    key: "storeEndToEndDeviceData",
    value: function storeEndToEndDeviceData(deviceData, txn) {
      this._deviceData = deviceData;
    } // E2E rooms

  }, {
    key: "storeEndToEndRoom",
    value: function storeEndToEndRoom(roomId, roomInfo, txn) {
      this._rooms[roomId] = roomInfo;
    }
  }, {
    key: "getEndToEndRooms",
    value: function getEndToEndRooms(txn, func) {
      func(this._rooms);
    }
  }, {
    key: "getSessionsNeedingBackup",
    value: function getSessionsNeedingBackup(limit) {
      var sessions = [];

      for (var session in this._sessionsNeedingBackup) {
        if (this._inboundGroupSessions[session]) {
          sessions.push({
            senderKey: session.substr(0, 43),
            sessionId: session.substr(44),
            sessionData: this._inboundGroupSessions[session]
          });

          if (limit && session.length >= limit) {
            break;
          }
        }
      }

      return Promise.resolve(sessions);
    }
  }, {
    key: "countSessionsNeedingBackup",
    value: function countSessionsNeedingBackup() {
      return Promise.resolve(Object.keys(this._sessionsNeedingBackup).length);
    }
  }, {
    key: "unmarkSessionsNeedingBackup",
    value: function unmarkSessionsNeedingBackup(sessions) {
      var _iterator9 = _createForOfIteratorHelper(sessions),
          _step9;

      try {
        for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
          var session = _step9.value;
          var sessionKey = session.senderKey + '/' + session.sessionId;
          delete this._sessionsNeedingBackup[sessionKey];
        }
      } catch (err) {
        _iterator9.e(err);
      } finally {
        _iterator9.f();
      }

      return Promise.resolve();
    }
  }, {
    key: "markSessionsNeedingBackup",
    value: function markSessionsNeedingBackup(sessions) {
      var _iterator10 = _createForOfIteratorHelper(sessions),
          _step10;

      try {
        for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
          var session = _step10.value;
          var sessionKey = session.senderKey + '/' + session.sessionId;
          this._sessionsNeedingBackup[sessionKey] = true;
        }
      } catch (err) {
        _iterator10.e(err);
      } finally {
        _iterator10.f();
      }

      return Promise.resolve();
    }
  }, {
    key: "addSharedHistoryInboundGroupSession",
    value: function addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId) {
      var sessions = this._sharedHistoryInboundGroupSessions[roomId] || [];
      sessions.push([senderKey, sessionId]);
      this._sharedHistoryInboundGroupSessions[roomId] = sessions;
    }
  }, {
    key: "getSharedHistoryInboundGroupSessions",
    value: function getSharedHistoryInboundGroupSessions(roomId) {
      return Promise.resolve(this._sharedHistoryInboundGroupSessions[roomId] || []);
    } // Session key backups

  }, {
    key: "doTxn",
    value: function doTxn(mode, stores, func) {
      return Promise.resolve(func(null));
    }
  }]);
  return MemoryCryptoStore;
}();

exports.MemoryCryptoStore = MemoryCryptoStore;

},{"../../logger":106,"../../utils":137,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],91:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VerificationBase = exports.SwitchStartEventError = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));

var _event = require("../../models/event");

var _events = require("events");

var _logger = require("../../logger");

var _deviceinfo = require("../deviceinfo");

var _Error2 = require("./Error");

var _CrossSigning = require("../CrossSigning");

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

var timeoutException = new Error("Verification timed out");

var SwitchStartEventError = /*#__PURE__*/function (_Error) {
  (0, _inherits2["default"])(SwitchStartEventError, _Error);

  var _super = _createSuper(SwitchStartEventError);

  function SwitchStartEventError(startEvent) {
    var _this;

    (0, _classCallCheck2["default"])(this, SwitchStartEventError);
    _this = _super.call(this);
    _this.startEvent = startEvent;
    return _this;
  }

  return SwitchStartEventError;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));

exports.SwitchStartEventError = SwitchStartEventError;

var VerificationBase = /*#__PURE__*/function (_EventEmitter) {
  (0, _inherits2["default"])(VerificationBase, _EventEmitter);

  var _super2 = _createSuper(VerificationBase);

  /**
   * Base class for verification methods.
   *
   * <p>Once a verifier object is created, the verification can be started by
   * calling the verify() method, which will return a promise that will
   * resolve when the verification is completed, or reject if it could not
   * complete.</p>
   *
   * <p>Subclasses must have a NAME class property.</p>
   *
   * @class
   *
   * @param {Object} channel the verification channel to send verification messages over.
   * TODO: Channel types
   *
   * @param {MatrixClient} baseApis base matrix api interface
   *
   * @param {string} userId the user ID that is being verified
   *
   * @param {string} deviceId the device ID that is being verified
   *
   * @param {object} [startEvent] the m.key.verification.start event that
   * initiated this verification, if any
   *
   * @param {object} [request] the key verification request object related to
   * this verification, if any
   */
  function VerificationBase(channel, baseApis, userId, deviceId, startEvent, request) {
    var _this2;

    (0, _classCallCheck2["default"])(this, VerificationBase);
    _this2 = _super2.call(this);
    _this2._channel = channel;
    _this2._baseApis = baseApis;
    _this2.userId = userId;
    _this2.deviceId = deviceId;
    _this2.startEvent = startEvent;
    _this2.request = request;
    _this2.cancelled = false;
    _this2._done = false;
    _this2._promise = null;
    _this2._transactionTimeoutTimer = null;
    return _this2;
  }

  (0, _createClass2["default"])(VerificationBase, [{
    key: "_resetTimer",
    value: function _resetTimer() {
      var _this3 = this;

      _logger.logger.info("Refreshing/starting the verification transaction timeout timer");

      if (this._transactionTimeoutTimer !== null) {
        clearTimeout(this._transactionTimeoutTimer);
      }

      this._transactionTimeoutTimer = setTimeout(function () {
        if (!_this3._done && !_this3.cancelled) {
          _logger.logger.info("Triggering verification timeout");

          _this3.cancel(timeoutException);
        }
      }, 10 * 60 * 1000); // 10 minutes
    }
  }, {
    key: "_endTimer",
    value: function _endTimer() {
      if (this._transactionTimeoutTimer !== null) {
        clearTimeout(this._transactionTimeoutTimer);
        this._transactionTimeoutTimer = null;
      }
    }
  }, {
    key: "_send",
    value: function _send(type, uncompletedContent) {
      return this._channel.send(type, uncompletedContent);
    }
  }, {
    key: "_waitForEvent",
    value: function _waitForEvent(type) {
      var _this4 = this;

      if (this._done) {
        return Promise.reject(new Error("Verification is already done"));
      }

      var existingEvent = this.request.getEventFromOtherParty(type);

      if (existingEvent) {
        return Promise.resolve(existingEvent);
      }

      this._expectedEvent = type;
      return new Promise(function (resolve, reject) {
        _this4._resolveEvent = resolve;
        _this4._rejectEvent = reject;
      });
    }
  }, {
    key: "canSwitchStartEvent",
    value: function canSwitchStartEvent() {
      return false;
    }
  }, {
    key: "switchStartEvent",
    value: function switchStartEvent(event) {
      if (this.canSwitchStartEvent(event)) {
        _logger.logger.log("Verification Base: switching verification start event", {
          restartingFlow: !!this._rejectEvent
        });

        if (this._rejectEvent) {
          var reject = this._rejectEvent;
          this._rejectEvent = undefined;
          reject(new SwitchStartEventError(event));
        } else {
          this.startEvent = event;
        }
      }
    }
  }, {
    key: "handleEvent",
    value: function handleEvent(e) {
      if (this._done) {
        return;
      } else if (e.getType() === this._expectedEvent) {
        // if we receive an expected m.key.verification.done, then just
        // ignore it, since we don't need to do anything about it
        if (this._expectedEvent !== "m.key.verification.done") {
          this._expectedEvent = undefined;
          this._rejectEvent = undefined;

          this._resetTimer();

          this._resolveEvent(e);
        }
      } else if (e.getType() === "m.key.verification.cancel") {
        var reject = this._reject;
        this._reject = undefined; // there is only promise to reject if verify has been called

        if (reject) {
          var content = e.getContent();
          var reason = content.reason,
              code = content.code;
          reject(new Error("Other side cancelled verification " + "because ".concat(reason, " (").concat(code, ")")));
        }
      } else if (this._expectedEvent) {
        // only cancel if there is an event expected.
        // if there is no event expected, it means verify() wasn't called
        // and we're just replaying the timeline events when syncing
        // after a refresh when the events haven't been stored in the cache yet.
        var exception = new Error("Unexpected message: expecting " + this._expectedEvent + " but got " + e.getType());
        this._expectedEvent = undefined;

        if (this._rejectEvent) {
          var _reject = this._rejectEvent;
          this._rejectEvent = undefined;

          _reject(exception);
        }

        this.cancel(exception);
      }
    }
  }, {
    key: "done",
    value: function done() {
      this._endTimer(); // always kill the activity timer


      if (!this._done) {
        this.request.onVerifierFinished();

        this._resolve();

        return (0, _CrossSigning.requestKeysDuringVerification)(this._baseApis, this.userId, this.deviceId);
      }
    }
  }, {
    key: "cancel",
    value: function cancel(e) {
      this._endTimer(); // always kill the activity timer


      if (!this._done) {
        this.cancelled = true;
        this.request.onVerifierCancelled();

        if (this.userId && this.deviceId) {
          // send a cancellation to the other user (if it wasn't
          // cancelled by the other user)
          if (e === timeoutException) {
            var timeoutEvent = (0, _Error2.newTimeoutError)();

            this._send(timeoutEvent.getType(), timeoutEvent.getContent());
          } else if (e instanceof _event.MatrixEvent) {
            var sender = e.getSender();

            if (sender !== this.userId) {
              var content = e.getContent();

              if (e.getType() === "m.key.verification.cancel") {
                content.code = content.code || "m.unknown";
                content.reason = content.reason || content.body || "Unknown reason";

                this._send("m.key.verification.cancel", content);
              } else {
                this._send("m.key.verification.cancel", {
                  code: "m.unknown",
                  reason: content.body || "Unknown reason"
                });
              }
            }
          } else {
            this._send("m.key.verification.cancel", {
              code: "m.unknown",
              reason: e.toString()
            });
          }
        }

        if (this._promise !== null) {
          // when we cancel without a promise, we end up with a promise
          // but no reject function. If cancel is called again, we'd error.
          if (this._reject) this._reject(e);
        } else {
          // FIXME: this causes an "Uncaught promise" console message
          // if nothing ends up chaining this promise.
          this._promise = Promise.reject(e);
        } // Also emit a 'cancel' event that the app can listen for to detect cancellation
        // before calling verify()


        this.emit('cancel', e);
      }
    }
    /**
     * Begin the key verification
     *
     * @returns {Promise} Promise which resolves when the verification has
     *     completed.
     */

  }, {
    key: "verify",
    value: function verify() {
      var _this5 = this;

      if (this._promise) return this._promise;
      this._promise = new Promise(function (resolve, reject) {
        _this5._resolve = function () {
          _this5._done = true;

          _this5._endTimer();

          resolve.apply(void 0, arguments);
        };

        _this5._reject = function () {
          _this5._done = true;

          _this5._endTimer();

          reject.apply(void 0, arguments);
        };
      });

      if (this._doVerification && !this._started) {
        this._started = true;

        this._resetTimer(); // restart the timeout


        Promise.resolve(this._doVerification()).then(this.done.bind(this), this.cancel.bind(this));
      }

      return this._promise;
    }
  }, {
    key: "_verifyKeys",
    value: function () {
      var _verifyKeys2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(userId, keys, verifier) {
        var verifiedDevices, _i, _Object$entries, _Object$entries$_i, keyId, keyInfo, deviceId, device, crossSigningInfo, _i2, _verifiedDevices, _deviceId;

        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // we try to verify all the keys that we're told about, but we might
                // not know about all of them, so keep track of the keys that we know
                // about, and ignore the rest
                verifiedDevices = [];
                _i = 0, _Object$entries = Object.entries(keys);

              case 2:
                if (!(_i < _Object$entries.length)) {
                  _context.next = 23;
                  break;
                }

                _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), keyId = _Object$entries$_i[0], keyInfo = _Object$entries$_i[1];
                deviceId = keyId.split(':', 2)[1];
                device = this._baseApis.getStoredDevice(userId, deviceId);

                if (!device) {
                  _context.next = 12;
                  break;
                }

                _context.next = 9;
                return verifier(keyId, device, keyInfo);

              case 9:
                verifiedDevices.push(deviceId);
                _context.next = 20;
                break;

              case 12:
                crossSigningInfo = this._baseApis.crypto.deviceList.getStoredCrossSigningForUser(userId);

                if (!(crossSigningInfo && crossSigningInfo.getId() === deviceId)) {
                  _context.next = 19;
                  break;
                }

                _context.next = 16;
                return verifier(keyId, _deviceinfo.DeviceInfo.fromStorage({
                  keys: (0, _defineProperty2["default"])({}, keyId, deviceId)
                }, deviceId), keyInfo);

              case 16:
                verifiedDevices.push(deviceId);
                _context.next = 20;
                break;

              case 19:
                _logger.logger.warn("verification: Could not find device ".concat(deviceId, " to verify"));

              case 20:
                _i++;
                _context.next = 2;
                break;

              case 23:
                if (verifiedDevices.length) {
                  _context.next = 25;
                  break;
                }

                throw new Error("No devices could be verified");

              case 25:
                _logger.logger.info("Verification completed! Marking devices verified: ", verifiedDevices); // TODO: There should probably be a batch version of this, otherwise it's going
                // to upload each signature in a separate API call which is silly because the
                // API supports as many signatures as you like.


                _i2 = 0, _verifiedDevices = verifiedDevices;

              case 27:
                if (!(_i2 < _verifiedDevices.length)) {
                  _context.next = 34;
                  break;
                }

                _deviceId = _verifiedDevices[_i2];
                _context.next = 31;
                return this._baseApis.setDeviceVerified(userId, _deviceId);

              case 31:
                _i2++;
                _context.next = 27;
                break;

              case 34:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function _verifyKeys(_x, _x2, _x3) {
        return _verifyKeys2.apply(this, arguments);
      }

      return _verifyKeys;
    }()
  }, {
    key: "initiatedByMe",
    get: function get() {
      // if there is no start event yet,
      // we probably want to send it,
      // which happens if we initiate
      if (!this.startEvent) {
        return true;
      }

      var sender = this.startEvent.getSender();
      var content = this.startEvent.getContent();
      return sender === this._baseApis.getUserId() && content.from_device === this._baseApis.getDeviceId();
    }
  }]);
  return VerificationBase;
}(_events.EventEmitter);

exports.VerificationBase = VerificationBase;

},{"../../logger":106,"../../models/event":113,"../CrossSigning":67,"../deviceinfo":82,"./Error":92,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/wrapNativeSuper":26,"@babel/runtime/regenerator":27,"events":36}],92:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.newVerificationError = newVerificationError;
exports.errorFactory = errorFactory;
exports.errorFromEvent = errorFromEvent;
exports.newInvalidMessageError = exports.newUserMismatchError = exports.newKeyMismatchError = exports.newUnexpectedMessageError = exports.newUnknownMethodError = exports.newUnknownTransactionError = exports.newTimeoutError = exports.newUserCancelledError = void 0;

var _event = require("../../models/event");

/*
Copyright 2018 New Vector Ltd

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

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

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

/**
 * Error messages.
 *
 * @module crypto/verification/Error
 */
function newVerificationError(code, reason, extradata) {
  var content = Object.assign({}, {
    code: code,
    reason: reason
  }, extradata);
  return new _event.MatrixEvent({
    type: "m.key.verification.cancel",
    content: content
  });
}

function errorFactory(code, reason) {
  return function (extradata) {
    return newVerificationError(code, reason, extradata);
  };
}
/**
 * The verification was cancelled by the user.
 */


var newUserCancelledError = errorFactory("m.user", "Cancelled by user");
/**
 * The verification timed out.
 */

exports.newUserCancelledError = newUserCancelledError;
var newTimeoutError = errorFactory("m.timeout", "Timed out");
/**
 * The transaction is unknown.
 */

exports.newTimeoutError = newTimeoutError;
var newUnknownTransactionError = errorFactory("m.unknown_transaction", "Unknown transaction");
/**
 * An unknown method was selected.
 */

exports.newUnknownTransactionError = newUnknownTransactionError;
var newUnknownMethodError = errorFactory("m.unknown_method", "Unknown method");
/**
 * An unexpected message was sent.
 */

exports.newUnknownMethodError = newUnknownMethodError;
var newUnexpectedMessageError = errorFactory("m.unexpected_message", "Unexpected message");
/**
 * The key does not match.
 */

exports.newUnexpectedMessageError = newUnexpectedMessageError;
var newKeyMismatchError = errorFactory("m.key_mismatch", "Key mismatch");
/**
 * The user does not match.
 */

exports.newKeyMismatchError = newKeyMismatchError;
var newUserMismatchError = errorFactory("m.user_error", "User mismatch");
/**
 * An invalid message was sent.
 */

exports.newUserMismatchError = newUserMismatchError;
var newInvalidMessageError = errorFactory("m.invalid_message", "Invalid message");
exports.newInvalidMessageError = newInvalidMessageError;

function errorFromEvent(event) {
  var content = event.getContent();

  if (content) {
    var code = content.code,
        reason = content.reason;
    return {
      code: code,
      reason: reason
    };
  } else {
    return {
      code: "Unknown error",
      reason: "m.unknown"
    };
  }
}

},{"../../models/event":113}],93:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IllegalMethod = void 0;

var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _Base2 = require("./Base");

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

/**
 * @class crypto/verification/IllegalMethod/IllegalMethod
 * @extends {module:crypto/verification/Base}
 */
var IllegalMethod = /*#__PURE__*/function (_Base) {
  (0, _inherits2["default"])(IllegalMethod, _Base);

  var _super = _createSuper(IllegalMethod);

  function IllegalMethod() {
    (0, _classCallCheck2["default"])(this, IllegalMethod);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(IllegalMethod, [{
    key: "_doVerification",
    value: function () {
      var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                throw new Error("Verification is not possible with this method");

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      function _doVerification() {
        return _doVerification2.apply(this, arguments);
      }

      return _doVerification;
    }()
  }], [{
    key: "factory",
    value: function factory() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return (0, _construct2["default"])(IllegalMethod, args);
    }
  }, {
    key: "NAME",
    get: function get() {
      // Typically the name will be something else, but to complete
      // the contract we offer a default one here.
      return "org.matrix.illegal_method";
    }
  }]);
  return IllegalMethod;
}(_Base2.VerificationBase);

exports.IllegalMethod = IllegalMethod;

},{"./Base":91,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/construct":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/regenerator":27}],94:[function(require,module,exports){
(function (global,Buffer){(function (){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.QRCodeData = exports.ReciprocateQRCode = exports.SCAN_QR_CODE_METHOD = exports.SHOW_QR_CODE_METHOD = void 0;

var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _Base2 = require("./Base");

var _Error = require("./Error");

var _olmlib = require("../olmlib");

var _logger = require("../../logger");

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

var SHOW_QR_CODE_METHOD = "m.qr_code.show.v1";
exports.SHOW_QR_CODE_METHOD = SHOW_QR_CODE_METHOD;
var SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1";
/**
 * @class crypto/verification/QRCode/ReciprocateQRCode
 * @extends {module:crypto/verification/Base}
 */

exports.SCAN_QR_CODE_METHOD = SCAN_QR_CODE_METHOD;

var ReciprocateQRCode = /*#__PURE__*/function (_Base) {
  (0, _inherits2["default"])(ReciprocateQRCode, _Base);

  var _super = _createSuper(ReciprocateQRCode);

  function ReciprocateQRCode() {
    (0, _classCallCheck2["default"])(this, ReciprocateQRCode);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(ReciprocateQRCode, [{
    key: "_doVerification",
    value: function () {
      var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var _this = this;

        var qrCodeData, keys, masterKey, deviceId, _masterKey;

        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (this.startEvent) {
                  _context.next = 2;
                  break;
                }

                throw new Error("It is not currently possible to start verification" + "with this method yet.");

              case 2:
                qrCodeData = this.request.qrCodeData; // 1. check the secret

                if (!(this.startEvent.getContent()['secret'] !== qrCodeData.encodedSharedSecret)) {
                  _context.next = 5;
                  break;
                }

                throw (0, _Error.newKeyMismatchError)();

              case 5:
                _context.next = 7;
                return new Promise(function (resolve, reject) {
                  _this.reciprocateQREvent = {
                    confirm: resolve,
                    cancel: function cancel() {
                      return reject((0, _Error.newUserCancelledError)());
                    }
                  };

                  _this.emit("show_reciprocate_qr", _this.reciprocateQREvent);
                });

              case 7:
                // 3. determine key to sign / mark as trusted
                keys = {};
                _context.t0 = qrCodeData.mode;
                _context.next = _context.t0 === MODE_VERIFY_OTHER_USER ? 11 : _context.t0 === MODE_VERIFY_SELF_TRUSTED ? 14 : _context.t0 === MODE_VERIFY_SELF_UNTRUSTED ? 17 : 20;
                break;

              case 11:
                // add master key to keys to be signed, only if we're not doing self-verification
                masterKey = qrCodeData.otherUserMasterKey;
                keys["ed25519:".concat(masterKey)] = masterKey;
                return _context.abrupt("break", 20);

              case 14:
                deviceId = this.request.targetDevice.deviceId;
                keys["ed25519:".concat(deviceId)] = qrCodeData.otherDeviceKey;
                return _context.abrupt("break", 20);

              case 17:
                _masterKey = qrCodeData.myMasterKey;
                keys["ed25519:".concat(_masterKey)] = _masterKey;
                return _context.abrupt("break", 20);

              case 20:
                _context.next = 22;
                return this._verifyKeys(this.userId, keys, function (keyId, device, keyInfo) {
                  // make sure the device has the expected keys
                  var targetKey = keys[keyId];
                  if (!targetKey) throw (0, _Error.newKeyMismatchError)();

                  if (keyInfo !== targetKey) {
                    _logger.logger.error("key ID from key info does not match");

                    throw (0, _Error.newKeyMismatchError)();
                  }

                  for (var deviceKeyId in device.keys) {
                    if (!deviceKeyId.startsWith("ed25519")) continue;
                    var deviceTargetKey = keys[deviceKeyId];
                    if (!deviceTargetKey) throw (0, _Error.newKeyMismatchError)();

                    if (device.keys[deviceKeyId] !== deviceTargetKey) {
                      _logger.logger.error("master key does not match");

                      throw (0, _Error.newKeyMismatchError)();
                    }
                  }
                });

              case 22:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function _doVerification() {
        return _doVerification2.apply(this, arguments);
      }

      return _doVerification;
    }()
  }], [{
    key: "factory",
    value: function factory() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return (0, _construct2["default"])(ReciprocateQRCode, args);
    }
  }, {
    key: "NAME",
    get: function get() {
      return "m.reciprocate.v1";
    }
  }]);
  return ReciprocateQRCode;
}(_Base2.VerificationBase);

exports.ReciprocateQRCode = ReciprocateQRCode;
var CODE_VERSION = 0x02; // the version of binary QR codes we support

var BINARY_PREFIX = "MATRIX"; // ASCII, used to prefix the binary format

var MODE_VERIFY_OTHER_USER = 0x00; // Verifying someone who isn't us

var MODE_VERIFY_SELF_TRUSTED = 0x01; // We trust the master key

var MODE_VERIFY_SELF_UNTRUSTED = 0x02; // We do not trust the master key

var QRCodeData = /*#__PURE__*/function () {
  function QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer) {
    (0, _classCallCheck2["default"])(this, QRCodeData);
    this._sharedSecret = sharedSecret;
    this._mode = mode;
    this._otherUserMasterKey = otherUserMasterKey;
    this._otherDeviceKey = otherDeviceKey;
    this._myMasterKey = myMasterKey;
    this._buffer = buffer;
  }

  (0, _createClass2["default"])(QRCodeData, [{
    key: "buffer",
    get: function get() {
      return this._buffer;
    }
  }, {
    key: "mode",
    get: function get() {
      return this._mode;
    }
    /**
     * only set when mode is MODE_VERIFY_SELF_TRUSTED
     * @return {string} device key of other party at time of generating QR code
     */

  }, {
    key: "otherDeviceKey",
    get: function get() {
      return this._otherDeviceKey;
    }
    /**
     * only set when mode is MODE_VERIFY_OTHER_USER
     * @return {string} master key of other party at time of generating QR code
     */

  }, {
    key: "otherUserMasterKey",
    get: function get() {
      return this._otherUserMasterKey;
    }
    /**
     * only set when mode is MODE_VERIFY_SELF_UNTRUSTED
     * @return {string} own master key at time of generating QR code
     */

  }, {
    key: "myMasterKey",
    get: function get() {
      return this._myMasterKey;
    }
    /**
     * The unpadded base64 encoded shared secret.
     */

  }, {
    key: "encodedSharedSecret",
    get: function get() {
      return this._sharedSecret;
    }
  }], [{
    key: "create",
    value: function () {
      var _create = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(request, client) {
        var sharedSecret, mode, otherUserMasterKey, otherDeviceKey, myMasterKey, otherUserCrossSigningInfo, myUserId, myCrossSigningInfo, qrData, buffer;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                sharedSecret = QRCodeData._generateSharedSecret();
                mode = QRCodeData._determineMode(request, client);
                otherUserMasterKey = null;
                otherDeviceKey = null;
                myMasterKey = null;

                if (!(mode === MODE_VERIFY_OTHER_USER)) {
                  _context2.next = 10;
                  break;
                }

                otherUserCrossSigningInfo = client.getStoredCrossSigningForUser(request.otherUserId);
                otherUserMasterKey = otherUserCrossSigningInfo.getId("master");
                _context2.next = 17;
                break;

              case 10:
                if (!(mode === MODE_VERIFY_SELF_TRUSTED)) {
                  _context2.next = 16;
                  break;
                }

                _context2.next = 13;
                return QRCodeData._getOtherDeviceKey(request, client);

              case 13:
                otherDeviceKey = _context2.sent;
                _context2.next = 17;
                break;

              case 16:
                if (mode === MODE_VERIFY_SELF_UNTRUSTED) {
                  myUserId = client.getUserId();
                  myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);
                  myMasterKey = myCrossSigningInfo.getId("master");
                }

              case 17:
                qrData = QRCodeData._generateQrData(request, client, mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey);
                buffer = QRCodeData._generateBuffer(qrData);
                return _context2.abrupt("return", new QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer));

              case 20:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      function create(_x, _x2) {
        return _create.apply(this, arguments);
      }

      return create;
    }()
  }, {
    key: "_generateSharedSecret",
    value: function _generateSharedSecret() {
      var secretBytes = new Uint8Array(11);
      global.crypto.getRandomValues(secretBytes);
      return (0, _olmlib.encodeUnpaddedBase64)(secretBytes);
    }
  }, {
    key: "_getOtherDeviceKey",
    value: function () {
      var _getOtherDeviceKey2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(request, client) {
        var myUserId, otherDevice, otherDeviceId, device, key;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                myUserId = client.getUserId();
                otherDevice = request.targetDevice;
                otherDeviceId = otherDevice ? otherDevice.deviceId : null;
                device = client.getStoredDevice(myUserId, otherDeviceId);

                if (device) {
                  _context3.next = 6;
                  break;
                }

                throw new Error("could not find device " + otherDeviceId);

              case 6:
                key = device.getFingerprint();
                return _context3.abrupt("return", key);

              case 8:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      function _getOtherDeviceKey(_x3, _x4) {
        return _getOtherDeviceKey2.apply(this, arguments);
      }

      return _getOtherDeviceKey;
    }()
  }, {
    key: "_determineMode",
    value: function _determineMode(request, client) {
      var myUserId = client.getUserId();
      var otherUserId = request.otherUserId;
      var mode = MODE_VERIFY_OTHER_USER;

      if (myUserId === otherUserId) {
        // Mode changes depending on whether or not we trust the master cross signing key
        var myTrust = client.checkUserTrust(myUserId);

        if (myTrust.isCrossSigningVerified()) {
          mode = MODE_VERIFY_SELF_TRUSTED;
        } else {
          mode = MODE_VERIFY_SELF_UNTRUSTED;
        }
      }

      return mode;
    }
  }, {
    key: "_generateQrData",
    value: function _generateQrData(request, client, mode, encodedSharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey) {
      var myUserId = client.getUserId();
      var transactionId = request.channel.transactionId;
      var qrData = {
        prefix: BINARY_PREFIX,
        version: CODE_VERSION,
        mode: mode,
        transactionId: transactionId,
        firstKeyB64: '',
        // worked out shortly
        secondKeyB64: '',
        // worked out shortly
        secretB64: encodedSharedSecret
      };
      var myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);

      if (mode === MODE_VERIFY_OTHER_USER) {
        // First key is our master cross signing key
        qrData.firstKeyB64 = myCrossSigningInfo.getId("master"); // Second key is the other user's master cross signing key

        qrData.secondKeyB64 = otherUserMasterKey;
      } else if (mode === MODE_VERIFY_SELF_TRUSTED) {
        // First key is our master cross signing key
        qrData.firstKeyB64 = myCrossSigningInfo.getId("master");
        qrData.secondKeyB64 = otherDeviceKey;
      } else if (mode === MODE_VERIFY_SELF_UNTRUSTED) {
        // First key is our device's key
        qrData.firstKeyB64 = client.getDeviceEd25519Key(); // Second key is what we think our master cross signing key is

        qrData.secondKeyB64 = myMasterKey;
      }

      return qrData;
    }
  }, {
    key: "_generateBuffer",
    value: function _generateBuffer(qrData) {
      var buf = Buffer.alloc(0); // we'll concat our way through life

      var appendByte = function appendByte(b) {
        var tmpBuf = Buffer.from([b]);
        buf = Buffer.concat([buf, tmpBuf]);
      };

      var appendInt = function appendInt(i) {
        var tmpBuf = Buffer.alloc(2);
        tmpBuf.writeInt16BE(i, 0);
        buf = Buffer.concat([buf, tmpBuf]);
      };

      var appendStr = function appendStr(s, enc) {
        var withLengthPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
        var tmpBuf = Buffer.from(s, enc);
        if (withLengthPrefix) appendInt(tmpBuf.byteLength);
        buf = Buffer.concat([buf, tmpBuf]);
      };

      var appendEncBase64 = function appendEncBase64(b64) {
        var b = (0, _olmlib.decodeBase64)(b64);
        var tmpBuf = Buffer.from(b);
        buf = Buffer.concat([buf, tmpBuf]);
      }; // Actually build the buffer for the QR code


      appendStr(qrData.prefix, "ascii", false);
      appendByte(qrData.version);
      appendByte(qrData.mode);
      appendStr(qrData.transactionId, "utf-8");
      appendEncBase64(qrData.firstKeyB64);
      appendEncBase64(qrData.secondKeyB64);
      appendEncBase64(qrData.secretB64);
      return buf;
    }
  }]);
  return QRCodeData;
}();

exports.QRCodeData = QRCodeData;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)

},{"../../logger":106,"../olmlib":85,"./Base":91,"./Error":92,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/construct":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/regenerator":27,"buffer":34}],95:[function(require,module,exports){
(function (global){(function (){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SAS = void 0;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _Base2 = require("./Base");

var _anotherJson = _interopRequireDefault(require("another-json"));

var _Error = require("./Error");

var _logger = require("../../logger");

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var START_TYPE = "m.key.verification.start";
var EVENTS = ["m.key.verification.accept", "m.key.verification.key", "m.key.verification.mac"];
var olmutil;
var newMismatchedSASError = (0, _Error.errorFactory)("m.mismatched_sas", "Mismatched short authentication string");
var newMismatchedCommitmentError = (0, _Error.errorFactory)("m.mismatched_commitment", "Mismatched commitment");

function generateDecimalSas(sasBytes) {
  /**
   *      +--------+--------+--------+--------+--------+
   *      | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 |
   *      +--------+--------+--------+--------+--------+
   * bits: 87654321 87654321 87654321 87654321 87654321
   *       \____________/\_____________/\____________/
   *         1st number    2nd number     3rd number
   */
  return [(sasBytes[0] << 5 | sasBytes[1] >> 3) + 1000, ((sasBytes[1] & 0x7) << 10 | sasBytes[2] << 2 | sasBytes[3] >> 6) + 1000, ((sasBytes[3] & 0x3f) << 7 | sasBytes[4] >> 1) + 1000];
}

var emojiMapping = [["🐶", "dog"], //  0
["🐱", "cat"], //  1
["🦁", "lion"], //  2
["🐎", "horse"], //  3
["🦄", "unicorn"], //  4
["🐷", "pig"], //  5
["🐘", "elephant"], //  6
["🐰", "rabbit"], //  7
["🐼", "panda"], //  8
["🐓", "rooster"], //  9
["🐧", "penguin"], // 10
["🐢", "turtle"], // 11
["🐟", "fish"], // 12
["🐙", "octopus"], // 13
["🦋", "butterfly"], // 14
["🌷", "flower"], // 15
["🌳", "tree"], // 16
["🌵", "cactus"], // 17
["🍄", "mushroom"], // 18
["🌏", "globe"], // 19
["🌙", "moon"], // 20
["☁️", "cloud"], // 21
["🔥", "fire"], // 22
["🍌", "banana"], // 23
["🍎", "apple"], // 24
["🍓", "strawberry"], // 25
["🌽", "corn"], // 26
["🍕", "pizza"], // 27
["🎂", "cake"], // 28
["❤️", "heart"], // 29
["🙂", "smiley"], // 30
["🤖", "robot"], // 31
["🎩", "hat"], // 32
["👓", "glasses"], // 33
["🔧", "spanner"], // 34
["🎅", "santa"], // 35
["👍", "thumbs up"], // 36
["☂️", "umbrella"], // 37
["⌛", "hourglass"], // 38
["⏰", "clock"], // 39
["🎁", "gift"], // 40
["💡", "light bulb"], // 41
["📕", "book"], // 42
["✏️", "pencil"], // 43
["📎", "paperclip"], // 44
["✂️", "scissors"], // 45
["🔒", "lock"], // 46
["🔑", "key"], // 47
["🔨", "hammer"], // 48
["☎️", "telephone"], // 49
["🏁", "flag"], // 50
["🚂", "train"], // 51
["🚲", "bicycle"], // 52
["✈️", "aeroplane"], // 53
["🚀", "rocket"], // 54
["🏆", "trophy"], // 55
["⚽", "ball"], // 56
["🎸", "guitar"], // 57
["🎺", "trumpet"], // 58
["🔔", "bell"], // 59
["⚓️", "anchor"], // 60
["🎧", "headphones"], // 61
["📁", "folder"], // 62
["📌", "pin"] // 63
];

function generateEmojiSas(sasBytes) {
  var emojis = [// just like base64 encoding
  sasBytes[0] >> 2, (sasBytes[0] & 0x3) << 4 | sasBytes[1] >> 4, (sasBytes[1] & 0xf) << 2 | sasBytes[2] >> 6, sasBytes[2] & 0x3f, sasBytes[3] >> 2, (sasBytes[3] & 0x3) << 4 | sasBytes[4] >> 4, (sasBytes[4] & 0xf) << 2 | sasBytes[5] >> 6];
  return emojis.map(function (num) {
    return emojiMapping[num];
  });
}

var sasGenerators = {
  decimal: generateDecimalSas,
  emoji: generateEmojiSas
};

function generateSas(sasBytes, methods) {
  var sas = {};

  var _iterator = _createForOfIteratorHelper(methods),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var method = _step.value;

      if (method in sasGenerators) {
        sas[method] = sasGenerators[method](sasBytes);
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  return sas;
}

var macMethods = {
  "hkdf-hmac-sha256": "calculate_mac",
  "hmac-sha256": "calculate_mac_long_kdf"
};

function calculateMAC(olmSAS, method) {
  return function () {
    var macFunction = olmSAS[macMethods[method]];

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var mac = macFunction.apply(olmSAS, args);

    _logger.logger.log("SAS calculateMAC:", method, args, mac);

    return mac;
  };
}

var calculateKeyAgreement = {
  "curve25519-hkdf-sha256": function curve25519HkdfSha256(sas, olmSAS, bytes) {
    var ourInfo = "".concat(sas._baseApis.getUserId(), "|").concat(sas._baseApis.deviceId, "|") + "".concat(sas.ourSASPubKey, "|");
    var theirInfo = "".concat(sas.userId, "|").concat(sas.deviceId, "|").concat(sas.theirSASPubKey, "|");
    var sasInfo = "MATRIX_KEY_VERIFICATION_SAS|" + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + sas._channel.transactionId;
    return olmSAS.generate_bytes(sasInfo, bytes);
  },
  "curve25519": function curve25519(sas, olmSAS, bytes) {
    var ourInfo = "".concat(sas._baseApis.getUserId()).concat(sas._baseApis.deviceId);
    var theirInfo = "".concat(sas.userId).concat(sas.deviceId);
    var sasInfo = "MATRIX_KEY_VERIFICATION_SAS" + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + sas._channel.transactionId;
    return olmSAS.generate_bytes(sasInfo, bytes);
  }
};
/* lists of algorithms/methods that are supported.  The key agreement, hashes,
 * and MAC lists should be sorted in order of preference (most preferred
 * first).
 */

var KEY_AGREEMENT_LIST = ["curve25519-hkdf-sha256", "curve25519"];
var HASHES_LIST = ["sha256"];
var MAC_LIST = ["hkdf-hmac-sha256", "hmac-sha256"];
var SAS_LIST = Object.keys(sasGenerators);
var KEY_AGREEMENT_SET = new Set(KEY_AGREEMENT_LIST);
var HASHES_SET = new Set(HASHES_LIST);
var MAC_SET = new Set(MAC_LIST);
var SAS_SET = new Set(SAS_LIST);

function intersection(anArray, aSet) {
  return anArray instanceof Array ? anArray.filter(function (x) {
    return aSet.has(x);
  }) : [];
}
/**
 * @alias module:crypto/verification/SAS
 * @extends {module:crypto/verification/Base}
 */


var SAS = /*#__PURE__*/function (_Base) {
  (0, _inherits2["default"])(SAS, _Base);

  var _super = _createSuper(SAS);

  function SAS() {
    (0, _classCallCheck2["default"])(this, SAS);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(SAS, [{
    key: "_doVerification",
    value: function () {
      var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var retry;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return global.Olm.init();

              case 2:
                olmutil = olmutil || new global.Olm.Utility(); // make sure user's keys are downloaded

                _context.next = 5;
                return this._baseApis.downloadKeys([this.userId]);

              case 5:
                retry = false;

              case 6:
                _context.prev = 6;

                if (!this.initiatedByMe) {
                  _context.next = 13;
                  break;
                }

                _context.next = 10;
                return this._doSendVerification();

              case 10:
                return _context.abrupt("return", _context.sent);

              case 13:
                _context.next = 15;
                return this._doRespondVerification();

              case 15:
                return _context.abrupt("return", _context.sent);

              case 16:
                _context.next = 26;
                break;

              case 18:
                _context.prev = 18;
                _context.t0 = _context["catch"](6);

                if (!(_context.t0 instanceof _Base2.SwitchStartEventError)) {
                  _context.next = 25;
                  break;
                }

                // this changes what initiatedByMe returns
                this.startEvent = _context.t0.startEvent;
                retry = true;
                _context.next = 26;
                break;

              case 25:
                throw _context.t0;

              case 26:
                if (retry) {
                  _context.next = 6;
                  break;
                }

              case 27:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[6, 18]]);
      }));

      function _doVerification() {
        return _doVerification2.apply(this, arguments);
      }

      return _doVerification;
    }()
  }, {
    key: "canSwitchStartEvent",
    value: function canSwitchStartEvent(event) {
      if (event.getType() !== START_TYPE) {
        return false;
      }

      var content = event.getContent();
      return content && content.method === SAS.NAME && this._waitingForAccept;
    }
  }, {
    key: "_sendStart",
    value: function () {
      var _sendStart2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
        var startContent;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                startContent = this._channel.completeContent(START_TYPE, {
                  method: SAS.NAME,
                  from_device: this._baseApis.deviceId,
                  key_agreement_protocols: KEY_AGREEMENT_LIST,
                  hashes: HASHES_LIST,
                  message_authentication_codes: MAC_LIST,
                  // FIXME: allow app to specify what SAS methods can be used
                  short_authentication_string: SAS_LIST
                });
                _context2.next = 3;
                return this._channel.sendCompleted(START_TYPE, startContent);

              case 3:
                return _context2.abrupt("return", startContent);

              case 4:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function _sendStart() {
        return _sendStart2.apply(this, arguments);
      }

      return _sendStart;
    }()
  }, {
    key: "_doSendVerification",
    value: function () {
      var _doSendVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
        var _this = this;

        var startContent, e, content, sasMethods, keyAgreement, macMethod, hashCommitment, olmSAS, commitmentStr, sasBytes, verifySAS, _yield$Promise$all, _yield$Promise$all2;

        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                this._waitingForAccept = true;

                if (!this.startEvent) {
                  _context4.next = 5;
                  break;
                }

                startContent = this._channel.completedContentFromEvent(this.startEvent);
                _context4.next = 8;
                break;

              case 5:
                _context4.next = 7;
                return this._sendStart();

              case 7:
                startContent = _context4.sent;

              case 8:
                if (this.initiatedByMe) {
                  _context4.next = 10;
                  break;
                }

                throw new _Base2.SwitchStartEventError(this.startEvent);

              case 10:
                _context4.prev = 10;
                _context4.next = 13;
                return this._waitForEvent("m.key.verification.accept");

              case 13:
                e = _context4.sent;

              case 14:
                _context4.prev = 14;
                this._waitingForAccept = false;
                return _context4.finish(14);

              case 17:
                content = e.getContent();
                sasMethods = intersection(content.short_authentication_string, SAS_SET);

                if (KEY_AGREEMENT_SET.has(content.key_agreement_protocol) && HASHES_SET.has(content.hash) && MAC_SET.has(content.message_authentication_code) && sasMethods.length) {
                  _context4.next = 21;
                  break;
                }

                throw (0, _Error.newUnknownMethodError)();

              case 21:
                if (!(typeof content.commitment !== "string")) {
                  _context4.next = 23;
                  break;
                }

                throw (0, _Error.newInvalidMessageError)();

              case 23:
                keyAgreement = content.key_agreement_protocol;
                macMethod = content.message_authentication_code;
                hashCommitment = content.commitment;
                olmSAS = new global.Olm.SAS();
                _context4.prev = 27;
                this.ourSASPubKey = olmSAS.get_pubkey();
                _context4.next = 31;
                return this._send("m.key.verification.key", {
                  key: this.ourSASPubKey
                });

              case 31:
                _context4.next = 33;
                return this._waitForEvent("m.key.verification.key");

              case 33:
                e = _context4.sent;
                // FIXME: make sure event is properly formed
                content = e.getContent();
                commitmentStr = content.key + _anotherJson["default"].stringify(startContent); // TODO: use selected hash function (when we support multiple)

                if (!(olmutil.sha256(commitmentStr) !== hashCommitment)) {
                  _context4.next = 38;
                  break;
                }

                throw newMismatchedCommitmentError();

              case 38:
                this.theirSASPubKey = content.key;
                olmSAS.set_their_key(content.key);
                sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);
                verifySAS = new Promise(function (resolve, reject) {
                  _this.sasEvent = {
                    sas: generateSas(sasBytes, sasMethods),
                    confirm: function () {
                      var _confirm = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
                        return _regenerator["default"].wrap(function _callee3$(_context3) {
                          while (1) {
                            switch (_context3.prev = _context3.next) {
                              case 0:
                                _context3.prev = 0;
                                _context3.next = 3;
                                return _this._sendMAC(olmSAS, macMethod);

                              case 3:
                                resolve();
                                _context3.next = 9;
                                break;

                              case 6:
                                _context3.prev = 6;
                                _context3.t0 = _context3["catch"](0);
                                reject(_context3.t0);

                              case 9:
                              case "end":
                                return _context3.stop();
                            }
                          }
                        }, _callee3, null, [[0, 6]]);
                      }));

                      function confirm() {
                        return _confirm.apply(this, arguments);
                      }

                      return confirm;
                    }(),
                    cancel: function cancel() {
                      return reject((0, _Error.newUserCancelledError)());
                    },
                    mismatch: function mismatch() {
                      return reject(newMismatchedSASError());
                    }
                  };

                  _this.emit("show_sas", _this.sasEvent);
                });
                _context4.next = 44;
                return Promise.all([this._waitForEvent("m.key.verification.mac").then(function (e) {
                  // we don't expect any more messages from the other
                  // party, and they may send a m.key.verification.done
                  // when they're done on their end
                  _this._expectedEvent = "m.key.verification.done";
                  return e;
                }), verifySAS]);

              case 44:
                _yield$Promise$all = _context4.sent;
                _yield$Promise$all2 = (0, _slicedToArray2["default"])(_yield$Promise$all, 1);
                e = _yield$Promise$all2[0];
                content = e.getContent();
                _context4.next = 50;
                return this._checkMAC(olmSAS, content, macMethod);

              case 50:
                _context4.prev = 50;
                olmSAS.free();
                return _context4.finish(50);

              case 53:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this, [[10,, 14, 17], [27,, 50, 53]]);
      }));

      function _doSendVerification() {
        return _doSendVerification2.apply(this, arguments);
      }

      return _doSendVerification;
    }()
  }, {
    key: "_doRespondVerification",
    value: function () {
      var _doRespondVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
        var _this2 = this;

        var content, keyAgreement, hashMethod, macMethod, sasMethods, olmSAS, commitmentStr, e, sasBytes, verifySAS, _yield$Promise$all3, _yield$Promise$all4;

        return _regenerator["default"].wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                // as m.related_to is not included in the encrypted content in e2e rooms,
                // we need to make sure it is added
                content = this._channel.completedContentFromEvent(this.startEvent); // Note: we intersect using our pre-made lists, rather than the sets,
                // so that the result will be in our order of preference.  Then
                // fetching the first element from the array will give our preferred
                // method out of the ones offered by the other party.

                keyAgreement = intersection(KEY_AGREEMENT_LIST, new Set(content.key_agreement_protocols))[0];
                hashMethod = intersection(HASHES_LIST, new Set(content.hashes))[0];
                macMethod = intersection(MAC_LIST, new Set(content.message_authentication_codes))[0]; // FIXME: allow app to specify what SAS methods can be used

                sasMethods = intersection(content.short_authentication_string, SAS_SET);

                if (keyAgreement !== undefined && hashMethod !== undefined && macMethod !== undefined && sasMethods.length) {
                  _context6.next = 7;
                  break;
                }

                throw (0, _Error.newUnknownMethodError)();

              case 7:
                olmSAS = new global.Olm.SAS();
                _context6.prev = 8;
                commitmentStr = olmSAS.get_pubkey() + _anotherJson["default"].stringify(content);
                _context6.next = 12;
                return this._send("m.key.verification.accept", {
                  key_agreement_protocol: keyAgreement,
                  hash: hashMethod,
                  message_authentication_code: macMethod,
                  short_authentication_string: sasMethods,
                  // TODO: use selected hash function (when we support multiple)
                  commitment: olmutil.sha256(commitmentStr)
                });

              case 12:
                _context6.next = 14;
                return this._waitForEvent("m.key.verification.key");

              case 14:
                e = _context6.sent;
                // FIXME: make sure event is properly formed
                content = e.getContent();
                this.theirSASPubKey = content.key;
                olmSAS.set_their_key(content.key);
                this.ourSASPubKey = olmSAS.get_pubkey();
                _context6.next = 21;
                return this._send("m.key.verification.key", {
                  key: this.ourSASPubKey
                });

              case 21:
                sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);
                verifySAS = new Promise(function (resolve, reject) {
                  _this2.sasEvent = {
                    sas: generateSas(sasBytes, sasMethods),
                    confirm: function () {
                      var _confirm2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
                        return _regenerator["default"].wrap(function _callee5$(_context5) {
                          while (1) {
                            switch (_context5.prev = _context5.next) {
                              case 0:
                                _context5.prev = 0;
                                _context5.next = 3;
                                return _this2._sendMAC(olmSAS, macMethod);

                              case 3:
                                resolve();
                                _context5.next = 9;
                                break;

                              case 6:
                                _context5.prev = 6;
                                _context5.t0 = _context5["catch"](0);
                                reject(_context5.t0);

                              case 9:
                              case "end":
                                return _context5.stop();
                            }
                          }
                        }, _callee5, null, [[0, 6]]);
                      }));

                      function confirm() {
                        return _confirm2.apply(this, arguments);
                      }

                      return confirm;
                    }(),
                    cancel: function cancel() {
                      return reject((0, _Error.newUserCancelledError)());
                    },
                    mismatch: function mismatch() {
                      return reject(newMismatchedSASError());
                    }
                  };

                  _this2.emit("show_sas", _this2.sasEvent);
                });
                _context6.next = 25;
                return Promise.all([this._waitForEvent("m.key.verification.mac").then(function (e) {
                  // we don't expect any more messages from the other
                  // party, and they may send a m.key.verification.done
                  // when they're done on their end
                  _this2._expectedEvent = "m.key.verification.done";
                  return e;
                }), verifySAS]);

              case 25:
                _yield$Promise$all3 = _context6.sent;
                _yield$Promise$all4 = (0, _slicedToArray2["default"])(_yield$Promise$all3, 1);
                e = _yield$Promise$all4[0];
                content = e.getContent();
                _context6.next = 31;
                return this._checkMAC(olmSAS, content, macMethod);

              case 31:
                _context6.prev = 31;
                olmSAS.free();
                return _context6.finish(31);

              case 34:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this, [[8,, 31, 34]]);
      }));

      function _doRespondVerification() {
        return _doRespondVerification2.apply(this, arguments);
      }

      return _doRespondVerification;
    }()
  }, {
    key: "_sendMAC",
    value: function _sendMAC(olmSAS, method) {
      var mac = {};
      var keyList = [];

      var baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + this._baseApis.getUserId() + this._baseApis.deviceId + this.userId + this.deviceId + this._channel.transactionId;

      var deviceKeyId = "ed25519:".concat(this._baseApis.deviceId);
      mac[deviceKeyId] = calculateMAC(olmSAS, method)(this._baseApis.getDeviceEd25519Key(), baseInfo + deviceKeyId);
      keyList.push(deviceKeyId);

      var crossSigningId = this._baseApis.getCrossSigningId();

      if (crossSigningId) {
        var crossSigningKeyId = "ed25519:".concat(crossSigningId);
        mac[crossSigningKeyId] = calculateMAC(olmSAS, method)(crossSigningId, baseInfo + crossSigningKeyId);
        keyList.push(crossSigningKeyId);
      }

      var keys = calculateMAC(olmSAS, method)(keyList.sort().join(","), baseInfo + "KEY_IDS");
      return this._send("m.key.verification.mac", {
        mac: mac,
        keys: keys
      });
    }
  }, {
    key: "_checkMAC",
    value: function () {
      var _checkMAC2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(olmSAS, content, method) {
        var baseInfo;
        return _regenerator["default"].wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + this.userId + this.deviceId + this._baseApis.getUserId() + this._baseApis.deviceId + this._channel.transactionId;

                if (!(content.keys !== calculateMAC(olmSAS, method)(Object.keys(content.mac).sort().join(","), baseInfo + "KEY_IDS"))) {
                  _context7.next = 3;
                  break;
                }

                throw (0, _Error.newKeyMismatchError)();

              case 3:
                _context7.next = 5;
                return this._verifyKeys(this.userId, content.mac, function (keyId, device, keyInfo) {
                  if (keyInfo !== calculateMAC(olmSAS, method)(device.keys[keyId], baseInfo + keyId)) {
                    throw (0, _Error.newKeyMismatchError)();
                  }
                });

              case 5:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function _checkMAC(_x, _x2, _x3) {
        return _checkMAC2.apply(this, arguments);
      }

      return _checkMAC;
    }()
  }, {
    key: "events",
    get: function get() {
      return EVENTS;
    }
  }], [{
    key: "NAME",
    get: function get() {
      return "m.sas.v1";
    }
  }]);
  return SAS;
}(_Base2.VerificationBase);

exports.SAS = SAS;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../../logger":106,"./Base":91,"./Error":92,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"another-json":28}],96:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InRoomRequests = exports.InRoomChannel = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _VerificationRequest = require("./VerificationRequest");

var _logger = require("../../../logger");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var MESSAGE_TYPE = "m.room.message";
var M_REFERENCE = "m.reference";
var M_RELATES_TO = "m.relates_to";
/**
 * A key verification channel that sends verification events in the timeline of a room.
 * Uses the event id of the initial m.key.verification.request event as a transaction id.
 */

var InRoomChannel = /*#__PURE__*/function () {
  /**
   * @param {MatrixClient} client the matrix client, to send messages with and get current user & device from.
   * @param {string} roomId id of the room where verification events should be posted in, should be a DM with the given user.
   * @param {string} userId id of user that the verification request is directed at, should be present in the room.
   */
  function InRoomChannel(client, roomId) {
    var userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    (0, _classCallCheck2["default"])(this, InRoomChannel);
    this._client = client;
    this._roomId = roomId;
    this.userId = userId;
    this._requestEventId = null;
  }

  (0, _createClass2["default"])(InRoomChannel, [{
    key: "getTimestamp",

    /**
     * @param {MatrixEvent} event the event to get the timestamp of
     * @return {number} the timestamp when the event was sent
     */
    value: function getTimestamp(event) {
      return event.getTs();
    }
    /**
     * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel
     * @param {string} type the event type to check
     * @returns {bool} boolean flag
     */

  }, {
    key: "handleEvent",

    /**
     * Changes the state of the channel, request, and verifier in response to a key verification event.
     * @param {MatrixEvent} event to handle
     * @param {VerificationRequest} request the request to forward handling to
     * @param {bool} isLiveEvent whether this is an even received through sync or not
     * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.
     */
    value: function () {
      var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(event, request, isLiveEvent) {
        var type, userId, ownUserId, sender, isRemoteEcho, isSentByUs;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!request.hasEventId(event.getId())) {
                  _context.next = 2;
                  break;
                }

                return _context.abrupt("return");

              case 2:
                type = InRoomChannel.getEventType(event); // do validations that need state (roomId, userId),
                // ignore if invalid

                if (!(event.getRoomId() !== this._roomId)) {
                  _context.next = 5;
                  break;
                }

                return _context.abrupt("return");

              case 5:
                // set userId if not set already
                if (this.userId === null) {
                  userId = InRoomChannel.getOtherPartyUserId(event, this._client);

                  if (userId) {
                    this.userId = userId;
                  }
                } // ignore events not sent by us or the other party


                ownUserId = this._client.getUserId();
                sender = event.getSender();

                if (!(this.userId !== null)) {
                  _context.next = 12;
                  break;
                }

                if (!(sender !== ownUserId && sender !== this.userId)) {
                  _context.next = 12;
                  break;
                }

                _logger.logger.log("InRoomChannel: ignoring verification event from " + "non-participating sender ".concat(sender));

                return _context.abrupt("return");

              case 12:
                if (this._requestEventId === null) {
                  this._requestEventId = InRoomChannel.getTransactionId(event);
                }

                isRemoteEcho = !!event.getUnsigned().transaction_id;
                isSentByUs = event.getSender() === this._client.getUserId();
                _context.next = 17;
                return request.handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs);

              case 17:
                return _context.abrupt("return", _context.sent);

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function handleEvent(_x, _x2, _x3) {
        return _handleEvent.apply(this, arguments);
      }

      return handleEvent;
    }()
    /**
     * Adds the transaction id (relation) back to a received event
     * so it has the same format as returned by `completeContent` before sending.
     * The relation can not appear on the event content because of encryption,
     * relations are excluded from encryption.
     * @param {MatrixEvent} event the received event
     * @returns {Object} the content object with the relation added again
     */

  }, {
    key: "completedContentFromEvent",
    value: function completedContentFromEvent(event) {
      // ensure m.related_to is included in e2ee rooms
      // as the field is excluded from encryption
      var content = Object.assign({}, event.getContent());
      content[M_RELATES_TO] = event.getRelation();
      return content;
    }
    /**
     * Add all the fields to content needed for sending it over this channel.
     * This is public so verification methods (SAS uses this) can get the exact
     * content that will be sent independent of the used channel,
     * as they need to calculate the hash of it.
     * @param {string} type the event type
     * @param {object} content the (incomplete) content
     * @returns {object} the complete content, as it will be sent.
     */

  }, {
    key: "completeContent",
    value: function completeContent(type, content) {
      content = Object.assign({}, content);

      if (type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE) {
        content.from_device = this._client.getDeviceId();
      }

      if (type === _VerificationRequest.REQUEST_TYPE) {
        // type is mapped to m.room.message in the send method
        content = {
          body: this._client.getUserId() + " is requesting to verify " + "your key, but your client does not support in-chat key " + "verification.  You will need to use legacy key " + "verification to verify keys.",
          msgtype: _VerificationRequest.REQUEST_TYPE,
          to: this.userId,
          from_device: content.from_device,
          methods: content.methods
        };
      } else {
        content[M_RELATES_TO] = {
          rel_type: M_REFERENCE,
          event_id: this.transactionId
        };
      }

      return content;
    }
    /**
     * Send an event over the channel with the content not having gone through `completeContent`.
     * @param {string} type the event type
     * @param {object} uncompletedContent the (incomplete) content
     * @returns {Promise} the promise of the request
     */

  }, {
    key: "send",
    value: function send(type, uncompletedContent) {
      var content = this.completeContent(type, uncompletedContent);
      return this.sendCompleted(type, content);
    }
    /**
     * Send an event over the channel with the content having gone through `completeContent` already.
     * @param {string} type the event type
     * @param {object} content
     * @returns {Promise} the promise of the request
     */

  }, {
    key: "sendCompleted",
    value: function () {
      var _sendCompleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(type, content) {
        var sendType, response;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                sendType = type;

                if (type === _VerificationRequest.REQUEST_TYPE) {
                  sendType = MESSAGE_TYPE;
                }

                _context2.next = 4;
                return this._client.sendEvent(this._roomId, sendType, content);

              case 4:
                response = _context2.sent;

                if (type === _VerificationRequest.REQUEST_TYPE) {
                  this._requestEventId = response.event_id;
                }

              case 6:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function sendCompleted(_x4, _x5) {
        return _sendCompleted.apply(this, arguments);
      }

      return sendCompleted;
    }()
  }, {
    key: "receiveStartFromOtherDevices",
    get: function get() {
      return true;
    }
  }, {
    key: "roomId",
    get: function get() {
      return this._roomId;
    }
    /** The transaction id generated/used by this verification channel */

  }, {
    key: "transactionId",
    get: function get() {
      return this._requestEventId;
    }
  }], [{
    key: "getOtherPartyUserId",
    value: function getOtherPartyUserId(event, client) {
      var type = InRoomChannel.getEventType(event);

      if (type !== _VerificationRequest.REQUEST_TYPE) {
        return;
      }

      var ownUserId = client.getUserId();
      var sender = event.getSender();
      var content = event.getContent();
      var receiver = content.to;

      if (sender === ownUserId) {
        return receiver;
      } else if (receiver === ownUserId) {
        return sender;
      }
    }
  }, {
    key: "canCreateRequest",
    value: function canCreateRequest(type) {
      return type === _VerificationRequest.REQUEST_TYPE;
    }
    /**
     * Extract the transaction id used by a given key verification event, if any
     * @param {MatrixEvent} event the event
     * @returns {string} the transaction id
     */

  }, {
    key: "getTransactionId",
    value: function getTransactionId(event) {
      if (InRoomChannel.getEventType(event) === _VerificationRequest.REQUEST_TYPE) {
        return event.getId();
      } else {
        var relation = event.getRelation();

        if (relation && relation.rel_type === M_REFERENCE) {
          return relation.event_id;
        }
      }
    }
    /**
     * Checks whether this event is a well-formed key verification event.
     * This only does checks that don't rely on the current state of a potentially already channel
     * so we can prevent channels being created by invalid events.
     * `handleEvent` can do more checks and choose to ignore invalid events.
     * @param {MatrixEvent} event the event to validate
     * @param {MatrixClient} client the client to get the current user and device id from
     * @returns {bool} whether the event is valid and should be passed to handleEvent
     */

  }, {
    key: "validateEvent",
    value: function validateEvent(event, client) {
      var txnId = InRoomChannel.getTransactionId(event);

      if (typeof txnId !== "string" || txnId.length === 0) {
        return false;
      }

      var type = InRoomChannel.getEventType(event);
      var content = event.getContent(); // from here on we're fairly sure that this is supposed to be
      // part of a verification request, so be noisy when rejecting something

      if (type === _VerificationRequest.REQUEST_TYPE) {
        if (!content || typeof content.to !== "string" || !content.to.length) {
          _logger.logger.log("InRoomChannel: validateEvent: " + "no valid to " + (content && content.to));

          return false;
        } // ignore requests that are not direct to or sent by the syncing user


        if (!InRoomChannel.getOtherPartyUserId(event, client)) {
          _logger.logger.log("InRoomChannel: validateEvent: " + "not directed to or sent by me: ".concat(event.getSender()) + ", ".concat(content && content.to));

          return false;
        }
      }

      return _VerificationRequest.VerificationRequest.validateEvent(type, event, client);
    }
    /**
     * As m.key.verification.request events are as m.room.message events with the InRoomChannel
     * to have a fallback message in non-supporting clients, we map the real event type
     * to the symbolic one to keep things in unison with ToDeviceChannel
     * @param {MatrixEvent} event the event to get the type of
     * @returns {string} the "symbolic" event type
     */

  }, {
    key: "getEventType",
    value: function getEventType(event) {
      var type = event.getType();

      if (type === MESSAGE_TYPE) {
        var content = event.getContent();

        if (content) {
          var msgtype = content.msgtype;

          if (msgtype === _VerificationRequest.REQUEST_TYPE) {
            return _VerificationRequest.REQUEST_TYPE;
          }
        }
      }

      if (type && type !== _VerificationRequest.REQUEST_TYPE) {
        return type;
      } else {
        return "";
      }
    }
  }]);
  return InRoomChannel;
}();

exports.InRoomChannel = InRoomChannel;

var InRoomRequests = /*#__PURE__*/function () {
  function InRoomRequests() {
    (0, _classCallCheck2["default"])(this, InRoomRequests);
    this._requestsByRoomId = new Map();
  }

  (0, _createClass2["default"])(InRoomRequests, [{
    key: "getRequest",
    value: function getRequest(event) {
      var roomId = event.getRoomId();
      var txnId = InRoomChannel.getTransactionId(event);
      return this._getRequestByTxnId(roomId, txnId);
    }
  }, {
    key: "getRequestByChannel",
    value: function getRequestByChannel(channel) {
      return this._getRequestByTxnId(channel.roomId, channel.transactionId);
    }
  }, {
    key: "_getRequestByTxnId",
    value: function _getRequestByTxnId(roomId, txnId) {
      var requestsByTxnId = this._requestsByRoomId.get(roomId);

      if (requestsByTxnId) {
        return requestsByTxnId.get(txnId);
      }
    }
  }, {
    key: "setRequest",
    value: function setRequest(event, request) {
      this._setRequest(event.getRoomId(), InRoomChannel.getTransactionId(event), request);
    }
  }, {
    key: "setRequestByChannel",
    value: function setRequestByChannel(channel, request) {
      this._setRequest(channel.roomId, channel.transactionId, request);
    }
  }, {
    key: "_setRequest",
    value: function _setRequest(roomId, txnId, request) {
      var requestsByTxnId = this._requestsByRoomId.get(roomId);

      if (!requestsByTxnId) {
        requestsByTxnId = new Map();

        this._requestsByRoomId.set(roomId, requestsByTxnId);
      }

      requestsByTxnId.set(txnId, request);
    }
  }, {
    key: "removeRequest",
    value: function removeRequest(event) {
      var roomId = event.getRoomId();

      var requestsByTxnId = this._requestsByRoomId.get(roomId);

      if (requestsByTxnId) {
        requestsByTxnId["delete"](InRoomChannel.getTransactionId(event));

        if (requestsByTxnId.size === 0) {
          this._requestsByRoomId["delete"](roomId);
        }
      }
    }
  }, {
    key: "findRequestInProgress",
    value: function findRequestInProgress(roomId) {
      var requestsByTxnId = this._requestsByRoomId.get(roomId);

      if (requestsByTxnId) {
        var _iterator = _createForOfIteratorHelper(requestsByTxnId.values()),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var request = _step.value;

            if (request.pending) {
              return request;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
    }
  }]);
  return InRoomRequests;
}();

exports.InRoomRequests = InRoomRequests;

},{"../../../logger":106,"./VerificationRequest":98,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27}],97:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ToDeviceRequests = exports.ToDeviceChannel = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _randomstring = require("../../../randomstring");

var _logger = require("../../../logger");

var _VerificationRequest = require("./VerificationRequest");

var _Error = require("../Error");

var _event = require("../../../models/event");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

/**
 * A key verification channel that sends verification events over to_device messages.
 * Generates its own transaction ids.
 */
var ToDeviceChannel = /*#__PURE__*/function () {
  // userId and devices of user we're about to verify
  function ToDeviceChannel(client, userId, devices) {
    var transactionId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    var deviceId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
    (0, _classCallCheck2["default"])(this, ToDeviceChannel);
    this._client = client;
    this.userId = userId;
    this._devices = devices;
    this.transactionId = transactionId;
    this._deviceId = deviceId;
  }

  (0, _createClass2["default"])(ToDeviceChannel, [{
    key: "isToDevices",
    value: function isToDevices(devices) {
      var _this = this;

      if (devices.length === this._devices.length) {
        var _iterator = _createForOfIteratorHelper(devices),
            _step;

        try {
          var _loop = function _loop() {
            var device = _step.value;

            var d = _this._devices.find(function (d) {
              return d.deviceId === device.deviceId;
            });

            if (!d) {
              return {
                v: false
              };
            }
          };

          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var _ret = _loop();

            if ((0, _typeof2["default"])(_ret) === "object") return _ret.v;
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }

        return true;
      } else {
        return false;
      }
    }
  }, {
    key: "getTimestamp",

    /**
     * @param {MatrixEvent} event the event to get the timestamp of
     * @return {number} the timestamp when the event was sent
     */
    value: function getTimestamp(event) {
      var content = event.getContent();
      return content && content.timestamp;
    }
    /**
     * Changes the state of the channel, request, and verifier in response to a key verification event.
     * @param {MatrixEvent} event to handle
     * @param {VerificationRequest} request the request to forward handling to
     * @param {bool} isLiveEvent whether this is an even received through sync or not
     * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.
     */

  }, {
    key: "handleEvent",
    value: function () {
      var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(event, request, isLiveEvent) {
        var _this2 = this;

        var type, content, deviceId, cancelContent, wasStarted, isStarted, isAcceptingEvent, nonChosenDevices, message;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                type = event.getType();
                content = event.getContent();

                if (!(type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE)) {
                  _context.next = 9;
                  break;
                }

                if (!this.transactionId) {
                  this.transactionId = content.transaction_id;
                }

                deviceId = content.from_device; // adopt deviceId if not set before and valid

                if (!this._deviceId && this._devices.includes(deviceId)) {
                  this._deviceId = deviceId;
                } // if no device id or different from addopted one, cancel with sender


                if (!(!this._deviceId || this._deviceId !== deviceId)) {
                  _context.next = 9;
                  break;
                }

                // also check that message came from the device we sent the request to earlier on
                // and do send a cancel message to that device
                // (but don't cancel the request for the device we should be talking to)
                cancelContent = this.completeContent((0, _Error.errorFromEvent)((0, _Error.newUnexpectedMessageError)()));
                return _context.abrupt("return", this._sendToDevices(_VerificationRequest.CANCEL_TYPE, cancelContent, [deviceId]));

              case 9:
                wasStarted = request.phase === _VerificationRequest.PHASE_STARTED || request.phase === _VerificationRequest.PHASE_READY;
                _context.next = 12;
                return request.handleEvent(event.getType(), event, isLiveEvent, false, false);

              case 12:
                isStarted = request.phase === _VerificationRequest.PHASE_STARTED || request.phase === _VerificationRequest.PHASE_READY;
                isAcceptingEvent = type === _VerificationRequest.START_TYPE || type === _VerificationRequest.READY_TYPE; // the request has picked a ready or start event, tell the other devices about it

                if (!(isAcceptingEvent && !wasStarted && isStarted && this._deviceId)) {
                  _context.next = 20;
                  break;
                }

                nonChosenDevices = this._devices.filter(function (d) {
                  return d !== _this2._deviceId && d !== _this2._client.getDeviceId();
                });

                if (!nonChosenDevices.length) {
                  _context.next = 20;
                  break;
                }

                message = this.completeContent({
                  code: "m.accepted",
                  reason: "Verification request accepted by another device"
                });
                _context.next = 20;
                return this._sendToDevices(_VerificationRequest.CANCEL_TYPE, message, nonChosenDevices);

              case 20:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function handleEvent(_x, _x2, _x3) {
        return _handleEvent.apply(this, arguments);
      }

      return handleEvent;
    }()
    /**
     * See {InRoomChannel.completedContentFromEvent} why this is needed.
     * @param {MatrixEvent} event the received event
     * @returns {Object} the content object
     */

  }, {
    key: "completedContentFromEvent",
    value: function completedContentFromEvent(event) {
      return event.getContent();
    }
    /**
     * Add all the fields to content needed for sending it over this channel.
     * This is public so verification methods (SAS uses this) can get the exact
     * content that will be sent independent of the used channel,
     * as they need to calculate the hash of it.
     * @param {string} type the event type
     * @param {object} content the (incomplete) content
     * @returns {object} the complete content, as it will be sent.
     */

  }, {
    key: "completeContent",
    value: function completeContent(type, content) {
      // make a copy
      content = Object.assign({}, content);

      if (this.transactionId) {
        content.transaction_id = this.transactionId;
      }

      if (type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE) {
        content.from_device = this._client.getDeviceId();
      }

      if (type === _VerificationRequest.REQUEST_TYPE) {
        content.timestamp = Date.now();
      }

      return content;
    }
    /**
     * Send an event over the channel with the content not having gone through `completeContent`.
     * @param {string} type the event type
     * @param {object} uncompletedContent the (incomplete) content
     * @returns {Promise} the promise of the request
     */

  }, {
    key: "send",
    value: function send(type) {
      var uncompletedContent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      // create transaction id when sending request
      if ((type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.START_TYPE) && !this.transactionId) {
        this.transactionId = ToDeviceChannel.makeTransactionId();
      }

      var content = this.completeContent(type, uncompletedContent);
      return this.sendCompleted(type, content);
    }
    /**
     * Send an event over the channel with the content having gone through `completeContent` already.
     * @param {string} type the event type
     * @param {object} content
     * @returns {Promise} the promise of the request
     */

  }, {
    key: "sendCompleted",
    value: function () {
      var _sendCompleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(type, content) {
        var result, remoteEchoEvent;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!(type === _VerificationRequest.REQUEST_TYPE)) {
                  _context2.next = 6;
                  break;
                }

                _context2.next = 3;
                return this._sendToDevices(type, content, this._devices);

              case 3:
                result = _context2.sent;
                _context2.next = 9;
                break;

              case 6:
                _context2.next = 8;
                return this._sendToDevices(type, content, [this._deviceId]);

              case 8:
                result = _context2.sent;

              case 9:
                // the VerificationRequest state machine requires remote echos of the event
                // the client sends itself, so we fake this for to_device messages
                remoteEchoEvent = new _event.MatrixEvent({
                  sender: this._client.getUserId(),
                  content: content,
                  type: type
                });
                _context2.next = 12;
                return this._request.handleEvent(type, remoteEchoEvent,
                /*isLiveEvent=*/
                true,
                /*isRemoteEcho=*/
                true,
                /*isSentByUs=*/
                true);

              case 12:
                return _context2.abrupt("return", result);

              case 13:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function sendCompleted(_x4, _x5) {
        return _sendCompleted.apply(this, arguments);
      }

      return sendCompleted;
    }()
  }, {
    key: "_sendToDevices",
    value: function _sendToDevices(type, content, devices) {
      if (devices.length) {
        var msgMap = {};

        var _iterator2 = _createForOfIteratorHelper(devices),
            _step2;

        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var deviceId = _step2.value;
            msgMap[deviceId] = content;
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }

        return this._client.sendToDevice(type, (0, _defineProperty2["default"])({}, this.userId, msgMap));
      } else {
        return Promise.resolve();
      }
    }
    /**
     * Allow Crypto module to create and know the transaction id before the .start event gets sent.
     * @returns {string} the transaction id
     */

  }, {
    key: "deviceId",
    get: function get() {
      return this._deviceId;
    }
  }], [{
    key: "getEventType",
    value: function getEventType(event) {
      return event.getType();
    }
    /**
     * Extract the transaction id used by a given key verification event, if any
     * @param {MatrixEvent} event the event
     * @returns {string} the transaction id
     */

  }, {
    key: "getTransactionId",
    value: function getTransactionId(event) {
      var content = event.getContent();
      return content && content.transaction_id;
    }
    /**
     * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel
     * @param {string} type the event type to check
     * @returns {bool} boolean flag
     */

  }, {
    key: "canCreateRequest",
    value: function canCreateRequest(type) {
      return type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.START_TYPE;
    }
    /**
     * Checks whether this event is a well-formed key verification event.
     * This only does checks that don't rely on the current state of a potentially already channel
     * so we can prevent channels being created by invalid events.
     * `handleEvent` can do more checks and choose to ignore invalid events.
     * @param {MatrixEvent} event the event to validate
     * @param {MatrixClient} client the client to get the current user and device id from
     * @returns {bool} whether the event is valid and should be passed to handleEvent
     */

  }, {
    key: "validateEvent",
    value: function validateEvent(event, client) {
      if (event.isCancelled()) {
        _logger.logger.warn("Ignoring flagged verification request from " + event.getSender());

        return false;
      }

      var content = event.getContent();

      if (!content) {
        _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no content");

        return false;
      }

      if (!content.transaction_id) {
        _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id");

        return false;
      }

      var type = event.getType();

      if (type === _VerificationRequest.REQUEST_TYPE) {
        if (!Number.isFinite(content.timestamp)) {
          _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp");

          return false;
        }

        if (event.getSender() === client.getUserId() && content.from_device == client.getDeviceId()) {
          // ignore requests from ourselves, because it doesn't make sense for a
          // device to verify itself
          _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device");

          return false;
        }
      }

      return _VerificationRequest.VerificationRequest.validateEvent(type, event, client);
    }
  }, {
    key: "makeTransactionId",
    value: function makeTransactionId() {
      return (0, _randomstring.randomString)(32);
    }
  }]);
  return ToDeviceChannel;
}();

exports.ToDeviceChannel = ToDeviceChannel;

var ToDeviceRequests = /*#__PURE__*/function () {
  function ToDeviceRequests() {
    (0, _classCallCheck2["default"])(this, ToDeviceRequests);
    this._requestsByUserId = new Map();
  }

  (0, _createClass2["default"])(ToDeviceRequests, [{
    key: "getRequest",
    value: function getRequest(event) {
      return this.getRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event));
    }
  }, {
    key: "getRequestByChannel",
    value: function getRequestByChannel(channel) {
      return this.getRequestBySenderAndTxnId(channel.userId, channel.transactionId);
    }
  }, {
    key: "getRequestBySenderAndTxnId",
    value: function getRequestBySenderAndTxnId(sender, txnId) {
      var requestsByTxnId = this._requestsByUserId.get(sender);

      if (requestsByTxnId) {
        return requestsByTxnId.get(txnId);
      }
    }
  }, {
    key: "setRequest",
    value: function setRequest(event, request) {
      this.setRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event), request);
    }
  }, {
    key: "setRequestByChannel",
    value: function setRequestByChannel(channel, request) {
      this.setRequestBySenderAndTxnId(channel.userId, channel.transactionId, request);
    }
  }, {
    key: "setRequestBySenderAndTxnId",
    value: function setRequestBySenderAndTxnId(sender, txnId, request) {
      var requestsByTxnId = this._requestsByUserId.get(sender);

      if (!requestsByTxnId) {
        requestsByTxnId = new Map();

        this._requestsByUserId.set(sender, requestsByTxnId);
      }

      requestsByTxnId.set(txnId, request);
    }
  }, {
    key: "removeRequest",
    value: function removeRequest(event) {
      var userId = event.getSender();

      var requestsByTxnId = this._requestsByUserId.get(userId);

      if (requestsByTxnId) {
        requestsByTxnId["delete"](ToDeviceChannel.getTransactionId(event));

        if (requestsByTxnId.size === 0) {
          this._requestsByUserId["delete"](userId);
        }
      }
    }
  }, {
    key: "findRequestInProgress",
    value: function findRequestInProgress(userId, devices) {
      var requestsByTxnId = this._requestsByUserId.get(userId);

      if (requestsByTxnId) {
        var _iterator3 = _createForOfIteratorHelper(requestsByTxnId.values()),
            _step3;

        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var request = _step3.value;

            if (request.pending && request.channel.isToDevices(devices)) {
              return request;
            }
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      }
    }
  }, {
    key: "getRequestsInProgress",
    value: function getRequestsInProgress(userId) {
      var requestsByTxnId = this._requestsByUserId.get(userId);

      if (requestsByTxnId) {
        return Array.from(requestsByTxnId.values()).filter(function (r) {
          return r.pending;
        });
      }

      return [];
    }
  }]);
  return ToDeviceRequests;
}();

exports.ToDeviceRequests = ToDeviceRequests;

},{"../../../logger":106,"../../../models/event":113,"../../../randomstring":123,"../Error":92,"./VerificationRequest":98,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/typeof":24,"@babel/runtime/regenerator":27}],98:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VerificationRequest = exports.PHASE_DONE = exports.PHASE_CANCELLED = exports.PHASE_STARTED = exports.PHASE_READY = exports.PHASE_REQUESTED = exports.PHASE_UNSENT = exports.READY_TYPE = exports.DONE_TYPE = exports.CANCEL_TYPE = exports.START_TYPE = exports.REQUEST_TYPE = exports.EVENT_PREFIX = void 0;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _logger = require("../../../logger");

var _events = require("events");

var _Error = require("../Error");

var _QRCode = require("../QRCode");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

// How long after the event's timestamp that the request times out
var TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes
// How long after we receive the event that the request times out

var TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes
// to avoid almost expired verification notifications
// from showing a notification and almost immediately
// disappearing, also ignore verification requests that
// are this amount of time away from expiring.

var VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds

var EVENT_PREFIX = "m.key.verification.";
exports.EVENT_PREFIX = EVENT_PREFIX;
var REQUEST_TYPE = EVENT_PREFIX + "request";
exports.REQUEST_TYPE = REQUEST_TYPE;
var START_TYPE = EVENT_PREFIX + "start";
exports.START_TYPE = START_TYPE;
var CANCEL_TYPE = EVENT_PREFIX + "cancel";
exports.CANCEL_TYPE = CANCEL_TYPE;
var DONE_TYPE = EVENT_PREFIX + "done";
exports.DONE_TYPE = DONE_TYPE;
var READY_TYPE = EVENT_PREFIX + "ready";
exports.READY_TYPE = READY_TYPE;
var PHASE_UNSENT = 1;
exports.PHASE_UNSENT = PHASE_UNSENT;
var PHASE_REQUESTED = 2;
exports.PHASE_REQUESTED = PHASE_REQUESTED;
var PHASE_READY = 3;
exports.PHASE_READY = PHASE_READY;
var PHASE_STARTED = 4;
exports.PHASE_STARTED = PHASE_STARTED;
var PHASE_CANCELLED = 5;
exports.PHASE_CANCELLED = PHASE_CANCELLED;
var PHASE_DONE = 6;
/**
 * State machine for verification requests.
 * Things that differ based on what channel is used to
 * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`.
 * @event "change" whenever the state of the request object has changed.
 */

exports.PHASE_DONE = PHASE_DONE;

var VerificationRequest = /*#__PURE__*/function (_EventEmitter) {
  (0, _inherits2["default"])(VerificationRequest, _EventEmitter);

  var _super = _createSuper(VerificationRequest);

  function VerificationRequest(channel, verificationMethods, client) {
    var _this;

    (0, _classCallCheck2["default"])(this, VerificationRequest);
    _this = _super.call(this);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_cancelOnTimeout", function () {
      try {
        if (_this.initiatedByMe) {
          _this.cancel({
            reason: "Other party didn't accept in time",
            code: "m.timeout"
          });
        } else {
          _this.cancel({
            reason: "User didn't accept in time",
            code: "m.timeout"
          });
        }
      } catch (err) {
        _logger.logger.error("Error while cancelling verification request", err);
      }
    });
    _this.channel = channel;
    _this.channel._request = (0, _assertThisInitialized2["default"])(_this);
    _this._verificationMethods = verificationMethods;
    _this._client = client;
    _this._commonMethods = [];

    _this._setPhase(PHASE_UNSENT, false);

    _this._eventsByUs = new Map();
    _this._eventsByThem = new Map();
    _this._observeOnly = false;
    _this._timeoutTimer = null;
    _this._accepting = false;
    _this._declining = false;
    _this._verifierHasFinished = false;
    _this._cancelled = false;
    _this._chosenMethod = null; // we keep a copy of the QR Code data (including other user master key) around
    // for QR reciprocate verification, to protect against
    // cross-signing identity reset between the .ready and .start event
    // and signing the wrong key after .start

    _this._qrCodeData = null; // The timestamp when we received the request event from the other side

    _this._requestReceivedAt = null;
    return _this;
  }
  /**
   * Stateless validation logic not specific to the channel.
   * Invoked by the same static method in either channel.
   * @param {string} type the "symbolic" event type, as returned by the `getEventType` function on the channel.
   * @param {MatrixEvent} event the event to validate. Don't call getType() on it but use the `type` parameter instead.
   * @param {MatrixClient} client the client to get the current user and device id from
   * @returns {bool} whether the event is valid and should be passed to handleEvent
   */


  (0, _createClass2["default"])(VerificationRequest, [{
    key: "calculateEventTimeout",
    value: function calculateEventTimeout(event) {
      var effectiveExpiresAt = this.channel.getTimestamp(event) + TIMEOUT_FROM_EVENT_TS;

      if (this._requestReceivedAt && !this.initiatedByMe && this.phase <= PHASE_REQUESTED) {
        var expiresAtByReceipt = this._requestReceivedAt + TIMEOUT_FROM_EVENT_RECEIPT;
        effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt);
      }

      return Math.max(0, effectiveExpiresAt - Date.now());
    }
    /** The current remaining amount of ms before the request should be automatically cancelled */

  }, {
    key: "otherPartySupportsMethod",

    /** Checks whether the other party supports a given verification method.
     *  This is useful when setting up the QR code UI, as it is somewhat asymmetrical:
     *  if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa.
     *  For methods that need to be supported by both ends, use the `methods` property.
     *  @param {string} method the method to check
     *  @param {boolean} force to check even if the phase is not ready or started yet, internal usage
     *  @return {bool} whether or not the other party said the supported the method */
    value: function otherPartySupportsMethod(method) {
      var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      if (!force && !this.ready && !this.started) {
        return false;
      }

      var theirMethodEvent = this._eventsByThem.get(REQUEST_TYPE) || this._eventsByThem.get(READY_TYPE);

      if (!theirMethodEvent) {
        // if we started straight away with .start event,
        // we are assuming that the other side will support the
        // chosen method, so return true for that.
        if (this.started && this.initiatedByMe) {
          var myStartEvent = this._eventsByUs.get(START_TYPE);

          var _content = myStartEvent && myStartEvent.getContent();

          var myStartMethod = _content && _content.method;
          return method == myStartMethod;
        }

        return false;
      }

      var content = theirMethodEvent.getContent();

      if (!content) {
        return false;
      }

      var methods = content.methods;

      if (!Array.isArray(methods)) {
        return false;
      }

      return methods.includes(method);
    }
    /** Whether this request was initiated by the syncing user.
     * For InRoomChannel, this is who sent the .request event.
     * For ToDeviceChannel, this is who sent the .start event
     */

  }, {
    key: "beginKeyVerification",

    /* Start the key verification, creating a verifier and sending a .start event.
     * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to.
     * @param {string} method the name of the verification method to use.
     * @param {string?} targetDevice.userId the id of the user to direct this request to
     * @param {string?} targetDevice.deviceId the id of the device to direct this request to
     * @returns {VerifierBase} the verifier of the given method
     */
    value: function beginKeyVerification(method) {
      var targetDevice = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

      // need to allow also when unsent in case of to_device
      if (!this.observeOnly && !this._verifier) {
        var validStartPhase = this.phase === PHASE_REQUESTED || this.phase === PHASE_READY || this.phase === PHASE_UNSENT && this.channel.constructor.canCreateRequest(START_TYPE);

        if (validStartPhase) {
          // when called on a request that was initiated with .request event
          // check the method is supported by both sides
          if (this._commonMethods.length && !this._commonMethods.includes(method)) {
            throw (0, _Error.newUnknownMethodError)();
          }

          this._verifier = this._createVerifier(method, null, targetDevice);

          if (!this._verifier) {
            throw (0, _Error.newUnknownMethodError)();
          }

          this._chosenMethod = method;
        }
      }

      return this._verifier;
    }
    /**
     * sends the initial .request event.
     * @returns {Promise} resolves when the event has been sent.
     */

  }, {
    key: "sendRequest",
    value: function () {
      var _sendRequest = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var methods;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!(!this.observeOnly && this._phase === PHASE_UNSENT)) {
                  _context.next = 4;
                  break;
                }

                methods = (0, _toConsumableArray2["default"])(this._verificationMethods.keys());
                _context.next = 4;
                return this.channel.send(REQUEST_TYPE, {
                  methods: methods
                });

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function sendRequest() {
        return _sendRequest.apply(this, arguments);
      }

      return sendRequest;
    }()
    /**
     * Cancels the request, sending a cancellation to the other party
     * @param {string?} error.reason the error reason to send the cancellation with
     * @param {string?} error.code the error code to send the cancellation with
     * @returns {Promise} resolves when the event has been sent.
     */

  }, {
    key: "cancel",
    value: function () {
      var _cancel = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
        var _ref,
            _ref$reason,
            reason,
            _ref$code,
            code,
            _args2 = arguments;

        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$reason = _ref.reason, reason = _ref$reason === void 0 ? "User declined" : _ref$reason, _ref$code = _ref.code, code = _ref$code === void 0 ? "m.user" : _ref$code;

                if (!(!this.observeOnly && this._phase !== PHASE_CANCELLED)) {
                  _context2.next = 11;
                  break;
                }

                this._declining = true;
                this.emit("change");

                if (!this._verifier) {
                  _context2.next = 8;
                  break;
                }

                return _context2.abrupt("return", this._verifier.cancel((0, _Error.errorFactory)(code, reason)()));

              case 8:
                this._cancellingUserId = this._client.getUserId();
                _context2.next = 11;
                return this.channel.send(CANCEL_TYPE, {
                  code: code,
                  reason: reason
                });

              case 11:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function cancel() {
        return _cancel.apply(this, arguments);
      }

      return cancel;
    }()
    /**
     * Accepts the request, sending a .ready event to the other party
     * @returns {Promise} resolves when the event has been sent.
     */

  }, {
    key: "accept",
    value: function () {
      var _accept = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
        var methods;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                if (!(!this.observeOnly && this.phase === PHASE_REQUESTED && !this.initiatedByMe)) {
                  _context3.next = 6;
                  break;
                }

                methods = (0, _toConsumableArray2["default"])(this._verificationMethods.keys());
                this._accepting = true;
                this.emit("change");
                _context3.next = 6;
                return this.channel.send(READY_TYPE, {
                  methods: methods
                });

              case 6:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function accept() {
        return _accept.apply(this, arguments);
      }

      return accept;
    }()
    /**
     * Can be used to listen for state changes until the callback returns true.
     * @param {Function} fn callback to evaluate whether the request is in the desired state.
     *                      Takes the request as an argument.
     * @returns {Promise} that resolves once the callback returns true
     * @throws {Error} when the request is cancelled
     */

  }, {
    key: "waitFor",
    value: function waitFor(fn) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        var check = function check() {
          var handled = false;

          if (fn(_this2)) {
            resolve(_this2);
            handled = true;
          } else if (_this2.cancelled) {
            reject(new Error("cancelled"));
            handled = true;
          }

          if (handled) {
            _this2.off("change", check);
          }

          return handled;
        };

        if (!check()) {
          _this2.on("change", check);
        }
      });
    }
  }, {
    key: "_setPhase",
    value: function _setPhase(phase) {
      var notify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      this._phase = phase;

      if (notify) {
        this.emit("change");
      }
    }
  }, {
    key: "_getEventByEither",
    value: function _getEventByEither(type) {
      return this._eventsByThem.get(type) || this._eventsByUs.get(type);
    }
  }, {
    key: "_getEventBy",
    value: function _getEventBy(type, byThem) {
      if (byThem) {
        return this._eventsByThem.get(type);
      } else {
        return this._eventsByUs.get(type);
      }
    }
  }, {
    key: "_calculatePhaseTransitions",
    value: function _calculatePhaseTransitions() {
      var transitions = [{
        phase: PHASE_UNSENT
      }];

      var phase = function phase() {
        return transitions[transitions.length - 1].phase;
      }; // always pass by .request first to be sure channel.userId has been set


      var hasRequestByThem = this._eventsByThem.has(REQUEST_TYPE);

      var requestEvent = this._getEventBy(REQUEST_TYPE, hasRequestByThem);

      if (requestEvent) {
        transitions.push({
          phase: PHASE_REQUESTED,
          event: requestEvent
        });
      }

      var readyEvent = requestEvent && this._getEventBy(READY_TYPE, !hasRequestByThem);

      if (readyEvent && phase() === PHASE_REQUESTED) {
        transitions.push({
          phase: PHASE_READY,
          event: readyEvent
        });
      }

      var startEvent;

      if (readyEvent || !requestEvent) {
        var theirStartEvent = this._eventsByThem.get(START_TYPE);

        var ourStartEvent = this._eventsByUs.get(START_TYPE); // any party can send .start after a .ready or unsent


        if (theirStartEvent && ourStartEvent) {
          startEvent = theirStartEvent.getSender() < ourStartEvent.getSender() ? theirStartEvent : ourStartEvent;
        } else {
          startEvent = theirStartEvent ? theirStartEvent : ourStartEvent;
        }
      } else {
        startEvent = this._getEventBy(START_TYPE, !hasRequestByThem);
      }

      if (startEvent) {
        var fromRequestPhase = phase() === PHASE_REQUESTED && requestEvent.getSender() !== startEvent.getSender();
        var fromUnsentPhase = phase() === PHASE_UNSENT && this.channel.constructor.canCreateRequest(START_TYPE);

        if (fromRequestPhase || phase() === PHASE_READY || fromUnsentPhase) {
          transitions.push({
            phase: PHASE_STARTED,
            event: startEvent
          });
        }
      }

      var ourDoneEvent = this._eventsByUs.get(DONE_TYPE);

      if (this._verifierHasFinished || ourDoneEvent && phase() === PHASE_STARTED) {
        transitions.push({
          phase: PHASE_DONE
        });
      }

      var cancelEvent = this._getEventByEither(CANCEL_TYPE);

      if ((this._cancelled || cancelEvent) && phase() !== PHASE_DONE) {
        transitions.push({
          phase: PHASE_CANCELLED,
          event: cancelEvent
        });
        return transitions;
      }

      return transitions;
    }
  }, {
    key: "_transitionToPhase",
    value: function _transitionToPhase(transition) {
      var _this3 = this;

      var phase = transition.phase,
          event = transition.event; // get common methods

      if (phase === PHASE_REQUESTED || phase === PHASE_READY) {
        if (!this._wasSentByOwnDevice(event)) {
          var content = event.getContent();
          this._commonMethods = content.methods.filter(function (m) {
            return _this3._verificationMethods.has(m);
          });
        }
      } // detect if we're not a party in the request, and we should just observe


      if (!this.observeOnly) {
        // if requested or accepted by one of my other devices
        if (phase === PHASE_REQUESTED || phase === PHASE_STARTED || phase === PHASE_READY) {
          if (this.channel.receiveStartFromOtherDevices && this._wasSentByOwnUser(event) && !this._wasSentByOwnDevice(event)) {
            this._observeOnly = true;
          }
        }
      } // create verifier


      if (phase === PHASE_STARTED) {
        var _event$getContent = event.getContent(),
            method = _event$getContent.method;

        if (!this._verifier && !this.observeOnly) {
          this._verifier = this._createVerifier(method, event);

          if (!this._verifier) {
            this.cancel({
              code: "m.unknown_method",
              reason: "Unknown method: ".concat(method)
            });
          } else {
            this._chosenMethod = method;
          }
        }
      }
    }
  }, {
    key: "_applyPhaseTransitions",
    value: function _applyPhaseTransitions() {
      var _this4 = this;

      var transitions = this._calculatePhaseTransitions();

      var existingIdx = transitions.findIndex(function (t) {
        return t.phase === _this4.phase;
      }); // trim off phases we already went through, if any

      var newTransitions = transitions.slice(existingIdx + 1); // transition to all new phases

      var _iterator = _createForOfIteratorHelper(newTransitions),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var transition = _step.value;

          this._transitionToPhase(transition);
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return newTransitions;
    }
  }, {
    key: "_isWinningStartRace",
    value: function _isWinningStartRace(newEvent) {
      if (newEvent.getType() !== START_TYPE) {
        return false;
      }

      var oldEvent = this._verifier.startEvent;
      var oldRaceIdentifier;

      if (this.isSelfVerification) {
        // if the verifier does not have a startEvent,
        // it is because it's still sending and we are on the initator side
        // we know we are sending a .start event because we already
        // have a verifier (checked in calling method)
        if (oldEvent) {
          var oldContent = oldEvent.getContent();
          oldRaceIdentifier = oldContent && oldContent.from_device;
        } else {
          oldRaceIdentifier = this._client.getDeviceId();
        }
      } else {
        if (oldEvent) {
          oldRaceIdentifier = oldEvent.getSender();
        } else {
          oldRaceIdentifier = this._client.getUserId();
        }
      }

      var newRaceIdentifier;

      if (this.isSelfVerification) {
        var newContent = newEvent.getContent();
        newRaceIdentifier = newContent && newContent.from_device;
      } else {
        newRaceIdentifier = newEvent.getSender();
      }

      return newRaceIdentifier < oldRaceIdentifier;
    }
  }, {
    key: "hasEventId",
    value: function hasEventId(eventId) {
      var _iterator2 = _createForOfIteratorHelper(this._eventsByUs.values()),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var event = _step2.value;

          if (event.getId() === eventId) {
            return true;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      var _iterator3 = _createForOfIteratorHelper(this._eventsByThem.values()),
          _step3;

      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var _event = _step3.value;

          if (_event.getId() === eventId) {
            return true;
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }

      return false;
    }
    /**
     * Changes the state of the request and verifier in response to a key verification event.
     * @param {string} type the "symbolic" event type, as returned by the `getEventType` function on the channel.
     * @param {MatrixEvent} event the event to handle. Don't call getType() on it but use the `type` parameter instead.
     * @param {bool} isLiveEvent whether this is an even received through sync or not
     * @param {bool} isRemoteEcho whether this is the remote echo of an event sent by the same device
     * @param {bool} isSentByUs whether this event is sent by a party that can accept and/or observe the request like one of our peers.
     *   For InRoomChannel this means any device for the syncing user. For ToDeviceChannel, just the syncing device.
     * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.
     */

  }, {
    key: "handleEvent",
    value: function () {
      var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(type, event, isLiveEvent, isRemoteEcho, isSentByUs) {
        var wasObserveOnly, isDuplicateEvent, oldPhase, newTransitions, newEventWinsRace, shouldGenerateQrCode, lastTransition, phase;
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                if (!(this.done || this.cancelled)) {
                  _context4.next = 2;
                  break;
                }

                return _context4.abrupt("return");

              case 2:
                wasObserveOnly = this._observeOnly;

                this._adjustObserveOnly(event, isLiveEvent);

                if (!(!this.observeOnly && !isRemoteEcho)) {
                  _context4.next = 9;
                  break;
                }

                _context4.next = 7;
                return this._cancelOnError(type, event);

              case 7:
                if (!_context4.sent) {
                  _context4.next = 9;
                  break;
                }

                return _context4.abrupt("return");

              case 9:
                // This assumes verification won't need to send an event with
                // the same type for the same party twice.
                // This is true for QR and SAS verification, and was
                // added here to prevent verification getting cancelled
                // when the server duplicates an event (https://github.com/matrix-org/synapse/issues/3365)
                isDuplicateEvent = isSentByUs ? this._eventsByUs.has(type) : this._eventsByThem.has(type);

                if (!isDuplicateEvent) {
                  _context4.next = 12;
                  break;
                }

                return _context4.abrupt("return");

              case 12:
                oldPhase = this.phase;

                this._addEvent(type, event, isSentByUs); // this will create if needed the verifier so needs to happen before calling it


                newTransitions = this._applyPhaseTransitions();
                _context4.prev = 15;

                // only pass events from the other side to the verifier,
                // no remote echos of our own events
                if (this._verifier && !this.observeOnly) {
                  newEventWinsRace = this._isWinningStartRace(event);

                  if (this._verifier.canSwitchStartEvent(event) && newEventWinsRace) {
                    this._verifier.switchStartEvent(event);
                  } else if (!isRemoteEcho) {
                    if (type === CANCEL_TYPE || this._verifier.events && this._verifier.events.includes(type)) {
                      this._verifier.handleEvent(event);
                    }
                  }
                }

                if (!newTransitions.length) {
                  _context4.next = 30;
                  break;
                }

                if (!(isLiveEvent && newTransitions.some(function (t) {
                  return t.phase === PHASE_READY;
                }))) {
                  _context4.next = 24;
                  break;
                }

                shouldGenerateQrCode = this.otherPartySupportsMethod(_QRCode.SCAN_QR_CODE_METHOD, true);

                if (!shouldGenerateQrCode) {
                  _context4.next = 24;
                  break;
                }

                _context4.next = 23;
                return _QRCode.QRCodeData.create(this, this._client);

              case 23:
                this._qrCodeData = _context4.sent;

              case 24:
                lastTransition = newTransitions[newTransitions.length - 1];
                phase = lastTransition.phase;

                this._setupTimeout(phase); // set phase as last thing as this emits the "change" event


                this._setPhase(phase);

                _context4.next = 31;
                break;

              case 30:
                if (this._observeOnly !== wasObserveOnly) {
                  this.emit("change");
                }

              case 31:
                _context4.prev = 31;

                // log events we processed so we can see from rageshakes what events were added to a request
                _logger.logger.log("Verification request ".concat(this.channel.transactionId, ": ") + "".concat(type, " event with id:").concat(event.getId(), ", ") + "content:".concat(JSON.stringify(event.getContent()), " ") + "deviceId:".concat(this.channel.deviceId, ", ") + "sender:".concat(event.getSender(), ", isSentByUs:").concat(isSentByUs, ", ") + "isLiveEvent:".concat(isLiveEvent, ", isRemoteEcho:").concat(isRemoteEcho, ", ") + "phase:".concat(oldPhase, "=>").concat(this.phase, ", ") + "observeOnly:".concat(wasObserveOnly, "=>").concat(this._observeOnly));

                return _context4.finish(31);

              case 34:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this, [[15,, 31, 34]]);
      }));

      function handleEvent(_x, _x2, _x3, _x4, _x5) {
        return _handleEvent.apply(this, arguments);
      }

      return handleEvent;
    }()
  }, {
    key: "_setupTimeout",
    value: function _setupTimeout(phase) {
      var shouldTimeout = !this._timeoutTimer && !this.observeOnly && phase === PHASE_REQUESTED;

      if (shouldTimeout) {
        this._timeoutTimer = setTimeout(this._cancelOnTimeout, this.timeout);
      }

      if (this._timeoutTimer) {
        var shouldClear = phase === PHASE_STARTED || phase === PHASE_READY || phase === PHASE_DONE || phase === PHASE_CANCELLED;

        if (shouldClear) {
          clearTimeout(this._timeoutTimer);
          this._timeoutTimer = null;
        }
      }
    }
  }, {
    key: "_cancelOnError",
    value: function () {
      var _cancelOnError2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(type, event) {
        var method, isUnexpectedRequest, isUnexpectedReady, reason;
        return _regenerator["default"].wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                if (!(type === START_TYPE)) {
                  _context5.next = 6;
                  break;
                }

                method = event.getContent().method;

                if (this._verificationMethods.has(method)) {
                  _context5.next = 6;
                  break;
                }

                _context5.next = 5;
                return this.cancel((0, _Error.errorFromEvent)((0, _Error.newUnknownMethodError)()));

              case 5:
                return _context5.abrupt("return", true);

              case 6:
                isUnexpectedRequest = type === REQUEST_TYPE && this.phase !== PHASE_UNSENT;
                isUnexpectedReady = type === READY_TYPE && this.phase !== PHASE_REQUESTED; // only if phase has passed from PHASE_UNSENT should we cancel, because events
                // are allowed to come in in any order (at least with InRoomChannel). So we only know
                // we're dealing with a valid request we should participate in once we've moved to PHASE_REQUESTED
                // before that, we could be looking at somebody elses verification request and we just
                // happen to be in the room

                if (!(this.phase !== PHASE_UNSENT && (isUnexpectedRequest || isUnexpectedReady))) {
                  _context5.next = 14;
                  break;
                }

                _logger.logger.warn("Cancelling, unexpected ".concat(type, " verification ") + "event from ".concat(event.getSender()));

                reason = "Unexpected ".concat(type, " event in phase ").concat(this.phase);
                _context5.next = 13;
                return this.cancel((0, _Error.errorFromEvent)((0, _Error.newUnexpectedMessageError)({
                  reason: reason
                })));

              case 13:
                return _context5.abrupt("return", true);

              case 14:
                return _context5.abrupt("return", false);

              case 15:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function _cancelOnError(_x6, _x7) {
        return _cancelOnError2.apply(this, arguments);
      }

      return _cancelOnError;
    }()
  }, {
    key: "_adjustObserveOnly",
    value: function _adjustObserveOnly(event, isLiveEvent) {
      // don't send out events for historical requests
      if (!isLiveEvent) {
        this._observeOnly = true;
      }

      if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) {
        this._observeOnly = true;
      }
    }
  }, {
    key: "_addEvent",
    value: function _addEvent(type, event, isSentByUs) {
      if (isSentByUs) {
        this._eventsByUs.set(type, event);
      } else {
        this._eventsByThem.set(type, event);
      } // once we know the userId of the other party (from the .request event)
      // see if any event by anyone else crept into this._eventsByThem


      if (type === REQUEST_TYPE) {
        var _iterator4 = _createForOfIteratorHelper(this._eventsByThem.entries()),
            _step4;

        try {
          for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
            var _step4$value = (0, _slicedToArray2["default"])(_step4.value, 2),
                _type = _step4$value[0],
                _event2 = _step4$value[1];

            if (_event2.getSender() !== this.otherUserId) {
              this._eventsByThem["delete"](_type);
            }
          } // also remember when we received the request event

        } catch (err) {
          _iterator4.e(err);
        } finally {
          _iterator4.f();
        }

        this._requestReceivedAt = Date.now();
      }
    }
  }, {
    key: "_createVerifier",
    value: function _createVerifier(method) {
      var startEvent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
      var targetDevice = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      if (!targetDevice) {
        targetDevice = this.targetDevice;
      }

      var _targetDevice = targetDevice,
          userId = _targetDevice.userId,
          deviceId = _targetDevice.deviceId;

      var VerifierCtor = this._verificationMethods.get(method);

      if (!VerifierCtor) {
        _logger.logger.warn("could not find verifier constructor for method", method);

        return;
      }

      return new VerifierCtor(this.channel, this._client, userId, deviceId, startEvent, this);
    }
  }, {
    key: "_wasSentByOwnUser",
    value: function _wasSentByOwnUser(event) {
      return event.getSender() === this._client.getUserId();
    } // only for .request, .ready or .start

  }, {
    key: "_wasSentByOwnDevice",
    value: function _wasSentByOwnDevice(event) {
      if (!this._wasSentByOwnUser(event)) {
        return false;
      }

      var content = event.getContent();

      if (!content || content.from_device !== this._client.getDeviceId()) {
        return false;
      }

      return true;
    }
  }, {
    key: "onVerifierCancelled",
    value: function onVerifierCancelled() {
      this._cancelled = true; // move to cancelled phase

      var newTransitions = this._applyPhaseTransitions();

      if (newTransitions.length) {
        this._setPhase(newTransitions[newTransitions.length - 1].phase);
      }
    }
  }, {
    key: "onVerifierFinished",
    value: function onVerifierFinished() {
      this.channel.send("m.key.verification.done", {});
      this._verifierHasFinished = true; // move to .done phase

      var newTransitions = this._applyPhaseTransitions();

      if (newTransitions.length) {
        this._setPhase(newTransitions[newTransitions.length - 1].phase);
      }
    }
  }, {
    key: "getEventFromOtherParty",
    value: function getEventFromOtherParty(type) {
      return this._eventsByThem.get(type);
    }
  }, {
    key: "invalid",
    get: function get() {
      return this.phase === PHASE_UNSENT;
    }
    /** returns whether the phase is PHASE_REQUESTED */

  }, {
    key: "requested",
    get: function get() {
      return this.phase === PHASE_REQUESTED;
    }
    /** returns whether the phase is PHASE_CANCELLED */

  }, {
    key: "cancelled",
    get: function get() {
      return this.phase === PHASE_CANCELLED;
    }
    /** returns whether the phase is PHASE_READY */

  }, {
    key: "ready",
    get: function get() {
      return this.phase === PHASE_READY;
    }
    /** returns whether the phase is PHASE_STARTED */

  }, {
    key: "started",
    get: function get() {
      return this.phase === PHASE_STARTED;
    }
    /** returns whether the phase is PHASE_DONE */

  }, {
    key: "done",
    get: function get() {
      return this.phase === PHASE_DONE;
    }
    /** once the phase is PHASE_STARTED (and !initiatedByMe) or PHASE_READY: common methods supported by both sides */

  }, {
    key: "methods",
    get: function get() {
      return this._commonMethods;
    }
    /** the method picked in the .start event */

  }, {
    key: "chosenMethod",
    get: function get() {
      return this._chosenMethod;
    }
  }, {
    key: "timeout",
    get: function get() {
      var requestEvent = this._getEventByEither(REQUEST_TYPE);

      if (requestEvent) {
        return this.calculateEventTimeout(requestEvent);
      }

      return 0;
    }
    /**
     * The key verification request event.
     * @returns {MatrixEvent} The request event, or falsey if not found.
     */

  }, {
    key: "requestEvent",
    get: function get() {
      return this._getEventByEither(REQUEST_TYPE);
    }
    /** current phase of the request. Some properties might only be defined in a current phase. */

  }, {
    key: "phase",
    get: function get() {
      return this._phase;
    }
    /** The verifier to do the actual verification, once the method has been established. Only defined when the `phase` is PHASE_STARTED. */

  }, {
    key: "verifier",
    get: function get() {
      return this._verifier;
    }
  }, {
    key: "canAccept",
    get: function get() {
      return this.phase < PHASE_READY && !this._accepting && !this._declining;
    }
  }, {
    key: "accepting",
    get: function get() {
      return this._accepting;
    }
  }, {
    key: "declining",
    get: function get() {
      return this._declining;
    }
    /** whether this request has sent it's initial event and needs more events to complete */

  }, {
    key: "pending",
    get: function get() {
      return !this.observeOnly && this._phase !== PHASE_DONE && this._phase !== PHASE_CANCELLED;
    }
    /** Only set after a .ready if the other party can scan a QR code */

  }, {
    key: "qrCodeData",
    get: function get() {
      return this._qrCodeData;
    }
  }, {
    key: "initiatedByMe",
    get: function get() {
      // event created by us but no remote echo has been received yet
      var noEventsYet = this._eventsByUs.size + this._eventsByThem.size === 0;

      if (this._phase === PHASE_UNSENT && noEventsYet) {
        return true;
      }

      var hasMyRequest = this._eventsByUs.has(REQUEST_TYPE);

      var hasTheirRequest = this._eventsByThem.has(REQUEST_TYPE);

      if (hasMyRequest && !hasTheirRequest) {
        return true;
      }

      if (!hasMyRequest && hasTheirRequest) {
        return false;
      }

      var hasMyStart = this._eventsByUs.has(START_TYPE);

      var hasTheirStart = this._eventsByThem.has(START_TYPE);

      if (hasMyStart && !hasTheirStart) {
        return true;
      }

      return false;
    }
    /** The id of the user that initiated the request */

  }, {
    key: "requestingUserId",
    get: function get() {
      if (this.initiatedByMe) {
        return this._client.getUserId();
      } else {
        return this.otherUserId;
      }
    }
    /** The id of the user that (will) receive(d) the request */

  }, {
    key: "receivingUserId",
    get: function get() {
      if (this.initiatedByMe) {
        return this.otherUserId;
      } else {
        return this._client.getUserId();
      }
    }
    /** The user id of the other party in this request */

  }, {
    key: "otherUserId",
    get: function get() {
      return this.channel.userId;
    }
  }, {
    key: "isSelfVerification",
    get: function get() {
      return this._client.getUserId() === this.otherUserId;
    }
    /**
     * The id of the user that cancelled the request,
     * only defined when phase is PHASE_CANCELLED
     */

  }, {
    key: "cancellingUserId",
    get: function get() {
      var myCancel = this._eventsByUs.get(CANCEL_TYPE);

      var theirCancel = this._eventsByThem.get(CANCEL_TYPE);

      if (myCancel && (!theirCancel || myCancel.getId() < theirCancel.getId())) {
        return myCancel.getSender();
      }

      if (theirCancel) {
        return theirCancel.getSender();
      }

      return undefined;
    }
    /**
     * The cancellation code e.g m.user which is responsible for cancelling this verification
     */

  }, {
    key: "cancellationCode",
    get: function get() {
      var ev = this._getEventByEither(CANCEL_TYPE);

      return ev ? ev.getContent().code : null;
    }
  }, {
    key: "observeOnly",
    get: function get() {
      return this._observeOnly;
    }
    /**
     * Gets which device the verification should be started with
     * given the events sent so far in the verification. This is the
     * same algorithm used to determine which device to send the
     * verification to when no specific device is specified.
     * @returns {{userId: *, deviceId: *}} The device information
     */

  }, {
    key: "targetDevice",
    get: function get() {
      var theirFirstEvent = this._eventsByThem.get(REQUEST_TYPE) || this._eventsByThem.get(READY_TYPE) || this._eventsByThem.get(START_TYPE);

      var theirFirstContent = theirFirstEvent.getContent();
      var fromDevice = theirFirstContent.from_device;
      return {
        userId: this.otherUserId,
        deviceId: fromDevice
      };
    }
  }], [{
    key: "validateEvent",
    value: function validateEvent(type, event, client) {
      var content = event.getContent();

      if (!type || !type.startsWith(EVENT_PREFIX)) {
        return false;
      } // from here on we're fairly sure that this is supposed to be
      // part of a verification request, so be noisy when rejecting something


      if (!content) {
        _logger.logger.log("VerificationRequest: validateEvent: no content");

        return false;
      }

      if (type === REQUEST_TYPE || type === READY_TYPE) {
        if (!Array.isArray(content.methods)) {
          _logger.logger.log("VerificationRequest: validateEvent: " + "fail because methods");

          return false;
        }
      }

      if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {
        if (typeof content.from_device !== "string" || content.from_device.length === 0) {
          _logger.logger.log("VerificationRequest: validateEvent: " + "fail because from_device");

          return false;
        }
      }

      return true;
    }
  }]);
  return VerificationRequest;
}(_events.EventEmitter);

exports.VerificationRequest = VerificationRequest;

},{"../../../logger":106,"../Error":92,"../QRCode":94,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/toConsumableArray":23,"@babel/runtime/regenerator":27,"events":36}],99:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InvalidStoreError = InvalidStoreError;
exports.InvalidCryptoStoreError = InvalidCryptoStoreError;
exports.KeySignatureUploadError = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

// can't just do InvalidStoreError extends Error
// because of http://babeljs.io/docs/usage/caveats/#classes
function InvalidStoreError(reason, value) {
  var message = "Store is invalid because ".concat(reason, ", ") + "please stop the client, delete all data and start the client again";
  var instance = Reflect.construct(Error, [message]);
  Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
  instance.reason = reason;
  instance.value = value;
  return instance;
}

InvalidStoreError.TOGGLED_LAZY_LOADING = "TOGGLED_LAZY_LOADING";
InvalidStoreError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: Error,
    enumerable: false,
    writable: true,
    configurable: true
  }
});
Reflect.setPrototypeOf(InvalidStoreError, Error);

function InvalidCryptoStoreError(reason) {
  var message = "Crypto store is invalid because ".concat(reason, ", ") + "please stop the client, delete all data and start the client again";
  var instance = Reflect.construct(Error, [message]);
  Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
  instance.reason = reason;
  instance.name = 'InvalidCryptoStoreError';
  return instance;
}

InvalidCryptoStoreError.TOO_NEW = "TOO_NEW";
InvalidCryptoStoreError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: Error,
    enumerable: false,
    writable: true,
    configurable: true
  }
});
Reflect.setPrototypeOf(InvalidCryptoStoreError, Error);

var KeySignatureUploadError = /*#__PURE__*/function (_Error) {
  (0, _inherits2["default"])(KeySignatureUploadError, _Error);

  var _super = _createSuper(KeySignatureUploadError);

  function KeySignatureUploadError(message, value) {
    var _this;

    (0, _classCallCheck2["default"])(this, KeySignatureUploadError);
    _this = _super.call(this, message);
    _this.value = value;
    return _this;
  }

  return KeySignatureUploadError;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));

exports.KeySignatureUploadError = KeySignatureUploadError;

},{"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/wrapNativeSuper":26}],100:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventMapperFor = void 0;
const event_1 = require("./models/event");
function eventMapperFor(client, options) {
    const preventReEmit = Boolean(options.preventReEmit);
    const decrypt = options.decrypt !== false;
    function mapper(plainOldJsObject) {
        const event = new event_1.MatrixEvent(plainOldJsObject);
        if (event.isEncrypted()) {
            if (!preventReEmit) {
                client.reEmitter.reEmit(event, [
                    "Event.decrypted",
                ]);
            }
            if (decrypt) {
                client.decryptEventIfNeeded(event);
            }
        }
        if (!preventReEmit) {
            client.reEmitter.reEmit(event, ["Event.replaced"]);
        }
        return event;
    }
    return mapper;
}
exports.eventMapperFor = eventMapperFor;

},{"./models/event":113}],101:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.FilterComponent = void 0;
/**
 * @module filter-component
 */
/**
 * Checks if a value matches a given field value, which may be a * terminated
 * wildcard pattern.
 * @param {String} actualValue  The value to be compared
 * @param {String} filterValue  The filter pattern to be compared
 * @return {boolean} true if the actualValue matches the filterValue
 */
function matchesWildcard(actualValue, filterValue) {
    if (filterValue.endsWith("*")) {
        const typePrefix = filterValue.slice(0, -1);
        return actualValue.substr(0, typePrefix.length) === typePrefix;
    }
    else {
        return actualValue === filterValue;
    }
}
/* eslint-enable camelcase */
/**
 * FilterComponent is a section of a Filter definition which defines the
 * types, rooms, senders filters etc to be applied to a particular type of resource.
 * This is all ported over from synapse's Filter object.
 *
 * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as
 * 'Filters' are referred to as 'FilterCollections'.
 *
 * @constructor
 * @param {Object} filterJson the definition of this filter JSON, e.g. { 'contains_url': true }
 */
class FilterComponent {
    constructor(filterJson) {
        this.filterJson = filterJson;
    }
    /**
     * Checks with the filter component matches the given event
     * @param {MatrixEvent} event event to be checked against the filter
     * @return {boolean} true if the event matches the filter
     */
    check(event) {
        return this.checkFields(event.getRoomId(), event.getSender(), event.getType(), event.getContent() ? event.getContent().url !== undefined : false);
    }
    /**
     * Converts the filter component into the form expected over the wire
     */
    toJSON() {
        return {
            types: this.filterJson.types || null,
            not_types: this.filterJson.not_types || [],
            rooms: this.filterJson.rooms || null,
            not_rooms: this.filterJson.not_rooms || [],
            senders: this.filterJson.senders || null,
            not_senders: this.filterJson.not_senders || [],
            contains_url: this.filterJson.contains_url || null,
        };
    }
    /**
     * Checks whether the filter component matches the given event fields.
     * @param {String} roomId        the roomId for the event being checked
     * @param {String} sender        the sender of the event being checked
     * @param {String} eventType     the type of the event being checked
     * @param {boolean} containsUrl  whether the event contains a content.url field
     * @return {boolean} true if the event fields match the filter
     */
    checkFields(roomId, sender, eventType, containsUrl) {
        const literalKeys = {
            "rooms": function (v) {
                return roomId === v;
            },
            "senders": function (v) {
                return sender === v;
            },
            "types": function (v) {
                return matchesWildcard(eventType, v);
            },
        };
        for (let n = 0; n < Object.keys(literalKeys).length; n++) {
            const name = Object.keys(literalKeys)[n];
            const matchFunc = literalKeys[name];
            const notName = "not_" + name;
            const disallowedValues = this.filterJson[notName];
            if (disallowedValues === null || disallowedValues === void 0 ? void 0 : disallowedValues.some(matchFunc)) {
                return false;
            }
            const allowedValues = this.filterJson[name];
            if (allowedValues && !allowedValues.some(matchFunc)) {
                return false;
            }
        }
        const containsUrlFilter = this.filterJson.contains_url;
        if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {
            return false;
        }
        return true;
    }
    /**
     * Filters a list of events down to those which match this filter component
     * @param {MatrixEvent[]} events  Events to be checked against the filter component
     * @return {MatrixEvent[]} events which matched the filter component
     */
    filter(events) {
        return events.filter(this.check, this);
    }
    /**
     * Returns the limit field for a given filter component, providing a default of
     * 10 if none is otherwise specified. Cargo-culted from Synapse.
     * @return {Number} the limit for this filter component.
     */
    limit() {
        return this.filterJson.limit !== undefined ? this.filterJson.limit : 10;
    }
}
exports.FilterComponent = FilterComponent;

},{}],102:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Filter = void 0;
/**
 * @module filter
 */
const filter_component_1 = require("./filter-component");
/**
 * @param {Object} obj
 * @param {string} keyNesting
 * @param {*} val
 */
function setProp(obj, keyNesting, val) {
    const nestedKeys = keyNesting.split(".");
    let currentObj = obj;
    for (let i = 0; i < (nestedKeys.length - 1); i++) {
        if (!currentObj[nestedKeys[i]]) {
            currentObj[nestedKeys[i]] = {};
        }
        currentObj = currentObj[nestedKeys[i]];
    }
    currentObj[nestedKeys[nestedKeys.length - 1]] = val;
}
/* eslint-enable camelcase */
/**
 * Construct a new Filter.
 * @constructor
 * @param {string} userId The user ID for this filter.
 * @param {string=} filterId The filter ID if known.
 * @prop {string} userId The user ID of the filter
 * @prop {?string} filterId The filter ID
 */
class Filter {
    constructor(userId, filterId) {
        this.userId = userId;
        this.filterId = filterId;
        this.definition = {};
    }
    /**
     * Create a filter from existing data.
     * @static
     * @param {string} userId
     * @param {string} filterId
     * @param {Object} jsonObj
     * @return {Filter}
     */
    static fromJson(userId, filterId, jsonObj) {
        const filter = new Filter(userId, filterId);
        filter.setDefinition(jsonObj);
        return filter;
    }
    /**
     * Get the ID of this filter on your homeserver (if known)
     * @return {?string} The filter ID
     */
    getFilterId() {
        return this.filterId;
    }
    /**
     * Get the JSON body of the filter.
     * @return {Object} The filter definition
     */
    getDefinition() {
        return this.definition;
    }
    /**
     * Set the JSON body of the filter
     * @param {Object} definition The filter definition
     */
    setDefinition(definition) {
        this.definition = definition;
        // This is all ported from synapse's FilterCollection()
        // definitions look something like:
        // {
        //   "room": {
        //     "rooms": ["!abcde:example.com"],
        //     "not_rooms": ["!123456:example.com"],
        //     "state": {
        //       "types": ["m.room.*"],
        //       "not_rooms": ["!726s6s6q:example.com"],
        //       "lazy_load_members": true,
        //     },
        //     "timeline": {
        //       "limit": 10,
        //       "types": ["m.room.message"],
        //       "not_rooms": ["!726s6s6q:example.com"],
        //       "not_senders": ["@spam:example.com"]
        //       "contains_url": true
        //     },
        //     "ephemeral": {
        //       "types": ["m.receipt", "m.typing"],
        //       "not_rooms": ["!726s6s6q:example.com"],
        //       "not_senders": ["@spam:example.com"]
        //     }
        //   },
        //   "presence": {
        //     "types": ["m.presence"],
        //     "not_senders": ["@alice:example.com"]
        //   },
        //   "event_format": "client",
        //   "event_fields": ["type", "content", "sender"]
        // }
        const roomFilterJson = definition.room;
        // consider the top level rooms/not_rooms filter
        const roomFilterFields = {};
        if (roomFilterJson) {
            if (roomFilterJson.rooms) {
                roomFilterFields.rooms = roomFilterJson.rooms;
            }
            if (roomFilterJson.rooms) {
                roomFilterFields.not_rooms = roomFilterJson.not_rooms;
            }
        }
        this.roomFilter = new filter_component_1.FilterComponent(roomFilterFields);
        this.roomTimelineFilter = new filter_component_1.FilterComponent((roomFilterJson === null || roomFilterJson === void 0 ? void 0 : roomFilterJson.timeline) || {});
        // don't bother porting this from synapse yet:
        // this._room_state_filter =
        //     new FilterComponent(roomFilterJson.state || {});
        // this._room_ephemeral_filter =
        //     new FilterComponent(roomFilterJson.ephemeral || {});
        // this._room_account_data_filter =
        //     new FilterComponent(roomFilterJson.account_data || {});
        // this._presence_filter =
        //     new FilterComponent(definition.presence || {});
        // this._account_data_filter =
        //     new FilterComponent(definition.account_data || {});
    }
    /**
     * Get the room.timeline filter component of the filter
     * @return {FilterComponent} room timeline filter component
     */
    getRoomTimelineFilterComponent() {
        return this.roomTimelineFilter;
    }
    /**
     * Filter the list of events based on whether they are allowed in a timeline
     * based on this filter
     * @param {MatrixEvent[]} events  the list of events being filtered
     * @return {MatrixEvent[]} the list of events which match the filter
     */
    filterRoomTimeline(events) {
        return this.roomTimelineFilter.filter(this.roomFilter.filter(events));
    }
    /**
     * Set the max number of events to return for each room's timeline.
     * @param {Number} limit The max number of events to return for each room.
     */
    setTimelineLimit(limit) {
        setProp(this.definition, "room.timeline.limit", limit);
    }
    setLazyLoadMembers(enabled) {
        setProp(this.definition, "room.state.lazy_load_members", !!enabled);
    }
    /**
     * Control whether left rooms should be included in responses.
     * @param {boolean} includeLeave True to make rooms the user has left appear
     * in responses.
     */
    setIncludeLeaveRooms(includeLeave) {
        setProp(this.definition, "room.include_leave", includeLeave);
    }
}
exports.Filter = Filter;
Filter.LAZY_LOADING_MESSAGES_FILTER = {
    lazy_load_members: true,
};

},{"./filter-component":101}],103:[function(require,module,exports){
(function (global){(function (){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MatrixHttpApi = MatrixHttpApi;
exports.retryNetworkOperation = retryNetworkOperation;
exports.AbortError = exports.ConnectionError = exports.MatrixError = exports.PREFIX_MEDIA_R0 = exports.PREFIX_IDENTITY_V2 = exports.PREFIX_IDENTITY_V1 = exports.PREFIX_UNSTABLE = exports.PREFIX_R0 = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _contentType = require("content-type");

var utils = _interopRequireWildcard(require("./utils"));

var _logger = require("./logger");

var callbacks = _interopRequireWildcard(require("./realtime-callbacks"));

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

/*
TODO:
- CS: complete register function (doing stages)
- Identity server: linkEmail, authEmail, bindEmail, lookup3pid
*/

/**
 * A constant representing the URI path for release 0 of the Client-Server HTTP API.
 */
var PREFIX_R0 = "/_matrix/client/r0";
/**
 * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.
 */

exports.PREFIX_R0 = PREFIX_R0;
var PREFIX_UNSTABLE = "/_matrix/client/unstable";
/**
 * URI path for v1 of the the identity API
 * @deprecated Use v2.
 */

exports.PREFIX_UNSTABLE = PREFIX_UNSTABLE;
var PREFIX_IDENTITY_V1 = "/_matrix/identity/api/v1";
/**
 * URI path for the v2 identity API
 */

exports.PREFIX_IDENTITY_V1 = PREFIX_IDENTITY_V1;
var PREFIX_IDENTITY_V2 = "/_matrix/identity/v2";
/**
 * URI path for the media repo API
 */

exports.PREFIX_IDENTITY_V2 = PREFIX_IDENTITY_V2;
var PREFIX_MEDIA_R0 = "/_matrix/media/r0";
/**
 * Construct a MatrixHttpApi.
 * @constructor
 * @param {EventEmitter} event_emitter The event emitter to use for emitting events
 * @param {Object} opts The options to use for this HTTP API.
 * @param {string} opts.baseUrl Required. The base client-server URL e.g.
 * 'http://localhost:8008'.
 * @param {Function} opts.request Required. The function to call for HTTP
 * requests. This function must look like function(opts, callback){ ... }.
 * @param {string} opts.prefix Required. The matrix client prefix to use, e.g.
 * '/_matrix/client/r0'. See PREFIX_R0 and PREFIX_UNSTABLE for constants.
 *
 * @param {boolean} opts.onlyData True to return only the 'data' component of the
 * response (e.g. the parsed HTTP body). If false, requests will return an
 * object with the properties <tt>code</tt>, <tt>headers</tt> and <tt>data</tt>.
 *
 * @param {string} opts.accessToken The access_token to send with requests. Can be
 * null to not send an access token.
 * @param {Object=} opts.extraParams Optional. Extra query parameters to send on
 * requests.
 * @param {Number=} opts.localTimeoutMs The default maximum amount of time to wait
 * before timing out the request. If not specified, there is no timeout.
 * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use
 * Authorization header instead of query param to send the access token to the server.
 */

exports.PREFIX_MEDIA_R0 = PREFIX_MEDIA_R0;

function MatrixHttpApi(event_emitter, opts) {
  utils.checkObjectHasKeys(opts, ["baseUrl", "request", "prefix"]);
  opts.onlyData = opts.onlyData || false;
  this.event_emitter = event_emitter;
  this.opts = opts;
  this.useAuthorizationHeader = Boolean(opts.useAuthorizationHeader);
  this.uploads = [];
}

MatrixHttpApi.prototype = {
  /**
   * Sets the baase URL for the identity server
   * @param {string} url The new base url
   */
  setIdBaseUrl: function setIdBaseUrl(url) {
    this.opts.idBaseUrl = url;
  },

  /**
   * Get the content repository url with query parameters.
   * @return {Object} An object with a 'base', 'path' and 'params' for base URL,
   *          path and query parameters respectively.
   */
  getContentUri: function getContentUri() {
    var params = {
      access_token: this.opts.accessToken
    };
    return {
      base: this.opts.baseUrl,
      path: "/_matrix/media/r0/upload",
      params: params
    };
  },

  /**
   * Upload content to the Home Server
   *
   * @param {object} file The object to upload. On a browser, something that
   *   can be sent to XMLHttpRequest.send (typically a File).  Under node.js,
   *   a Buffer, String or ReadStream.
   *
   * @param {object} opts  options object
   *
   * @param {string=} opts.name   Name to give the file on the server. Defaults
   *   to <tt>file.name</tt>.
   *
   * @param {boolean=} opts.includeFilename if false will not send the filename,
   *   e.g for encrypted file uploads where filename leaks are undesirable.
   *   Defaults to true.
   *
   * @param {string=} opts.type   Content-type for the upload. Defaults to
   *   <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.
   *
   * @param {boolean=} opts.rawResponse Return the raw body, rather than
   *   parsing the JSON. Defaults to false (except on node.js, where it
   *   defaults to true for backwards compatibility).
   *
   * @param {boolean=} opts.onlyContentUri Just return the content URI,
   *   rather than the whole body. Defaults to false (except on browsers,
   *   where it defaults to true for backwards compatibility). Ignored if
   *   opts.rawResponse is true.
   *
   * @param {Function=} opts.callback Deprecated. Optional. The callback to
   *    invoke on success/failure. See the promise return values for more
   *    information.
   *
   * @param {Function=} opts.progressHandler Optional. Called when a chunk of
   *    data has been uploaded, with an object containing the fields `loaded`
   *    (number of bytes transferred) and `total` (total size, if known).
   *
   * @return {Promise} Resolves to response object, as
   *    determined by this.opts.onlyData, opts.rawResponse, and
   *    opts.onlyContentUri.  Rejects with an error (usually a MatrixError).
   */
  uploadContent: function uploadContent(file, opts) {
    if (utils.isFunction(opts)) {
      // opts used to be callback
      opts = {
        callback: opts
      };
    } else if (opts === undefined) {
      opts = {};
    } // default opts.includeFilename to true (ignoring falsey values)


    var includeFilename = opts.includeFilename !== false; // if the file doesn't have a mime type, use a default since
    // the HS errors if we don't supply one.

    var contentType = opts.type || file.type || 'application/octet-stream';
    var fileName = opts.name || file.name; // We used to recommend setting file.stream to the thing to upload on
    // Node.js. As of 2019-06-11, this is still in widespread use in various
    // clients, so we should preserve this for simple objects used in
    // Node.js. File API objects (via either the File or Blob interfaces) in
    // the browser now define a `stream` method, which leads to trouble
    // here, so we also check the type of `stream`.

    var body = file;

    if (body.stream && typeof body.stream !== "function") {
      _logger.logger.warn("Using `file.stream` as the content to upload. Future " + "versions of the js-sdk will change this to expect `file` to " + "be the content directly.");

      body = body.stream;
    } // backwards-compatibility hacks where we used to do different things
    // between browser and node.


    var rawResponse = opts.rawResponse;

    if (rawResponse === undefined) {
      if (global.XMLHttpRequest) {
        rawResponse = false;
      } else {
        _logger.logger.warn("Returning the raw JSON from uploadContent(). Future " + "versions of the js-sdk will change this default, to " + "return the parsed object. Set opts.rawResponse=false " + "to change this behaviour now.");

        rawResponse = true;
      }
    }

    var onlyContentUri = opts.onlyContentUri;

    if (!rawResponse && onlyContentUri === undefined) {
      if (global.XMLHttpRequest) {
        _logger.logger.warn("Returning only the content-uri from uploadContent(). " + "Future versions of the js-sdk will change this " + "default, to return the whole response object. Set " + "opts.onlyContentUri=false to change this behaviour now.");

        onlyContentUri = true;
      } else {
        onlyContentUri = false;
      }
    } // browser-request doesn't support File objects because it deep-copies
    // the options using JSON.parse(JSON.stringify(options)). Instead of
    // loading the whole file into memory as a string and letting
    // browser-request base64 encode and then decode it again, we just
    // use XMLHttpRequest directly.
    // (browser-request doesn't support progress either, which is also kind
    // of important here)


    var upload = {
      loaded: 0,
      total: 0
    };
    var promise; // XMLHttpRequest doesn't parse JSON for us. request normally does, but
    // we're setting opts.json=false so that it doesn't JSON-encode the
    // request, which also means it doesn't JSON-decode the response. Either
    // way, we have to JSON-parse the response ourselves.

    var bodyParser = null;

    if (!rawResponse) {
      bodyParser = function bodyParser(rawBody) {
        var body = JSON.parse(rawBody);

        if (onlyContentUri) {
          body = body.content_uri;

          if (body === undefined) {
            throw Error('Bad response');
          }
        }

        return body;
      };
    }

    if (global.XMLHttpRequest) {
      var defer = utils.defer();
      var xhr = new global.XMLHttpRequest();
      upload.xhr = xhr;
      var cb = requestCallback(defer, opts.callback, this.opts.onlyData);

      var timeout_fn = function timeout_fn() {
        xhr.abort();
        cb(new Error('Timeout'));
      }; // set an initial timeout of 30s; we'll advance it each time we get
      // a progress notification


      xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);

      xhr.onreadystatechange = function () {
        var resp;

        switch (xhr.readyState) {
          case global.XMLHttpRequest.DONE:
            callbacks.clearTimeout(xhr.timeout_timer);

            try {
              if (xhr.status === 0) {
                throw new AbortError();
              }

              if (!xhr.responseText) {
                throw new Error('No response body.');
              }

              resp = xhr.responseText;

              if (bodyParser) {
                resp = bodyParser(resp);
              }
            } catch (err) {
              err.http_status = xhr.status;
              cb(err);
              return;
            }

            cb(undefined, xhr, resp);
            break;
        }
      };

      xhr.upload.addEventListener("progress", function (ev) {
        callbacks.clearTimeout(xhr.timeout_timer);
        upload.loaded = ev.loaded;
        upload.total = ev.total;
        xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);

        if (opts.progressHandler) {
          opts.progressHandler({
            loaded: ev.loaded,
            total: ev.total
          });
        }
      });
      var url = this.opts.baseUrl + "/_matrix/media/r0/upload";
      var queryArgs = [];

      if (includeFilename && fileName) {
        queryArgs.push("filename=" + encodeURIComponent(fileName));
      }

      if (!this.useAuthorizationHeader) {
        queryArgs.push("access_token=" + encodeURIComponent(this.opts.accessToken));
      }

      if (queryArgs.length > 0) {
        url += "?" + queryArgs.join("&");
      }

      xhr.open("POST", url);

      if (this.useAuthorizationHeader) {
        xhr.setRequestHeader("Authorization", "Bearer " + this.opts.accessToken);
      }

      xhr.setRequestHeader("Content-Type", contentType);
      xhr.send(body);
      promise = defer.promise; // dirty hack (as per _request) to allow the upload to be cancelled.

      promise.abort = xhr.abort.bind(xhr);
    } else {
      var queryParams = {};

      if (includeFilename && fileName) {
        queryParams.filename = fileName;
      }

      promise = this.authedRequest(opts.callback, "POST", "/upload", queryParams, body, {
        prefix: "/_matrix/media/r0",
        headers: {
          "Content-Type": contentType
        },
        json: false,
        bodyParser: bodyParser
      });
    }

    var self = this; // remove the upload from the list on completion

    var promise0 = promise["finally"](function () {
      for (var i = 0; i < self.uploads.length; ++i) {
        if (self.uploads[i] === upload) {
          self.uploads.splice(i, 1);
          return;
        }
      }
    }); // copy our dirty abort() method to the new promise

    promise0.abort = promise.abort;
    upload.promise = promise0;
    this.uploads.push(upload);
    return promise0;
  },
  cancelUpload: function cancelUpload(promise) {
    if (promise.abort) {
      promise.abort();
      return true;
    }

    return false;
  },
  getCurrentUploads: function getCurrentUploads() {
    return this.uploads;
  },
  idServerRequest: function idServerRequest(callback, method, path, params, prefix, accessToken) {
    if (!this.opts.idBaseUrl) {
      throw new Error("No Identity Server base URL set");
    }

    var fullUri = this.opts.idBaseUrl + prefix + path;

    if (callback !== undefined && !utils.isFunction(callback)) {
      throw Error("Expected callback to be a function but got " + (0, _typeof2["default"])(callback));
    }

    var opts = {
      uri: fullUri,
      method: method,
      withCredentials: false,
      json: true,
      // we want a JSON response if we can
      _matrix_opts: this.opts,
      headers: {}
    };

    if (method === 'GET') {
      opts.qs = params;
    } else if ((0, _typeof2["default"])(params) === "object") {
      opts.json = params;
    }

    if (accessToken) {
      opts.headers['Authorization'] = "Bearer ".concat(accessToken);
    }

    var defer = utils.defer();
    this.opts.request(opts, requestCallback(defer, callback, this.opts.onlyData));
    return defer.promise;
  },

  /**
   * Perform an authorised request to the homeserver.
   * @param {Function} callback Optional. The callback to invoke on
   * success/failure. See the promise return values for more information.
   * @param {string} method The HTTP method e.g. "GET".
   * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.
   * "/createRoom".
   *
   * @param {Object=} queryParams A dict of query params (these will NOT be
   * urlencoded). If unspecified, there will be no query params.
   *
   * @param {Object} [data] The HTTP JSON body.
   *
   * @param {Object|Number=} opts additional options. If a number is specified,
   * this is treated as `opts.localTimeoutMs`.
   *
   * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before
   * timing out the request. If not specified, there is no timeout.
   *
   * @param {sting=} opts.prefix The full prefix to use e.g.
   * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix.
   *
   * @param {Object=} opts.headers map of additional request headers
   *
   * @return {Promise} Resolves to <code>{data: {Object},
   * headers: {Object}, code: {Number}}</code>.
   * If <code>onlyData</code> is set, this will resolve to the <code>data</code>
   * object only.
   * @return {module:http-api.MatrixError} Rejects with an error if a problem
   * occurred. This includes network problems and Matrix-specific error JSON.
   */
  authedRequest: function authedRequest(callback, method, path, queryParams, data, opts) {
    if (!queryParams) {
      queryParams = {};
    }

    if (this.useAuthorizationHeader) {
      if (isFinite(opts)) {
        // opts used to be localTimeoutMs
        opts = {
          localTimeoutMs: opts
        };
      }

      if (!opts) {
        opts = {};
      }

      if (!opts.headers) {
        opts.headers = {};
      }

      if (!opts.headers.Authorization) {
        opts.headers.Authorization = "Bearer " + this.opts.accessToken;
      }

      if (queryParams.access_token) {
        delete queryParams.access_token;
      }
    } else {
      if (!queryParams.access_token) {
        queryParams.access_token = this.opts.accessToken;
      }
    }

    var requestPromise = this.request(callback, method, path, queryParams, data, opts);
    var self = this;
    requestPromise["catch"](function (err) {
      if (err.errcode == 'M_UNKNOWN_TOKEN') {
        self.event_emitter.emit("Session.logged_out", err);
      } else if (err.errcode == 'M_CONSENT_NOT_GIVEN') {
        self.event_emitter.emit("no_consent", err.message, err.data.consent_uri);
      }
    }); // return the original promise, otherwise tests break due to it having to
    // go around the event loop one more time to process the result of the request

    return requestPromise;
  },

  /**
   * Perform a request to the homeserver without any credentials.
   * @param {Function} callback Optional. The callback to invoke on
   * success/failure. See the promise return values for more information.
   * @param {string} method The HTTP method e.g. "GET".
   * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.
   * "/createRoom".
   *
   * @param {Object=} queryParams A dict of query params (these will NOT be
   * urlencoded). If unspecified, there will be no query params.
   *
   * @param {Object} [data] The HTTP JSON body.
   *
   * @param {Object=} opts additional options
   *
   * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before
   * timing out the request. If not specified, there is no timeout.
   *
   * @param {sting=} opts.prefix The full prefix to use e.g.
   * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix.
   *
   * @param {Object=} opts.headers map of additional request headers
   *
   * @return {Promise} Resolves to <code>{data: {Object},
   * headers: {Object}, code: {Number}}</code>.
   * If <code>onlyData</code> is set, this will resolve to the <code>data</code>
   * object only.
   * @return {module:http-api.MatrixError} Rejects with an error if a problem
   * occurred. This includes network problems and Matrix-specific error JSON.
   */
  request: function request(callback, method, path, queryParams, data, opts) {
    opts = opts || {};
    var prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix;
    var fullUri = this.opts.baseUrl + prefix + path;
    return this.requestOtherUrl(callback, method, fullUri, queryParams, data, opts);
  },

  /**
   * Perform a request to an arbitrary URL.
   * @param {Function} callback Optional. The callback to invoke on
   * success/failure. See the promise return values for more information.
   * @param {string} method The HTTP method e.g. "GET".
   * @param {string} uri The HTTP URI
   *
   * @param {Object=} queryParams A dict of query params (these will NOT be
   * urlencoded). If unspecified, there will be no query params.
   *
   * @param {Object} [data] The HTTP JSON body.
   *
   * @param {Object=} opts additional options
   *
   * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before
   * timing out the request. If not specified, there is no timeout.
   *
   * @param {sting=} opts.prefix The full prefix to use e.g.
   * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix.
   *
   * @param {Object=} opts.headers map of additional request headers
   *
   * @return {Promise} Resolves to <code>{data: {Object},
   * headers: {Object}, code: {Number}}</code>.
   * If <code>onlyData</code> is set, this will resolve to the <code>data</code>
   * object only.
   * @return {module:http-api.MatrixError} Rejects with an error if a problem
   * occurred. This includes network problems and Matrix-specific error JSON.
   */
  requestOtherUrl: function requestOtherUrl(callback, method, uri, queryParams, data, opts) {
    if (opts === undefined || opts === null) {
      opts = {};
    } else if (isFinite(opts)) {
      // opts used to be localTimeoutMs
      opts = {
        localTimeoutMs: opts
      };
    }

    return this._request(callback, method, uri, queryParams, data, opts);
  },

  /**
   * Form and return a homeserver request URL based on the given path
   * params and prefix.
   * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.
   * "/createRoom".
   * @param {Object} queryParams A dict of query params (these will NOT be
   * urlencoded).
   * @param {string} prefix The full prefix to use e.g.
   * "/_matrix/client/v2_alpha".
   * @return {string} URL
   */
  getUrl: function getUrl(path, queryParams, prefix) {
    var queryString = "";

    if (queryParams) {
      queryString = "?" + utils.encodeParams(queryParams);
    }

    return this.opts.baseUrl + prefix + path + queryString;
  },

  /**
   * @private
   *
   * @param {function} callback
   * @param {string} method
   * @param {string} uri
   * @param {object} queryParams
   * @param {object|string} data
   * @param {object=} opts
   *
   * @param {boolean} [opts.json =true] Json-encode data before sending, and
   *   decode response on receipt. (We will still json-decode error
   *   responses, even if this is false.)
   *
   * @param {object=} opts.headers  extra request headers
   *
   * @param {number=} opts.localTimeoutMs client-side timeout for the
   *    request. Default timeout if falsy.
   *
   * @param {function=} opts.bodyParser function to parse the body of the
   *    response before passing it to the promise and callback.
   *
   * @return {Promise} a promise which resolves to either the
   * response object (if this.opts.onlyData is truthy), or the parsed
   * body. Rejects
   */
  _request: function _request(callback, method, uri, queryParams, data, opts) {
    if (callback !== undefined && !utils.isFunction(callback)) {
      throw Error("Expected callback to be a function but got " + (0, _typeof2["default"])(callback));
    }

    opts = opts || {};
    var self = this;

    if (this.opts.extraParams) {
      queryParams = _objectSpread(_objectSpread({}, queryParams), this.opts.extraParams);
    }

    var headers = utils.extend({}, opts.headers || {});
    var json = opts.json === undefined ? true : opts.json;
    var bodyParser = opts.bodyParser; // we handle the json encoding/decoding here, because request and
    // browser-request make a mess of it. Specifically, they attempt to
    // json-decode plain-text error responses, which in turn means that the
    // actual error gets swallowed by a SyntaxError.

    if (json) {
      if (data) {
        data = JSON.stringify(data);
        headers['content-type'] = 'application/json';
      }

      if (!headers['accept']) {
        headers['accept'] = 'application/json';
      }

      if (bodyParser === undefined) {
        bodyParser = function bodyParser(rawBody) {
          return JSON.parse(rawBody);
        };
      }
    }

    var defer = utils.defer();
    var timeoutId;
    var timedOut = false;
    var req;
    var localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs;

    var resetTimeout = function resetTimeout() {
      if (localTimeoutMs) {
        if (timeoutId) {
          callbacks.clearTimeout(timeoutId);
        }

        timeoutId = callbacks.setTimeout(function () {
          timedOut = true;

          if (req && req.abort) {
            req.abort();
          }

          defer.reject(new MatrixError({
            error: "Locally timed out waiting for a response",
            errcode: "ORG.MATRIX.JSSDK_TIMEOUT",
            timeout: localTimeoutMs
          }));
        }, localTimeoutMs);
      }
    };

    resetTimeout();
    var reqPromise = defer.promise;

    try {
      req = this.opts.request({
        uri: uri,
        method: method,
        withCredentials: false,
        qs: queryParams,
        qsStringifyOptions: opts.qsStringifyOptions,
        useQuerystring: true,
        body: data,
        json: false,
        timeout: localTimeoutMs,
        headers: headers || {},
        _matrix_opts: this.opts
      }, function (err, response, body) {
        if (localTimeoutMs) {
          callbacks.clearTimeout(timeoutId);

          if (timedOut) {
            return; // already rejected promise
          }
        }

        var handlerFn = requestCallback(defer, callback, self.opts.onlyData, bodyParser);
        handlerFn(err, response, body);
      });

      if (req) {
        // This will only work in a browser, where opts.request is the
        // `browser-request` import. Currently `request` does not support progress
        // updates - see https://github.com/request/request/pull/2346.
        // `browser-request` returns an XHRHttpRequest which exposes `onprogress`
        if ('onprogress' in req) {
          req.onprogress = function (e) {
            // Prevent the timeout from rejecting the deferred promise if progress is
            // seen with the request
            resetTimeout();
          };
        } // FIXME: This is EVIL, but I can't think of a better way to expose
        // abort() operations on underlying HTTP requests :(


        if (req.abort) reqPromise.abort = req.abort.bind(req);
      }
    } catch (ex) {
      defer.reject(ex);

      if (callback) {
        callback(ex);
      }
    }

    return reqPromise;
  }
};
/*
 * Returns a callback that can be invoked by an HTTP request on completion,
 * that will either resolve or reject the given defer as well as invoke the
 * given userDefinedCallback (if any).
 *
 * HTTP errors are transformed into javascript errors and the deferred is rejected.
 *
 * If bodyParser is given, it is used to transform the body of the successful
 * responses before passing to the defer/callback.
 *
 * If onlyData is true, the defer/callback is invoked with the body of the
 * response, otherwise the result object (with `code` and `data` fields)
 *
 */

var requestCallback = function requestCallback(defer, userDefinedCallback, onlyData, bodyParser) {
  userDefinedCallback = userDefinedCallback || function () {};

  return function (err, response, body) {
    if (err) {
      // the unit tests use matrix-mock-request, which throw the string "aborted" when aborting a request.
      // See https://github.com/matrix-org/matrix-mock-request/blob/3276d0263a561b5b8326b47bae720578a2c7473a/src/index.js#L48
      var aborted = err.name === "AbortError" || err === "aborted";

      if (!aborted && !(err instanceof MatrixError)) {
        // browser-request just throws normal Error objects,
        // not `TypeError`s like fetch does. So just assume any
        // error is due to the connection.
        err = new ConnectionError("request failed", err);
      }
    }

    if (!err) {
      try {
        var httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage

        if (httpStatus >= 400) {
          err = parseErrorResponse(response, body);
        } else if (bodyParser) {
          body = bodyParser(body);
        }
      } catch (e) {
        err = new Error("Error parsing server response: ".concat(e));
      }
    }

    if (err) {
      defer.reject(err);
      userDefinedCallback(err);
    } else {
      var res = {
        code: response.status || response.statusCode,
        // XMLHttpRequest vs http.IncomingMessage
        // XXX: why do we bother with this? it doesn't work for
        // XMLHttpRequest, so clearly we don't use it.
        headers: response.headers,
        data: body
      };
      defer.resolve(onlyData ? body : res);
      userDefinedCallback(null, onlyData ? body : res);
    }
  };
};
/**
 * Attempt to turn an HTTP error response into a Javascript Error.
 *
 * If it is a JSON response, we will parse it into a MatrixError. Otherwise
 * we return a generic Error.
 *
 * @param {XMLHttpRequest|http.IncomingMessage} response response object
 * @param {String} body raw body of the response
 * @returns {Error}
 */


function parseErrorResponse(response, body) {
  var httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage

  var contentType = getResponseContentType(response);
  var err;

  if (contentType) {
    if (contentType.type === 'application/json') {
      var jsonBody = (0, _typeof2["default"])(body) === 'object' ? body : JSON.parse(body);
      err = new MatrixError(jsonBody);
    } else if (contentType.type === 'text/plain') {
      err = new Error("Server returned ".concat(httpStatus, " error: ").concat(body));
    }
  }

  if (!err) {
    err = new Error("Server returned ".concat(httpStatus, " error"));
  }

  err.httpStatus = httpStatus;
  return err;
}
/**
 * extract the Content-Type header from the response object, and
 * parse it to a `{type, parameters}` object.
 *
 * returns null if no content-type header could be found.
 *
 * @param {XMLHttpRequest|http.IncomingMessage} response response object
 * @returns {{type: String, parameters: Object}?} parsed content-type header, or null if not found
 */


function getResponseContentType(response) {
  var contentType;

  if (response.getResponseHeader) {
    // XMLHttpRequest provides getResponseHeader
    contentType = response.getResponseHeader("Content-Type");
  } else if (response.headers) {
    // request provides http.IncomingMessage which has a message.headers map
    contentType = response.headers['content-type'] || null;
  }

  if (!contentType) {
    return null;
  }

  try {
    return (0, _contentType.parse)(contentType);
  } catch (e) {
    throw new Error("Error parsing Content-Type '".concat(contentType, "': ").concat(e));
  }
}
/**
 * Construct a Matrix error. This is a JavaScript Error with additional
 * information specific to the standard Matrix error response.
 * @constructor
 * @param {Object} errorJson The Matrix error JSON returned from the homeserver.
 * @prop {string} errcode The Matrix 'errcode' value, e.g. "M_FORBIDDEN".
 * @prop {string} name Same as MatrixError.errcode but with a default unknown string.
 * @prop {string} message The Matrix 'error' value, e.g. "Missing token."
 * @prop {Object} data The raw Matrix error JSON used to construct this object.
 * @prop {integer} httpStatus The numeric HTTP status code given
 */


var MatrixError = /*#__PURE__*/function (_Error) {
  (0, _inherits2["default"])(MatrixError, _Error);

  var _super = _createSuper(MatrixError);

  function MatrixError(errorJson) {
    var _this;

    (0, _classCallCheck2["default"])(this, MatrixError);
    errorJson = errorJson || {};
    _this = _super.call(this, "MatrixError: ".concat(errorJson.errcode));
    _this.errcode = errorJson.errcode;
    _this.name = errorJson.errcode || "Unknown error code";
    _this.message = errorJson.error || "Unknown message";
    _this.data = errorJson;
    return _this;
  }

  return MatrixError;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));
/**
 * Construct a ConnectionError. This is a JavaScript Error indicating
 * that a request failed because of some error with the connection, either
 * CORS was not correctly configured on the server, the server didn't response,
 * the request timed out, or the internet connection on the client side went down.
 * @constructor
 */


exports.MatrixError = MatrixError;

var ConnectionError = /*#__PURE__*/function (_Error2) {
  (0, _inherits2["default"])(ConnectionError, _Error2);

  var _super2 = _createSuper(ConnectionError);

  function ConnectionError(message) {
    var _this2;

    var cause = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
    (0, _classCallCheck2["default"])(this, ConnectionError);
    _this2 = _super2.call(this, message + (cause ? ": ".concat(cause.message) : ""));
    _this2._cause = cause;
    return _this2;
  }

  (0, _createClass2["default"])(ConnectionError, [{
    key: "name",
    get: function get() {
      return "ConnectionError";
    }
  }, {
    key: "cause",
    get: function get() {
      return this._cause;
    }
  }]);
  return ConnectionError;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));

exports.ConnectionError = ConnectionError;

var AbortError = /*#__PURE__*/function (_Error3) {
  (0, _inherits2["default"])(AbortError, _Error3);

  var _super3 = _createSuper(AbortError);

  function AbortError() {
    (0, _classCallCheck2["default"])(this, AbortError);
    return _super3.call(this, "Operation aborted");
  }

  (0, _createClass2["default"])(AbortError, [{
    key: "name",
    get: function get() {
      return "AbortError";
    }
  }]);
  return AbortError;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));
/**
 * Retries a network operation run in a callback.
 * @param  {number}   maxAttempts maximum attempts to try
 * @param  {Function} callback    callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.
 * @return {any} the result of the network operation
 * @throws {ConnectionError} If after maxAttempts the callback still throws ConnectionError
 */


exports.AbortError = AbortError;

function retryNetworkOperation(_x, _x2) {
  return _retryNetworkOperation.apply(this, arguments);
}

function _retryNetworkOperation() {
  _retryNetworkOperation = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(maxAttempts, callback) {
    var attempts, lastConnectionError;
    return _regenerator["default"].wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            attempts = 0;
            lastConnectionError = null;

          case 2:
            if (!(attempts < maxAttempts)) {
              _context2.next = 21;
              break;
            }

            _context2.prev = 3;

            if (!(attempts > 0)) {
              _context2.next = 6;
              break;
            }

            return _context2.delegateYield( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
              var timeout;
              return _regenerator["default"].wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      timeout = 1000 * Math.pow(2, attempts);

                      _logger.logger.log("network operation failed ".concat(attempts, " times,") + " retrying in ".concat(timeout, "ms..."));

                      _context.next = 4;
                      return new Promise(function (r) {
                        return setTimeout(r, timeout);
                      });

                    case 4:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            })(), "t0", 6);

          case 6:
            _context2.next = 8;
            return callback();

          case 8:
            return _context2.abrupt("return", _context2.sent);

          case 11:
            _context2.prev = 11;
            _context2.t1 = _context2["catch"](3);

            if (!(_context2.t1 instanceof ConnectionError)) {
              _context2.next = 18;
              break;
            }

            attempts += 1;
            lastConnectionError = _context2.t1;
            _context2.next = 19;
            break;

          case 18:
            throw _context2.t1;

          case 19:
            _context2.next = 2;
            break;

          case 21:
            throw lastConnectionError;

          case 22:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[3, 11]]);
  }));
  return _retryNetworkOperation.apply(this, arguments);
}

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./logger":106,"./realtime-callbacks":124,"./utils":137,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/typeof":24,"@babel/runtime/helpers/wrapNativeSuper":26,"@babel/runtime/regenerator":27,"content-type":35}],104:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.exists = exists;

/*
Copyright 2019 New Vector Ltd

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

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

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

/**
 * Check if an IndexedDB database exists. The only way to do so is to try opening it, so
 * we do that and then delete it did not exist before.
 *
 * @param {Object} indexedDB The `indexedDB` interface
 * @param {string} dbName The database name to test for
 * @returns {boolean} Whether the database exists
 */
function exists(indexedDB, dbName) {
  return new Promise(function (resolve, reject) {
    var exists = true;
    var req = indexedDB.open(dbName);

    req.onupgradeneeded = function () {
      // Since we did not provide an explicit version when opening, this event
      // should only fire if the DB did not exist before at any version.
      exists = false;
    };

    req.onblocked = function () {
      return reject();
    };

    req.onsuccess = function () {
      var db = req.result;
      db.close();

      if (!exists) {
        // The DB did not exist before, but has been created as part of this
        // existence check. Delete it now to restore previous state. Delete can
        // actually take a while to complete in some browsers, so don't wait for
        // it. This won't block future open calls that a store might issue next to
        // properly set up the DB.
        indexedDB.deleteDatabase(dbName);
      }

      resolve(exists);
    };

    req.onerror = function (ev) {
      return reject(ev.target.error);
    };
  });
}

},{}],105:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InteractiveAuth = InteractiveAuth;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _url = _interopRequireDefault(require("url"));

var utils = _interopRequireWildcard(require("./utils"));

var _logger = require("./logger");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var EMAIL_STAGE_TYPE = "m.login.email.identity";
var MSISDN_STAGE_TYPE = "m.login.msisdn";
/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 * <p>Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 * <p>Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Also passes a
 *     second deprecated arg which is a flag set to true if this request
 *     is a background request. The busyChanged callback should be used
 *     instead of the backfround flag. Should return a promise which resolves
 *     to the successful response or rejects with a MatrixError.
 *
 * @param {function(bool): Promise} opts.busyChanged
 *     called whenever the interactive auth logic becomes busy submitting
 *     information provided by the user or finsihes. After this has been
 *     called with true the UI should indicate that a request is in progress
 *     until it is called again with false.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 * @param {function?} opts.requestEmailToken A function that takes the email address (string),
 *     clientSecret (string), attempt number (int) and sessionId (string) and calls the
 *     relevant requestToken function and returns the promise returned by that function.
 *     If the resulting promise rejects, the rejection will propagate through to the
 *     attemptAuth promise.
 *
 */

function InteractiveAuth(opts) {
  this._matrixClient = opts.matrixClient;
  this._data = opts.authData || {};
  this._requestCallback = opts.doRequest;
  this._busyChangedCallback = opts.busyChanged; // startAuthStage included for backwards compat

  this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
  this._resolveFunc = null;
  this._rejectFunc = null;
  this._inputs = opts.inputs || {};
  this._requestEmailTokenCallback = opts.requestEmailToken;
  if (opts.sessionId) this._data.session = opts.sessionId;
  this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
  this._emailSid = opts.emailSid;
  if (this._emailSid === undefined) this._emailSid = null;
  this._requestingEmailToken = false;
  this._chosenFlow = null;
  this._currentStage = null; // if we are currently trying to submit an auth dict (which includes polling)
  // the promise the will resolve/reject when it completes

  this._submitPromise = null;
}

InteractiveAuth.prototype = {
  /**
   * begin the authentication process.
   *
   * @return {Promise} which resolves to the response on success,
   * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
   *     no suitable authentication flow can be found
   */
  attemptAuth: function attemptAuth() {
    var _this = this;

    // This promise will be quite long-lived and will resolve when the
    // request is authenticated and completes successfully.
    return new Promise(function (resolve, reject) {
      _this._resolveFunc = resolve;
      _this._rejectFunc = reject;
      var hasFlows = _this._data && _this._data.flows; // if we have no flows, try a request to acquire the flows

      if (!hasFlows) {
        if (_this._busyChangedCallback) _this._busyChangedCallback(true); // use the existing sessionid, if one is present.

        var auth = null;

        if (_this._data.session) {
          auth = {
            session: _this._data.session
          };
        }

        _this._doRequest(auth)["finally"](function () {
          if (_this._busyChangedCallback) _this._busyChangedCallback(false);
        });
      } else {
        _this._startNextAuthStage();
      }
    });
  },

  /**
   * Poll to check if the auth session or current stage has been
   * completed out-of-band. If so, the attemptAuth promise will
   * be resolved.
   */
  poll: function () {
    var _poll = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var authDict, creds, idServerParsedUrl;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (this._data.session) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

            case 2:
              if (this._resolveFunc) {
                _context.next = 4;
                break;
              }

              return _context.abrupt("return");

            case 4:
              if (!this._submitPromise) {
                _context.next = 6;
                break;
              }

              return _context.abrupt("return");

            case 6:
              authDict = {};

              if (!(this._currentStage == EMAIL_STAGE_TYPE)) {
                _context.next = 16;
                break;
              }

              if (!this._emailSid) {
                _context.next = 16;
                break;
              }

              creds = {
                sid: this._emailSid,
                client_secret: this._clientSecret
              };
              _context.next = 12;
              return this._matrixClient.doesServerRequireIdServerParam();

            case 12:
              if (!_context.sent) {
                _context.next = 15;
                break;
              }

              idServerParsedUrl = _url["default"].parse(this._matrixClient.getIdentityServerUrl());
              creds.id_server = idServerParsedUrl.host;

            case 15:
              authDict = {
                type: EMAIL_STAGE_TYPE,
                // TODO: Remove `threepid_creds` once servers support proper UIA
                // See https://github.com/matrix-org/synapse/issues/5665
                // See https://github.com/matrix-org/matrix-doc/issues/2220
                threepid_creds: creds,
                threepidCreds: creds
              };

            case 16:
              this.submitAuthDict(authDict, true);

            case 17:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    function poll() {
      return _poll.apply(this, arguments);
    }

    return poll;
  }(),

  /**
   * get the auth session ID
   *
   * @return {string} session id
   */
  getSessionId: function getSessionId() {
    return this._data ? this._data.session : undefined;
  },

  /**
   * get the client secret used for validation sessions
   * with the ID server.
   *
   * @return {string} client secret
   */
  getClientSecret: function getClientSecret() {
    return this._clientSecret;
  },

  /**
   * get the server params for a given stage
   *
   * @param {string} loginType login type for the stage
   * @return {object?} any parameters from the server for this stage
   */
  getStageParams: function getStageParams(loginType) {
    var params = {};

    if (this._data && this._data.params) {
      params = this._data.params;
    }

    return params[loginType];
  },
  getChosenFlow: function getChosenFlow() {
    return this._chosenFlow;
  },

  /**
   * submit a new auth dict and fire off the request. This will either
   * make attemptAuth resolve/reject, or cause the startAuthStage callback
   * to be called for a new stage.
   *
   * @param {object} authData new auth dict to send to the server. Should
   *    include a `type` propterty denoting the login type, as well as any
   *    other params for that stage.
   * @param {bool} background If true, this request failing will not result
   *    in the attemptAuth promise being rejected. This can be set to true
   *    for requests that just poll to see if auth has been completed elsewhere.
   */
  submitAuthDict: function () {
    var _submitAuthDict = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(authData, background) {
      var auth;
      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (this._resolveFunc) {
                _context2.next = 2;
                break;
              }

              throw new Error("submitAuthDict() called before attemptAuth()");

            case 2:
              if (!background && this._busyChangedCallback) {
                this._busyChangedCallback(true);
              } // if we're currently trying a request, wait for it to finish
              // as otherwise we can get multiple 200 responses which can mean
              // things like multiple logins for register requests.
              // (but discard any expections as we only care when its done,
              // not whether it worked or not)


            case 3:
              if (!this._submitPromise) {
                _context2.next = 13;
                break;
              }

              _context2.prev = 4;
              _context2.next = 7;
              return this._submitPromise;

            case 7:
              _context2.next = 11;
              break;

            case 9:
              _context2.prev = 9;
              _context2.t0 = _context2["catch"](4);

            case 11:
              _context2.next = 3;
              break;

            case 13:
              if (this._data.session) {
                auth = {
                  session: this._data.session
                };
                utils.extend(auth, authData);
              } else {
                auth = authData;
              }

              _context2.prev = 14;
              // NB. the 'background' flag is deprecated by the busyChanged
              // callback and is here for backwards compat
              this._submitPromise = this._doRequest(auth, background);
              _context2.next = 18;
              return this._submitPromise;

            case 18:
              _context2.prev = 18;
              this._submitPromise = null;

              if (!background && this._busyChangedCallback) {
                this._busyChangedCallback(false);
              }

              return _context2.finish(18);

            case 22:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, this, [[4, 9], [14,, 18, 22]]);
    }));

    function submitAuthDict(_x, _x2) {
      return _submitAuthDict.apply(this, arguments);
    }

    return submitAuthDict;
  }(),

  /**
   * Gets the sid for the email validation session
   * Specific to m.login.email.identity
   *
   * @returns {string} The sid of the email auth session
   */
  getEmailSid: function getEmailSid() {
    return this._emailSid;
  },

  /**
   * Sets the sid for the email validation session
   * This must be set in order to successfully poll for completion
   * of the email validation.
   * Specific to m.login.email.identity
   *
   * @param {string} sid The sid for the email validation session
   */
  setEmailSid: function setEmailSid(sid) {
    this._emailSid = sid;
  },

  /**
   * Fire off a request, and either resolve the promise, or call
   * startAuthStage.
   *
   * @private
   * @param {object?} auth new auth dict, including session id
   * @param {bool?} background If true, this request is a background poll, so it
   *    failing will not result in the attemptAuth promise being rejected.
   *    This can be set to true for requests that just poll to see if auth has
   *    been completed elsewhere.
   */
  _doRequest: function () {
    var _doRequest2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(auth, background) {
      var result, errorFlows, haveFlows, requestTokenResult;
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              _context3.next = 3;
              return this._requestCallback(auth, background);

            case 3:
              result = _context3.sent;

              this._resolveFunc(result);

              this._resolveFunc = null;
              this._rejectFunc = null;
              _context3.next = 34;
              break;

            case 9:
              _context3.prev = 9;
              _context3.t0 = _context3["catch"](0);
              // sometimes UI auth errors don't come with flows
              errorFlows = _context3.t0.data ? _context3.t0.data.flows : null;
              haveFlows = this._data.flows || Boolean(errorFlows);

              if (_context3.t0.httpStatus !== 401 || !_context3.t0.data || !haveFlows) {
                // doesn't look like an interactive-auth failure.
                if (!background) {
                  this._rejectFunc(_context3.t0);
                } else {
                  // We ignore all failures here (even non-UI auth related ones)
                  // since we don't want to suddenly fail if the internet connection
                  // had a blip whilst we were polling
                  _logger.logger.log("Background poll request failed doing UI auth: ignoring", _context3.t0);
                }
              } // if the error didn't come with flows, completed flows or session ID,
              // copy over the ones we have. Synapse sometimes sends responses without
              // any UI auth data (eg. when polling for email validation, if the email
              // has not yet been validated). This appears to be a Synapse bug, which
              // we workaround here.


              if (!_context3.t0.data.flows && !_context3.t0.data.completed && !_context3.t0.data.session) {
                _context3.t0.data.flows = this._data.flows;
                _context3.t0.data.completed = this._data.completed;
                _context3.t0.data.session = this._data.session;
              }

              this._data = _context3.t0.data;

              try {
                this._startNextAuthStage();
              } catch (e) {
                this._rejectFunc(e);

                this._resolveFunc = null;
                this._rejectFunc = null;
              }

              if (!(!this._emailSid && !this._requestingEmailToken && this._chosenFlow.stages.includes('m.login.email.identity'))) {
                _context3.next = 34;
                break;
              }

              // If we've picked a flow with email auth, we send the email
              // now because we want the request to fail as soon as possible
              // if the email address is not valid (ie. already taken or not
              // registered, depending on what the operation is).
              this._requestingEmailToken = true;
              _context3.prev = 19;
              _context3.next = 22;
              return this._requestEmailTokenCallback(this._inputs.emailAddress, this._clientSecret, 1, // TODO: Multiple send attempts?
              this._data.session);

            case 22:
              requestTokenResult = _context3.sent;
              this._emailSid = requestTokenResult.sid; // NB. promise is not resolved here - at some point, doRequest
              // will be called again and if the user has jumped through all
              // the hoops correctly, auth will be complete and the request
              // will succeed.
              // Also, we should expose the fact that this request has compledted
              // so clients can know that the email has actually been sent.

              _context3.next = 31;
              break;

            case 26:
              _context3.prev = 26;
              _context3.t1 = _context3["catch"](19);

              // we failed to request an email token, so fail the request.
              // This could be due to the email already beeing registered
              // (or not being registered, depending on what we're trying
              // to do) or it could be a network failure. Either way, pass
              // the failure up as the user can't complete auth if we can't
              // send the email, for whatever reason.
              this._rejectFunc(_context3.t1);

              this._resolveFunc = null;
              this._rejectFunc = null;

            case 31:
              _context3.prev = 31;
              this._requestingEmailToken = false;
              return _context3.finish(31);

            case 34:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, this, [[0, 9], [19, 26, 31, 34]]);
    }));

    function _doRequest(_x3, _x4) {
      return _doRequest2.apply(this, arguments);
    }

    return _doRequest;
  }(),

  /**
   * Pick the next stage and call the callback
   *
   * @private
   * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
   */
  _startNextAuthStage: function _startNextAuthStage() {
    var nextStage = this._chooseStage();

    if (!nextStage) {
      throw new Error("No incomplete flows from the server");
    }

    this._currentStage = nextStage;

    if (nextStage === 'm.login.dummy') {
      this.submitAuthDict({
        type: 'm.login.dummy'
      });
      return;
    }

    if (this._data && this._data.errcode || this._data.error) {
      this._stateUpdatedCallback(nextStage, {
        errcode: this._data.errcode || "",
        error: this._data.error || ""
      });

      return;
    }

    var stageStatus = {};

    if (nextStage == EMAIL_STAGE_TYPE) {
      stageStatus.emailSid = this._emailSid;
    }

    this._stateUpdatedCallback(nextStage, stageStatus);
  },

  /**
   * Pick the next auth stage
   *
   * @private
   * @return {string?} login type
   * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
   */
  _chooseStage: function _chooseStage() {
    if (this._chosenFlow === null) {
      this._chosenFlow = this._chooseFlow();
    }

    _logger.logger.log("Active flow => %s", JSON.stringify(this._chosenFlow));

    var nextStage = this._firstUncompletedStage(this._chosenFlow);

    _logger.logger.log("Next stage: %s", nextStage);

    return nextStage;
  },

  /**
   * Pick one of the flows from the returned list
   * If a flow using all of the inputs is found, it will
   * be returned, otherwise, null will be returned.
   *
   * Only flows using all given inputs are chosen because it
   * is likley to be surprising if the user provides a
   * credential and it is not used. For example, for registration,
   * this could result in the email not being used which would leave
   * the account with no means to reset a password.
   *
   * @private
   * @return {object} flow
   * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
   */
  _chooseFlow: function _chooseFlow() {
    var flows = this._data.flows || []; // we've been given an email or we've already done an email part

    var haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
    var haveMsisdn = Boolean(this._inputs.phoneCountry) && Boolean(this._inputs.phoneNumber);

    var _iterator = _createForOfIteratorHelper(flows),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var flow = _step.value;
        var flowHasEmail = false;
        var flowHasMsisdn = false;

        var _iterator2 = _createForOfIteratorHelper(flow.stages),
            _step2;

        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var stage = _step2.value;

            if (stage === EMAIL_STAGE_TYPE) {
              flowHasEmail = true;
            } else if (stage == MSISDN_STAGE_TYPE) {
              flowHasMsisdn = true;
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }

        if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
          return flow;
        }
      } // Throw an error with a fairly generic description, but with more
      // information such that the app can give a better one if so desired.

    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    var err = new Error("No appropriate authentication flow found");
    err.name = 'NoAuthFlowFoundError';
    err.required_stages = [];
    if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
    if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
    err.available_flows = flows;
    throw err;
  },

  /**
   * Get the first uncompleted stage in the given flow
   *
   * @private
   * @param {object} flow
   * @return {string} login type
   */
  _firstUncompletedStage: function _firstUncompletedStage(flow) {
    var completed = (this._data || {}).completed || [];

    for (var i = 0; i < flow.stages.length; ++i) {
      var stageType = flow.stages[i];

      if (completed.indexOf(stageType) === -1) {
        return stageType;
      }
    }
  }
};

},{"./logger":106,"./utils":137,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27,"url":56}],106:[function(require,module,exports){
"use strict";
/*
Copyright 2018 André Jaenisch
Copyright 2019, 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
/**
 * @module logger
 */
const loglevel_1 = __importDefault(require("loglevel"));
// This is to demonstrate, that you can use any namespace you want.
// Namespaces allow you to turn on/off the logging for specific parts of the
// application.
// An idea would be to control this via an environment variable (on Node.js).
// See https://www.npmjs.com/package/debug to see how this could be implemented
// Part of #332 is introducing a logging library in the first place.
const DEFAULT_NAMESPACE = "matrix";
// because rageshakes in react-sdk hijack the console log, also at module load time,
// initializing the logger here races with the initialization of rageshakes.
// to avoid the issue, we override the methodFactory of loglevel that binds to the
// console methods at initialization time by a factory that looks up the console methods
// when logging so we always get the current value of console methods.
loglevel_1.default.methodFactory = function (methodName, logLevel, loggerName) {
    return function (...args) {
        /* eslint-disable @typescript-eslint/no-invalid-this */
        if (this.prefix) {
            args.unshift(this.prefix);
        }
        /* eslint-enable @typescript-eslint/no-invalid-this */
        const supportedByConsole = methodName === "error" ||
            methodName === "warn" ||
            methodName === "trace" ||
            methodName === "info";
        /* eslint-disable no-console */
        if (supportedByConsole) {
            return console[methodName](...args);
        }
        else {
            return console.log(...args);
        }
        /* eslint-enable no-console */
    };
};
/**
 * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}.
 * Can be tailored down to specific use cases if needed.
 */
exports.logger = loglevel_1.default.getLogger(DEFAULT_NAMESPACE);
exports.logger.setLevel(loglevel_1.default.levels.DEBUG);
function extendLogger(logger) {
    logger.withPrefix = function (prefix) {
        const existingPrefix = this.prefix || "";
        return getPrefixedLogger(existingPrefix + prefix);
    };
}
extendLogger(exports.logger);
function getPrefixedLogger(prefix) {
    const prefixLogger = loglevel_1.default.getLogger(`${DEFAULT_NAMESPACE}-${prefix}`);
    if (prefixLogger.prefix !== prefix) {
        // Only do this setup work the first time through, as loggers are saved by name.
        extendLogger(prefixLogger);
        prefixLogger.prefix = prefix;
        prefixLogger.setLevel(loglevel_1.default.levels.DEBUG);
    }
    return prefixLogger;
}

},{"loglevel":38}],107:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2015-2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClient = exports.setCryptoStoreFactory = exports.wrapRequest = exports.getRequest = exports.request = exports.setMatrixCallVideoInput = exports.setMatrixCallAudioInput = exports.createNewMatrixCall = exports.ContentHelpers = void 0;
const memory_crypto_store_1 = require("./crypto/store/memory-crypto-store");
const memory_1 = require("./store/memory");
const scheduler_1 = require("./scheduler");
const client_1 = require("./client");
__exportStar(require("./client"), exports);
__exportStar(require("./http-api"), exports);
__exportStar(require("./autodiscovery"), exports);
__exportStar(require("./sync-accumulator"), exports);
__exportStar(require("./errors"), exports);
__exportStar(require("./models/event"), exports);
__exportStar(require("./models/room"), exports);
__exportStar(require("./models/group"), exports);
__exportStar(require("./models/event-timeline"), exports);
__exportStar(require("./models/event-timeline-set"), exports);
__exportStar(require("./models/room-member"), exports);
__exportStar(require("./models/room-state"), exports);
__exportStar(require("./models/user"), exports);
__exportStar(require("./scheduler"), exports);
__exportStar(require("./filter"), exports);
__exportStar(require("./timeline-window"), exports);
__exportStar(require("./interactive-auth"), exports);
__exportStar(require("./service-types"), exports);
__exportStar(require("./store/memory"), exports);
__exportStar(require("./store/indexeddb"), exports);
__exportStar(require("./store/session/webstorage"), exports);
__exportStar(require("./crypto/store/memory-crypto-store"), exports);
__exportStar(require("./crypto/store/indexeddb-crypto-store"), exports);
__exportStar(require("./content-repo"), exports);
exports.ContentHelpers = __importStar(require("./content-helpers"));
var call_1 = require("./webrtc/call");
Object.defineProperty(exports, "createNewMatrixCall", { enumerable: true, get: function () { return call_1.createNewMatrixCall; } });
Object.defineProperty(exports, "setMatrixCallAudioInput", { enumerable: true, get: function () { return call_1.setAudioInput; } });
Object.defineProperty(exports, "setMatrixCallVideoInput", { enumerable: true, get: function () { return call_1.setVideoInput; } });
// expose the underlying request object so different environments can use
// different request libs (e.g. request or browser-request)
let requestInstance;
/**
 * The function used to perform HTTP requests. Only use this if you want to
 * use a different HTTP library, e.g. Angular's <code>$http</code>. This should
 * be set prior to calling {@link createClient}.
 * @param {requestFunction} r The request function to use.
 */
function request(r) {
    requestInstance = r;
}
exports.request = request;
/**
 * Return the currently-set request function.
 * @return {requestFunction} The current request function.
 */
function getRequest() {
    return requestInstance;
}
exports.getRequest = getRequest;
/**
 * Apply wrapping code around the request function. The wrapper function is
 * installed as the new request handler, and when invoked it is passed the
 * previous value, along with the options and callback arguments.
 * @param {requestWrapperFunction} wrapper The wrapping function.
 */
function wrapRequest(wrapper) {
    const origRequest = requestInstance;
    requestInstance = function (options, callback) {
        return wrapper(origRequest, options, callback);
    };
}
exports.wrapRequest = wrapRequest;
let cryptoStoreFactory = () => new memory_crypto_store_1.MemoryCryptoStore;
/**
 * Configure a different factory to be used for creating crypto stores
 *
 * @param {Function} fac  a function which will return a new
 *    {@link module:crypto.store.base~CryptoStore}.
 */
function setCryptoStoreFactory(fac) {
    cryptoStoreFactory = fac;
}
exports.setCryptoStoreFactory = setCryptoStoreFactory;
/**
 * Construct a Matrix Client. Similar to {@link module:client.MatrixClient}
 * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.
 * @param {(Object|string)} opts The configuration options for this client. If
 * this is a string, it is assumed to be the base URL. These configuration
 * options will be passed directly to {@link module:client.MatrixClient}.
 * @param {Object} opts.store If not set, defaults to
 * {@link module:store/memory.MemoryStore}.
 * @param {Object} opts.scheduler If not set, defaults to
 * {@link module:scheduler~MatrixScheduler}.
 * @param {requestFunction} opts.request If not set, defaults to the function
 * supplied to {@link request} which defaults to the request module from NPM.
 *
 * @param {module:crypto.store.base~CryptoStore=} opts.cryptoStore
 *    crypto store implementation. Calls the factory supplied to
 *    {@link setCryptoStoreFactory} if unspecified; or if no factory has been
 *    specified, uses a default implementation (indexeddb in the browser,
 *    in-memory otherwise).
 *
 * @return {MatrixClient} A new matrix client.
 * @see {@link module:client.MatrixClient} for the full list of options for
 * <code>opts</code>.
 */
function createClient(opts) {
    if (typeof opts === "string") {
        opts = {
            "baseUrl": opts,
        };
    }
    opts.request = opts.request || requestInstance;
    opts.store = opts.store || new memory_1.MemoryStore({
        localStorage: global.localStorage,
    });
    opts.scheduler = opts.scheduler || new scheduler_1.MatrixScheduler();
    opts.cryptoStore = opts.cryptoStore || cryptoStoreFactory();
    return new client_1.MatrixClient(opts);
}
exports.createClient = createClient;
/**
 * The request function interface for performing HTTP requests. This matches the
 * API for the {@link https://github.com/request/request#requestoptions-callback|
 * request NPM module}. The SDK will attempt to call this function in order to
 * perform an HTTP request.
 * @callback requestFunction
 * @param {Object} opts The options for this HTTP request.
 * @param {string} opts.uri The complete URI.
 * @param {string} opts.method The HTTP method.
 * @param {Object} opts.qs The query parameters to append to the URI.
 * @param {Object} opts.body The JSON-serializable object.
 * @param {boolean} opts.json True if this is a JSON request.
 * @param {Object} opts._matrix_opts The underlying options set for
 * {@link MatrixHttpApi}.
 * @param {requestCallback} callback The request callback.
 */
/**
 * A wrapper for the request function interface.
 * @callback requestWrapperFunction
 * @param {requestFunction} origRequest The underlying request function being
 * wrapped
 * @param {Object} opts The options for this HTTP request, given in the same
 * form as {@link requestFunction}.
 * @param {requestCallback} callback The request callback.
 */
/**
  * The request callback interface for performing HTTP requests. This matches the
  * API for the {@link https://github.com/request/request#requestoptions-callback|
  * request NPM module}. The SDK will implement a callback which meets this
  * interface in order to handle the HTTP response.
  * @callback requestCallback
  * @param {Error} err The error if one occurred, else falsey.
  * @param {Object} response The HTTP response which consists of
  * <code>{statusCode: {Number}, headers: {Object}}</code>
  * @param {Object} body The parsed HTTP response body.
  */

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./autodiscovery":62,"./client":64,"./content-helpers":65,"./content-repo":66,"./crypto/store/indexeddb-crypto-store":88,"./crypto/store/memory-crypto-store":90,"./errors":99,"./filter":102,"./http-api":103,"./interactive-auth":105,"./models/event":113,"./models/event-timeline":112,"./models/event-timeline-set":111,"./models/group":114,"./models/room":119,"./models/room-member":116,"./models/room-state":117,"./models/user":121,"./scheduler":125,"./service-types":126,"./store/indexeddb":129,"./store/memory":130,"./store/session/webstorage":131,"./sync-accumulator":133,"./timeline-window":136,"./webrtc/call":138}],108:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MSC3089Branch = void 0;
const event_1 = require("../@types/event");
/**
 * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference
 * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes
 * without notice.
 */
class MSC3089Branch {
    constructor(client, indexEvent) {
        this.client = client;
        this.indexEvent = indexEvent;
        // Nothing to do
    }
    /**
     * The file ID.
     */
    get id() {
        return this.indexEvent.getStateKey();
    }
    /**
     * Whether this branch is active/valid.
     */
    get isActive() {
        return this.indexEvent.getContent()["active"] === true;
    }
    get roomId() {
        return this.indexEvent.getRoomId();
    }
    /**
     * Deletes the file from the tree.
     * @returns {Promise<void>} Resolves when complete.
     */
    delete() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, {}, this.id);
            yield this.client.redactEvent(this.roomId, this.id);
            // TODO: Delete edit history as well
        });
    }
    /**
     * Gets the name for this file.
     * @returns {string} The name, or "Unnamed File" if unknown.
     */
    getName() {
        return this.indexEvent.getContent()['name'] || "Unnamed File";
    }
    /**
     * Sets the name for this file.
     * @param {string} name The new name for this file.
     * @returns {Promise<void>} Resolves when complete.
     */
    setName(name) {
        return this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, Object.assign(Object.assign({}, this.indexEvent.getContent()), { name: name }), this.id);
    }
    /**
     * Gets information about the file needed to download it.
     * @returns {Promise<{info: IEncryptedFile, httpUrl: string}>} Information about the file.
     */
    getFileInfo() {
        return __awaiter(this, void 0, void 0, function* () {
            const room = this.client.getRoom(this.roomId);
            if (!room)
                throw new Error("Unknown room");
            const timeline = yield this.client.getEventTimeline(room.getUnfilteredTimelineSet(), this.id);
            if (!timeline)
                throw new Error("Failed to get timeline for room event");
            const event = timeline.getEvents().find(e => e.getId() === this.id);
            if (!event)
                throw new Error("Failed to find event");
            // Sometimes the event context doesn't decrypt for us, so do that.
            yield this.client.decryptEventIfNeeded(event, { emit: false, isRetry: false });
            const file = event.getContent()['file'];
            const httpUrl = this.client.mxcUrlToHttp(file['url']);
            return { info: file, httpUrl: httpUrl };
        });
    }
}
exports.MSC3089Branch = MSC3089Branch;

},{"../@types/event":58}],109:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MSC3089TreeSpace = exports.TreePermissions = exports.DEFAULT_TREE_POWER_LEVELS_TEMPLATE = void 0;
const event_1 = require("../@types/event");
const logger_1 = require("../logger");
const utils_1 = require("../utils");
const MSC3089Branch_1 = require("./MSC3089Branch");
const p_retry_1 = __importDefault(require("p-retry"));
const megolm_1 = require("../crypto/algorithms/megolm");
/**
 * The recommended defaults for a tree space's power levels. Note that this
 * is UNSTABLE and subject to breaking changes without notice.
 */
exports.DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {
    // Owner
    invite: 100,
    kick: 100,
    ban: 100,
    // Editor
    redact: 50,
    state_default: 50,
    events_default: 50,
    // Viewer
    users_default: 0,
    // Mixed
    events: {
        [event_1.EventType.RoomPowerLevels]: 100,
        [event_1.EventType.RoomHistoryVisibility]: 100,
        [event_1.EventType.RoomTombstone]: 100,
        [event_1.EventType.RoomEncryption]: 100,
        [event_1.EventType.RoomName]: 50,
        [event_1.EventType.RoomMessage]: 50,
        [event_1.EventType.RoomMessageEncrypted]: 50,
        [event_1.EventType.Sticker]: 50,
    },
    users: {},
};
/**
 * Ease-of-use representation for power levels represented as simple roles.
 * Note that this is UNSTABLE and subject to breaking changes without notice.
 */
var TreePermissions;
(function (TreePermissions) {
    TreePermissions["Viewer"] = "viewer";
    TreePermissions["Editor"] = "editor";
    TreePermissions["Owner"] = "owner";
})(TreePermissions = exports.TreePermissions || (exports.TreePermissions = {}));
/**
 * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)
 * file tree Space. Note that this is UNSTABLE and subject to breaking changes
 * without notice.
 */
class MSC3089TreeSpace {
    constructor(client, roomId) {
        this.client = client;
        this.roomId = roomId;
        this.room = this.client.getRoom(this.roomId);
        if (!this.room)
            throw new Error("Unknown room");
    }
    /**
     * Syntactic sugar for room ID of the Space.
     */
    get id() {
        return this.roomId;
    }
    /**
     * Whether or not this is a top level space.
     */
    get isTopLevel() {
        // XXX: This is absolutely not how you find out if the space is top level
        // but is safe for a managed usecase like we offer in the SDK.
        const parentEvents = this.room.currentState.getStateEvents(event_1.EventType.SpaceParent);
        if (!(parentEvents === null || parentEvents === void 0 ? void 0 : parentEvents.length))
            return true;
        return parentEvents.every(e => { var _a; return !((_a = e.getContent()) === null || _a === void 0 ? void 0 : _a['via']); });
    }
    /**
     * Sets the name of the tree space.
     * @param {string} name The new name for the space.
     * @returns {Promise<void>} Resolves when complete.
     */
    setName(name) {
        return this.client.sendStateEvent(this.roomId, event_1.EventType.RoomName, { name }, "");
    }
    /**
     * Invites a user to the tree space. They will be given the default Viewer
     * permission level unless specified elsewhere.
     * @param {string} userId The user ID to invite.
     * @param {boolean} andSubspaces True (default) to invite the user to all
     * directories/subspaces too, recursively.
     * @param {boolean} shareHistoryKeys True (default) to share encryption keys
     * with the invited user. This will allow them to decrypt the events (files)
     * in the tree. Keys will not be shared if the room is lacking appropriate
     * history visibility (by default, history visibility is "shared" in trees,
     * which is an appropriate visibility for these purposes).
     * @returns {Promise<void>} Resolves when complete.
     */
    invite(userId, andSubspaces = true, shareHistoryKeys = true) {
        return __awaiter(this, void 0, void 0, function* () {
            const promises = [this.retryInvite(userId)];
            if (andSubspaces) {
                promises.push(...this.getDirectories().map(d => d.invite(userId, andSubspaces, shareHistoryKeys)));
            }
            return Promise.all(promises).then(() => {
                // Note: key sharing is default on because for file trees it is relatively important that the invite
                // target can actually decrypt the files. The implied use case is that by inviting a user to the tree
                // it means the sender would like the receiver to view/download the files contained within, much like
                // sharing a folder in other circles.
                if (shareHistoryKeys && megolm_1.isRoomSharedHistory(this.room)) {
                    // noinspection JSIgnoredPromiseFromCall - we aren't concerned as much if this fails.
                    this.client.sendSharedHistoryKeys(this.roomId, [userId]);
                }
            });
        });
    }
    retryInvite(userId) {
        return utils_1.simpleRetryOperation(() => __awaiter(this, void 0, void 0, function* () {
            yield this.client.invite(this.roomId, userId).catch(e => {
                // We don't want to retry permission errors forever...
                if ((e === null || e === void 0 ? void 0 : e.errcode) === "M_FORBIDDEN") {
                    throw new p_retry_1.default.AbortError(e);
                }
                throw e;
            });
        }));
    }
    /**
     * Sets the permissions of a user to the given role. Note that if setting a user
     * to Owner then they will NOT be able to be demoted. If the user does not have
     * permission to change the power level of the target, an error will be thrown.
     * @param {string} userId The user ID to change the role of.
     * @param {TreePermissions} role The role to assign.
     * @returns {Promise<void>} Resolves when complete.
     */
    setPermissions(userId, role) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const currentPls = this.room.currentState.getStateEvents(event_1.EventType.RoomPowerLevels, "");
            if (Array.isArray(currentPls))
                throw new Error("Unexpected return type for power levels");
            const pls = currentPls.getContent() || {};
            const viewLevel = pls['users_default'] || 0;
            const editLevel = pls['events_default'] || 50;
            const adminLevel = ((_a = pls['events']) === null || _a === void 0 ? void 0 : _a[event_1.EventType.RoomPowerLevels]) || 100;
            const users = pls['users'] || {};
            switch (role) {
                case TreePermissions.Viewer:
                    users[userId] = viewLevel;
                    break;
                case TreePermissions.Editor:
                    users[userId] = editLevel;
                    break;
                case TreePermissions.Owner:
                    users[userId] = adminLevel;
                    break;
                default:
                    throw new Error("Invalid role: " + role);
            }
            pls['users'] = users;
            return this.client.sendStateEvent(this.roomId, event_1.EventType.RoomPowerLevels, pls, "");
        });
    }
    /**
     * Creates a directory under this tree space, represented as another tree space.
     * @param {string} name The name for the directory.
     * @returns {Promise<MSC3089TreeSpace>} Resolves to the created directory.
     */
    createDirectory(name) {
        return __awaiter(this, void 0, void 0, function* () {
            const directory = yield this.client.unstableCreateFileTree(name);
            yield this.client.sendStateEvent(this.roomId, event_1.EventType.SpaceChild, {
                via: [this.client.getDomain()],
            }, directory.roomId);
            yield this.client.sendStateEvent(directory.roomId, event_1.EventType.SpaceParent, {
                via: [this.client.getDomain()],
            }, this.roomId);
            return directory;
        });
    }
    /**
     * Gets a list of all known immediate subdirectories to this tree space.
     * @returns {MSC3089TreeSpace[]} The tree spaces (directories). May be empty, but not null.
     */
    getDirectories() {
        const trees = [];
        const children = this.room.currentState.getStateEvents(event_1.EventType.SpaceChild);
        for (const child of children) {
            try {
                const tree = this.client.unstableGetFileTreeSpace(child.getStateKey());
                if (tree)
                    trees.push(tree);
            }
            catch (e) {
                logger_1.logger.warn("Unable to create tree space instance for listing. Are we joined?", e);
            }
        }
        return trees;
    }
    /**
     * Gets a subdirectory of a given ID under this tree space. Note that this will not recurse
     * into children and instead only look one level deep.
     * @param {string} roomId The room ID (directory ID) to find.
     * @returns {MSC3089TreeSpace} The directory, or falsy if not found.
     */
    getDirectory(roomId) {
        return this.getDirectories().find(r => r.roomId === roomId);
    }
    /**
     * Deletes the tree, kicking all members and deleting **all subdirectories**.
     * @returns {Promise<void>} Resolves when complete.
     */
    delete() {
        return __awaiter(this, void 0, void 0, function* () {
            const subdirectories = this.getDirectories();
            for (const dir of subdirectories) {
                yield dir.delete();
            }
            const kickMemberships = ["invite", "knock", "join"];
            const members = this.room.currentState.getStateEvents(event_1.EventType.RoomMember);
            for (const member of members) {
                const isNotUs = member.getStateKey() !== this.client.getUserId();
                if (isNotUs && kickMemberships.includes(member.getContent()['membership'])) {
                    yield this.client.kick(this.roomId, member.getStateKey(), "Room deleted");
                }
            }
            yield this.client.leave(this.roomId);
        });
    }
    getOrderedChildren(children) {
        const ordered = children
            .map(c => ({ roomId: c.getStateKey(), order: c.getContent()['order'] }));
        ordered.sort((a, b) => {
            var _a, _b, _c, _d;
            if (a.order && !b.order) {
                return -1;
            }
            else if (!a.order && b.order) {
                return 1;
            }
            else if (!a.order && !b.order) {
                const roomA = this.client.getRoom(a.roomId);
                const roomB = this.client.getRoom(b.roomId);
                if (!roomA || !roomB) { // just don't bother trying to do more partial sorting
                    return utils_1.lexicographicCompare(a.roomId, b.roomId);
                }
                const createTsA = (_b = (_a = roomA.currentState.getStateEvents(event_1.EventType.RoomCreate, "")) === null || _a === void 0 ? void 0 : _a.getTs()) !== null && _b !== void 0 ? _b : 0;
                const createTsB = (_d = (_c = roomB.currentState.getStateEvents(event_1.EventType.RoomCreate, "")) === null || _c === void 0 ? void 0 : _c.getTs()) !== null && _d !== void 0 ? _d : 0;
                if (createTsA === createTsB) {
                    return utils_1.lexicographicCompare(a.roomId, b.roomId);
                }
                return createTsA - createTsB;
            }
            else { // both not-null orders
                return utils_1.lexicographicCompare(a.order, b.order);
            }
        });
        return ordered;
    }
    getParentRoom() {
        const parents = this.room.currentState.getStateEvents(event_1.EventType.SpaceParent);
        const parent = parents[0]; // XXX: Wild assumption
        if (!parent)
            throw new Error("Expected to have a parent in a non-top level space");
        // XXX: We are assuming the parent is a valid tree space.
        // We probably don't need to validate the parent room state for this usecase though.
        const parentRoom = this.client.getRoom(parent.getStateKey());
        if (!parentRoom)
            throw new Error("Unable to locate room for parent");
        return parentRoom;
    }
    /**
     * Gets the current order index for this directory. Note that if this is the top level space
     * then -1 will be returned.
     * @returns {number} The order index of this space.
     */
    getOrder() {
        if (this.isTopLevel)
            return -1;
        const parentRoom = this.getParentRoom();
        const children = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild);
        const ordered = this.getOrderedChildren(children);
        return ordered.findIndex(c => c.roomId === this.roomId);
    }
    /**
     * Sets the order index for this directory within its parent. Note that if this is a top level
     * space then an error will be thrown. -1 can be used to move the child to the start, and numbers
     * larger than the number of children can be used to move the child to the end.
     * @param {number} index The new order index for this space.
     * @returns {Promise<void>} Resolves when complete.
     * @throws Throws if this is a top level space.
     */
    setOrder(index) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            if (this.isTopLevel)
                throw new Error("Cannot set order of top level spaces currently");
            const parentRoom = this.getParentRoom();
            const children = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild);
            const ordered = this.getOrderedChildren(children);
            index = Math.max(Math.min(index, ordered.length - 1), 0);
            const currentIndex = this.getOrder();
            const movingUp = currentIndex < index;
            if (movingUp && index === (ordered.length - 1)) {
                index--;
            }
            else if (!movingUp && index === 0) {
                index++;
            }
            const prev = ordered[movingUp ? index : (index - 1)];
            const next = ordered[movingUp ? (index + 1) : index];
            let newOrder = utils_1.DEFAULT_ALPHABET[0];
            let ensureBeforeIsSane = false;
            if (!prev) {
                // Move to front
                if (next === null || next === void 0 ? void 0 : next.order) {
                    newOrder = utils_1.prevString(next.order);
                }
            }
            else if (index === (ordered.length - 1)) {
                // Move to back
                if (next === null || next === void 0 ? void 0 : next.order) {
                    newOrder = utils_1.nextString(next.order);
                }
            }
            else {
                // Move somewhere in the middle
                const startOrder = prev === null || prev === void 0 ? void 0 : prev.order;
                const endOrder = next === null || next === void 0 ? void 0 : next.order;
                if (startOrder && endOrder) {
                    if (startOrder === endOrder) {
                        // Error case: just move +1 to break out of awful math
                        newOrder = utils_1.nextString(startOrder);
                    }
                    else {
                        newOrder = utils_1.averageBetweenStrings(startOrder, endOrder);
                    }
                }
                else {
                    if (startOrder) {
                        // We're at the end (endOrder is null, so no explicit order)
                        newOrder = utils_1.nextString(startOrder);
                    }
                    else if (endOrder) {
                        // We're at the start (startOrder is null, so nothing before us)
                        newOrder = utils_1.prevString(endOrder);
                    }
                    else {
                        // Both points are unknown. We're likely in a range where all the children
                        // don't have particular order values, so we may need to update them too.
                        // The other possibility is there's only us as a child, but we should have
                        // shown up in the other states.
                        ensureBeforeIsSane = true;
                    }
                }
            }
            if (ensureBeforeIsSane) {
                // We were asked by the order algorithm to prepare the moving space for a landing
                // in the undefined order part of the order array, which means we need to update the
                // spaces that come before it with a stable order value.
                let lastOrder;
                for (let i = 0; i <= index; i++) {
                    const target = ordered[i];
                    if (i === 0) {
                        lastOrder = target.order;
                    }
                    if (!target.order) {
                        // XXX: We should be creating gaps to avoid conflicts
                        lastOrder = lastOrder ? utils_1.nextString(lastOrder) : utils_1.DEFAULT_ALPHABET[0];
                        const currentChild = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild, target.roomId);
                        const content = (_a = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _a !== void 0 ? _a : { via: [this.client.getDomain()] };
                        yield this.client.sendStateEvent(parentRoom.roomId, event_1.EventType.SpaceChild, Object.assign(Object.assign({}, content), { order: lastOrder }), target.roomId);
                    }
                    else {
                        lastOrder = target.order;
                    }
                }
                newOrder = utils_1.nextString(lastOrder);
            }
            // TODO: Deal with order conflicts by reordering
            // Now we can finally update our own order state
            const currentChild = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild, this.roomId);
            const content = (_b = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _b !== void 0 ? _b : { via: [this.client.getDomain()] };
            yield this.client.sendStateEvent(parentRoom.roomId, event_1.EventType.SpaceChild, Object.assign(Object.assign({}, content), { 
                // TODO: Safely constrain to 50 character limit required by spaces.
                order: newOrder }), this.roomId);
        });
    }
    /**
     * Creates (uploads) a new file to this tree. The file must have already been encrypted for the room.
     * @param {string} name The name of the file.
     * @param {ArrayBuffer} encryptedContents The encrypted contents.
     * @param {Partial<IEncryptedFile>} info The encrypted file information.
     * @returns {Promise<void>} Resolves when uploaded.
     */
    createFile(name, encryptedContents, info) {
        return __awaiter(this, void 0, void 0, function* () {
            const mxc = yield this.client.uploadContent(new Blob([encryptedContents]), {
                includeFilename: false,
                onlyContentUri: true,
            });
            info.url = mxc;
            const res = yield this.client.sendMessage(this.roomId, {
                msgtype: event_1.MsgType.File,
                body: name,
                url: mxc,
                file: info,
                [event_1.UNSTABLE_MSC3089_LEAF.name]: {},
            });
            yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, {
                active: true,
                name: name,
            }, res['event_id']);
        });
    }
    /**
     * Retrieves a file from the tree.
     * @param {string} fileEventId The event ID of the file.
     * @returns {MSC3089Branch} The file, or falsy if not found.
     */
    getFile(fileEventId) {
        const branch = this.room.currentState.getStateEvents(event_1.UNSTABLE_MSC3089_BRANCH.name, fileEventId);
        return branch ? new MSC3089Branch_1.MSC3089Branch(this.client, branch) : null;
    }
    /**
     * Gets an array of all known files for the tree.
     * @returns {MSC3089Branch[]} The known files. May be empty, but not null.
     */
    listFiles() {
        var _a;
        const branches = (_a = this.room.currentState.getStateEvents(event_1.UNSTABLE_MSC3089_BRANCH.name)) !== null && _a !== void 0 ? _a : [];
        return branches.map(e => new MSC3089Branch_1.MSC3089Branch(this.client, e)).filter(b => b.isActive);
    }
}
exports.MSC3089TreeSpace = MSC3089TreeSpace;

},{"../@types/event":58,"../crypto/algorithms/megolm":77,"../logger":106,"../utils":137,"./MSC3089Branch":108,"p-retry":39}],110:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventContext = void 0;
const event_timeline_1 = require("./event-timeline");
/**
 * @module models/event-context
 */
class EventContext {
    /**
     * Construct a new EventContext
     *
     * An eventcontext is used for circumstances such as search results, when we
     * have a particular event of interest, and a bunch of events before and after
     * it.
     *
     * It also stores pagination tokens for going backwards and forwards in the
     * timeline.
     *
     * @param {MatrixEvent} ourEvent  the event at the centre of this context
     *
     * @constructor
     */
    constructor(ourEvent) {
        this.ourEventIndex = 0;
        this.paginateTokens = {
            [event_timeline_1.Direction.Backward]: null,
            [event_timeline_1.Direction.Forward]: null,
        };
        this.timeline = [ourEvent];
    }
    /**
     * Get the main event of interest
     *
     * This is a convenience function for getTimeline()[getOurEventIndex()].
     *
     * @return {MatrixEvent} The event at the centre of this context.
     */
    getEvent() {
        return this.timeline[this.ourEventIndex];
    }
    /**
     * Get the list of events in this context
     *
     * @return {Array} An array of MatrixEvents
     */
    getTimeline() {
        return this.timeline;
    }
    /**
     * Get the index in the timeline of our event
     *
     * @return {Number}
     */
    getOurEventIndex() {
        return this.ourEventIndex;
    }
    /**
     * Get a pagination token.
     *
     * @param {boolean} backwards   true to get the pagination token for going
     *                                  backwards in time
     * @return {string}
     */
    getPaginateToken(backwards = false) {
        return this.paginateTokens[backwards ? event_timeline_1.Direction.Backward : event_timeline_1.Direction.Forward];
    }
    /**
     * Set a pagination token.
     *
     * Generally this will be used only by the matrix js sdk.
     *
     * @param {string} token        pagination token
     * @param {boolean} backwards   true to set the pagination token for going
     *                                   backwards in time
     */
    setPaginateToken(token, backwards = false) {
        this.paginateTokens[backwards ? event_timeline_1.Direction.Backward : event_timeline_1.Direction.Forward] = token;
    }
    /**
     * Add more events to the timeline
     *
     * @param {Array} events      new events, in timeline order
     * @param {boolean} atStart   true to insert new events at the start
     */
    addEvents(events, atStart = false) {
        // TODO: should we share logic with Room.addEventsToTimeline?
        // Should Room even use EventContext?
        if (atStart) {
            this.timeline = events.concat(this.timeline);
            this.ourEventIndex += events.length;
        }
        else {
            this.timeline = this.timeline.concat(events);
        }
    }
}
exports.EventContext = EventContext;

},{"./event-timeline":112}],111:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventTimelineSet = void 0;
/**
 * @module models/event-timeline-set
 */
const events_1 = require("events");
const event_timeline_1 = require("./event-timeline");
const event_1 = require("./event");
const logger_1 = require("../logger");
const relations_1 = require("./relations");
// var DEBUG = false;
const DEBUG = true;
let debuglog;
if (DEBUG) {
    // using bind means that we get to keep useful line numbers in the console
    debuglog = logger_1.logger.log.bind(logger_1.logger);
}
else {
    debuglog = function () { };
}
class EventTimelineSet extends events_1.EventEmitter {
    /**
     * Construct a set of EventTimeline objects, typically on behalf of a given
     * room.  A room may have multiple EventTimelineSets for different levels
     * of filtering.  The global notification list is also an EventTimelineSet, but
     * lacks a room.
     *
     * <p>This is an ordered sequence of timelines, which may or may not
     * be continuous. Each timeline lists a series of events, as well as tracking
     * the room state at the start and the end of the timeline (if appropriate).
     * It also tracks forward and backward pagination tokens, as well as containing
     * links to the next timeline in the sequence.
     *
     * <p>There is one special timeline - the 'live' timeline, which represents the
     * timeline to which events are being added in real-time as they are received
     * from the /sync API. Note that you should not retain references to this
     * timeline - even if it is the current timeline right now, it may not remain
     * so if the server gives us a timeline gap in /sync.
     *
     * <p>In order that we can find events from their ids later, we also maintain a
     * map from event_id to timeline and index.
     *
     * @constructor
     * @param {?Room} room
     * Room for this timelineSet. May be null for non-room cases, such as the
     * notification timeline.
     * @param {Object} opts Options inherited from Room.
     *
     * @param {boolean} [opts.timelineSupport = false]
     * Set to true to enable improved timeline support.
     * @param {Object} [opts.filter = null]
     * The filter object, if any, for this timelineSet.
     * @param {boolean} [opts.unstableClientRelationAggregation = false]
     * Optional. Set to true to enable client-side aggregation of event relations
     * via `getRelationsForEvent`.
     * This feature is currently unstable and the API may change without notice.
     */
    constructor(room, opts) {
        super();
        this.room = room;
        this.timelineSupport = Boolean(opts.timelineSupport);
        this.liveTimeline = new event_timeline_1.EventTimeline(this);
        this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;
        // just a list - *not* ordered.
        this.timelines = [this.liveTimeline];
        this._eventIdToTimeline = {};
        this.filter = opts.filter;
        if (this.unstableClientRelationAggregation) {
            // A tree of objects to access a set of relations for an event, as in:
            // this.relations[relatesToEventId][relationType][relationEventType]
            this.relations = {};
        }
    }
    /**
     * Get all the timelines in this set
     * @return {module:models/event-timeline~EventTimeline[]} the timelines in this set
     */
    getTimelines() {
        return this.timelines;
    }
    /**
     * Get the filter object this timeline set is filtered on, if any
     * @return {?Filter} the optional filter for this timelineSet
     */
    getFilter() {
        return this.filter;
    }
    /**
     * Set the filter object this timeline set is filtered on
     * (passed to the server when paginating via /messages).
     * @param {Filter} filter the filter for this timelineSet
     */
    setFilter(filter) {
        this.filter = filter;
    }
    /**
     * Get the list of pending sent events for this timelineSet's room, filtered
     * by the timelineSet's filter if appropriate.
     *
     * @return {module:models/event.MatrixEvent[]} A list of the sent events
     * waiting for remote echo.
     *
     * @throws If <code>opts.pendingEventOrdering</code> was not 'detached'
     */
    getPendingEvents() {
        if (!this.room) {
            return [];
        }
        if (this.filter) {
            return this.filter.filterRoomTimeline(this.room.getPendingEvents());
        }
        else {
            return this.room.getPendingEvents();
        }
    }
    /**
     * Get the live timeline for this room.
     *
     * @return {module:models/event-timeline~EventTimeline} live timeline
     */
    getLiveTimeline() {
        return this.liveTimeline;
    }
    /**
     * Return the timeline (if any) this event is in.
     * @param {String} eventId the eventId being sought
     * @return {module:models/event-timeline~EventTimeline} timeline
     */
    eventIdToTimeline(eventId) {
        return this._eventIdToTimeline[eventId];
    }
    /**
     * Track a new event as if it were in the same timeline as an old event,
     * replacing it.
     * @param {String} oldEventId  event ID of the original event
     * @param {String} newEventId  event ID of the replacement event
     */
    replaceEventId(oldEventId, newEventId) {
        const existingTimeline = this._eventIdToTimeline[oldEventId];
        if (existingTimeline) {
            delete this._eventIdToTimeline[oldEventId];
            this._eventIdToTimeline[newEventId] = existingTimeline;
        }
    }
    /**
     * Reset the live timeline, and start a new one.
     *
     * <p>This is used when /sync returns a 'limited' timeline.
     *
     * @param {string=} backPaginationToken   token for back-paginating the new timeline
     * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline,
     * if absent or null, all timelines are reset.
     *
     * @fires module:client~MatrixClient#event:"Room.timelineReset"
     */
    resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
        // Each EventTimeline has RoomState objects tracking the state at the start
        // and end of that timeline. The copies at the end of the live timeline are
        // special because they will have listeners attached to monitor changes to
        // the current room state, so we move this RoomState from the end of the
        // current live timeline to the end of the new one and, if necessary,
        // replace it with a newly created one. We also make a copy for the start
        // of the new timeline.
        // if timeline support is disabled, forget about the old timelines
        const resetAllTimelines = !this.timelineSupport || !forwardPaginationToken;
        const oldTimeline = this.liveTimeline;
        const newTimeline = resetAllTimelines ?
            oldTimeline.forkLive(event_timeline_1.EventTimeline.FORWARDS) :
            oldTimeline.fork(event_timeline_1.EventTimeline.FORWARDS);
        if (resetAllTimelines) {
            this.timelines = [newTimeline];
            this._eventIdToTimeline = {};
        }
        else {
            this.timelines.push(newTimeline);
        }
        if (forwardPaginationToken) {
            // Now set the forward pagination token on the old live timeline
            // so it can be forward-paginated.
            oldTimeline.setPaginationToken(forwardPaginationToken, event_timeline_1.EventTimeline.FORWARDS);
        }
        // make sure we set the pagination token before firing timelineReset,
        // otherwise clients which start back-paginating will fail, and then get
        // stuck without realising that they *can* back-paginate.
        newTimeline.setPaginationToken(backPaginationToken, event_timeline_1.EventTimeline.BACKWARDS);
        // Now we can swap the live timeline to the new one.
        this.liveTimeline = newTimeline;
        this.emit("Room.timelineReset", this.room, this, resetAllTimelines);
    }
    /**
     * Get the timeline which contains the given event, if any
     *
     * @param {string} eventId  event ID to look for
     * @return {?module:models/event-timeline~EventTimeline} timeline containing
     * the given event, or null if unknown
     */
    getTimelineForEvent(eventId) {
        const res = this._eventIdToTimeline[eventId];
        return (res === undefined) ? null : res;
    }
    /**
     * Get an event which is stored in our timelines
     *
     * @param {string} eventId  event ID to look for
     * @return {?module:models/event~MatrixEvent} the given event, or undefined if unknown
     */
    findEventById(eventId) {
        const tl = this.getTimelineForEvent(eventId);
        if (!tl) {
            return undefined;
        }
        return tl.getEvents().find(function (ev) {
            return ev.getId() == eventId;
        });
    }
    /**
     * Add a new timeline to this timeline list
     *
     * @return {module:models/event-timeline~EventTimeline} newly-created timeline
     */
    addTimeline() {
        if (!this.timelineSupport) {
            throw new Error("timeline support is disabled. Set the 'timelineSupport'" +
                " parameter to true when creating MatrixClient to enable" +
                " it.");
        }
        const timeline = new event_timeline_1.EventTimeline(this);
        this.timelines.push(timeline);
        return timeline;
    }
    /**
     * Add events to a timeline
     *
     * <p>Will fire "Room.timeline" for each event added.
     *
     * @param {MatrixEvent[]} events A list of events to add.
     *
     * @param {boolean} toStartOfTimeline   True to add these events to the start
     * (oldest) instead of the end (newest) of the timeline. If true, the oldest
     * event will be the <b>last</b> element of 'events'.
     *
     * @param {module:models/event-timeline~EventTimeline} timeline   timeline to
     *    add events to.
     *
     * @param {string=} paginationToken   token for the next batch of events
     *
     * @fires module:client~MatrixClient#event:"Room.timeline"
     *
     */
    addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken) {
        if (!timeline) {
            throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");
        }
        if (!toStartOfTimeline && timeline == this.liveTimeline) {
            throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to " +
                "the live timeline - use Room.addLiveEvents instead");
        }
        if (this.filter) {
            events = this.filter.filterRoomTimeline(events);
            if (!events.length) {
                return;
            }
        }
        const direction = toStartOfTimeline ? event_timeline_1.EventTimeline.BACKWARDS :
            event_timeline_1.EventTimeline.FORWARDS;
        const inverseDirection = toStartOfTimeline ? event_timeline_1.EventTimeline.FORWARDS :
            event_timeline_1.EventTimeline.BACKWARDS;
        // Adding events to timelines can be quite complicated. The following
        // illustrates some of the corner-cases.
        //
        // Let's say we start by knowing about four timelines. timeline3 and
        // timeline4 are neighbours:
        //
        //    timeline1    timeline2    timeline3    timeline4
        //      [M]          [P]          [S] <------> [T]
        //
        // Now we paginate timeline1, and get the following events from the server:
        // [M, N, P, R, S, T, U].
        //
        // 1. First, we ignore event M, since we already know about it.
        //
        // 2. Next, we append N to timeline 1.
        //
        // 3. Next, we don't add event P, since we already know about it,
        //    but we do link together the timelines. We now have:
        //
        //    timeline1    timeline2    timeline3    timeline4
        //      [M, N] <---> [P]          [S] <------> [T]
        //
        // 4. Now we add event R to timeline2:
        //
        //    timeline1    timeline2    timeline3    timeline4
        //      [M, N] <---> [P, R]       [S] <------> [T]
        //
        //    Note that we have switched the timeline we are working on from
        //    timeline1 to timeline2.
        //
        // 5. We ignore event S, but again join the timelines:
        //
        //    timeline1    timeline2    timeline3    timeline4
        //      [M, N] <---> [P, R] <---> [S] <------> [T]
        //
        // 6. We ignore event T, and the timelines are already joined, so there
        //    is nothing to do.
        //
        // 7. Finally, we add event U to timeline4:
        //
        //    timeline1    timeline2    timeline3    timeline4
        //      [M, N] <---> [P, R] <---> [S] <------> [T, U]
        //
        // The important thing to note in the above is what happened when we
        // already knew about a given event:
        //
        //   - if it was appropriate, we joined up the timelines (steps 3, 5).
        //   - in any case, we started adding further events to the timeline which
        //       contained the event we knew about (steps 3, 5, 6).
        //
        //
        // So much for adding events to the timeline. But what do we want to do
        // with the pagination token?
        //
        // In the case above, we will be given a pagination token which tells us how to
        // get events beyond 'U' - in this case, it makes sense to store this
        // against timeline4. But what if timeline4 already had 'U' and beyond? in
        // that case, our best bet is to throw away the pagination token we were
        // given and stick with whatever token timeline4 had previously. In short,
        // we want to only store the pagination token if the last event we receive
        // is one we didn't previously know about.
        //
        // We make an exception for this if it turns out that we already knew about
        // *all* of the events, and we weren't able to join up any timelines. When
        // that happens, it means our existing pagination token is faulty, since it
        // is only telling us what we already know. Rather than repeatedly
        // paginating with the same token, we might as well use the new pagination
        // token in the hope that we eventually work our way out of the mess.
        let didUpdate = false;
        let lastEventWasNew = false;
        for (let i = 0; i < events.length; i++) {
            const event = events[i];
            const eventId = event.getId();
            const existingTimeline = this._eventIdToTimeline[eventId];
            if (!existingTimeline) {
                // we don't know about this event yet. Just add it to the timeline.
                this.addEventToTimeline(event, timeline, toStartOfTimeline);
                lastEventWasNew = true;
                didUpdate = true;
                continue;
            }
            lastEventWasNew = false;
            if (existingTimeline == timeline) {
                debuglog("Event " + eventId + " already in timeline " + timeline);
                continue;
            }
            const neighbour = timeline.getNeighbouringTimeline(direction);
            if (neighbour) {
                // this timeline already has a neighbour in the relevant direction;
                // let's assume the timelines are already correctly linked up, and
                // skip over to it.
                //
                // there's probably some edge-case here where we end up with an
                // event which is in a timeline a way down the chain, and there is
                // a break in the chain somewhere. But I can't really imagine how
                // that would happen, so I'm going to ignore it for now.
                //
                if (existingTimeline == neighbour) {
                    debuglog("Event " + eventId + " in neighbouring timeline - " +
                        "switching to " + existingTimeline);
                }
                else {
                    debuglog("Event " + eventId + " already in a different " +
                        "timeline " + existingTimeline);
                }
                timeline = existingTimeline;
                continue;
            }
            // time to join the timelines.
            logger_1.logger.info("Already have timeline for " + eventId +
                " - joining timeline " + timeline + " to " +
                existingTimeline);
            // Variables to keep the line length limited below.
            const existingIsLive = existingTimeline === this.liveTimeline;
            const timelineIsLive = timeline === this.liveTimeline;
            const backwardsIsLive = direction === event_timeline_1.EventTimeline.BACKWARDS && existingIsLive;
            const forwardsIsLive = direction === event_timeline_1.EventTimeline.FORWARDS && timelineIsLive;
            if (backwardsIsLive || forwardsIsLive) {
                // The live timeline should never be spliced into a non-live position.
                // We use independent logging to better discover the problem at a glance.
                if (backwardsIsLive) {
                    logger_1.logger.warn("Refusing to set a preceding existingTimeLine on our " +
                        "timeline as the existingTimeLine is live (" + existingTimeline + ")");
                }
                if (forwardsIsLive) {
                    logger_1.logger.warn("Refusing to set our preceding timeline on a existingTimeLine " +
                        "as our timeline is live (" + timeline + ")");
                }
                continue; // abort splicing - try next event
            }
            timeline.setNeighbouringTimeline(existingTimeline, direction);
            existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);
            timeline = existingTimeline;
            didUpdate = true;
        }
        // see above - if the last event was new to us, or if we didn't find any
        // new information, we update the pagination token for whatever
        // timeline we ended up on.
        if (lastEventWasNew || !didUpdate) {
            if (direction === event_timeline_1.EventTimeline.FORWARDS && timeline === this.liveTimeline) {
                logger_1.logger.warn({ lastEventWasNew, didUpdate }); // for debugging
                logger_1.logger.warn(`Refusing to set forwards pagination token of live timeline ` +
                    `${timeline} to ${paginationToken}`);
                return;
            }
            timeline.setPaginationToken(paginationToken, direction);
        }
    }
    /**
     * Add an event to the end of this live timeline.
     *
     * @param {MatrixEvent} event Event to be added
     * @param {string?} duplicateStrategy 'ignore' or 'replace'
     * @param {boolean} fromCache whether the sync response came from cache
     */
    addLiveEvent(event, duplicateStrategy, fromCache = false) {
        if (this.filter) {
            const events = this.filter.filterRoomTimeline([event]);
            if (!events.length) {
                return;
            }
        }
        const timeline = this._eventIdToTimeline[event.getId()];
        if (timeline) {
            if (duplicateStrategy === "replace") {
                debuglog("EventTimelineSet.addLiveEvent: replacing duplicate event " +
                    event.getId());
                const tlEvents = timeline.getEvents();
                for (let j = 0; j < tlEvents.length; j++) {
                    if (tlEvents[j].getId() === event.getId()) {
                        // still need to set the right metadata on this event
                        event_timeline_1.EventTimeline.setEventMetadata(event, timeline.getState(event_timeline_1.EventTimeline.FORWARDS), false);
                        tlEvents[j] = event;
                        // XXX: we need to fire an event when this happens.
                        break;
                    }
                }
            }
            else {
                debuglog("EventTimelineSet.addLiveEvent: ignoring duplicate event " +
                    event.getId());
            }
            return;
        }
        this.addEventToTimeline(event, this.liveTimeline, false, fromCache);
    }
    /**
     * Add event to the given timeline, and emit Room.timeline. Assumes
     * we have already checked we don't know about this event.
     *
     * Will fire "Room.timeline" for each event added.
     *
     * @param {MatrixEvent} event
     * @param {EventTimeline} timeline
     * @param {boolean} toStartOfTimeline
     * @param {boolean} fromCache whether the sync response came from cache
     *
     * @fires module:client~MatrixClient#event:"Room.timeline"
     */
    addEventToTimeline(event, timeline, toStartOfTimeline, fromCache = false) {
        const eventId = event.getId();
        timeline.addEvent(event, toStartOfTimeline);
        this._eventIdToTimeline[eventId] = timeline;
        this.setRelationsTarget(event);
        this.aggregateRelations(event);
        const data = {
            timeline: timeline,
            liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache,
        };
        this.emit("Room.timeline", event, this.room, Boolean(toStartOfTimeline), false, data);
    }
    /**
     * Replaces event with ID oldEventId with one with newEventId, if oldEventId is
     * recognised.  Otherwise, add to the live timeline.  Used to handle remote echos.
     *
     * @param {MatrixEvent} localEvent     the new event to be added to the timeline
     * @param {String} oldEventId          the ID of the original event
     * @param {boolean} newEventId         the ID of the replacement event
     *
     * @fires module:client~MatrixClient#event:"Room.timeline"
     */
    handleRemoteEcho(localEvent, oldEventId, newEventId) {
        // XXX: why don't we infer newEventId from localEvent?
        const existingTimeline = this._eventIdToTimeline[oldEventId];
        if (existingTimeline) {
            delete this._eventIdToTimeline[oldEventId];
            this._eventIdToTimeline[newEventId] = existingTimeline;
        }
        else {
            if (this.filter) {
                if (this.filter.filterRoomTimeline([localEvent]).length) {
                    this.addEventToTimeline(localEvent, this.liveTimeline, false);
                }
            }
            else {
                this.addEventToTimeline(localEvent, this.liveTimeline, false);
            }
        }
    }
    /**
     * Removes a single event from this room.
     *
     * @param {String} eventId  The id of the event to remove
     *
     * @return {?MatrixEvent} the removed event, or null if the event was not found
     * in this room.
     */
    removeEvent(eventId) {
        const timeline = this._eventIdToTimeline[eventId];
        if (!timeline) {
            return null;
        }
        const removed = timeline.removeEvent(eventId);
        if (removed) {
            delete this._eventIdToTimeline[eventId];
            const data = {
                timeline: timeline,
            };
            this.emit("Room.timeline", removed, this.room, undefined, true, data);
        }
        return removed;
    }
    /**
     * Determine where two events appear in the timeline relative to one another
     *
     * @param {string} eventId1   The id of the first event
     * @param {string} eventId2   The id of the second event

     * @return {?number} a number less than zero if eventId1 precedes eventId2, and
     *    greater than zero if eventId1 succeeds eventId2. zero if they are the
     *    same event; null if we can't tell (either because we don't know about one
     *    of the events, or because they are in separate timelines which don't join
     *    up).
     */
    compareEventOrdering(eventId1, eventId2) {
        if (eventId1 == eventId2) {
            // optimise this case
            return 0;
        }
        const timeline1 = this._eventIdToTimeline[eventId1];
        const timeline2 = this._eventIdToTimeline[eventId2];
        if (timeline1 === undefined) {
            return null;
        }
        if (timeline2 === undefined) {
            return null;
        }
        if (timeline1 === timeline2) {
            // both events are in the same timeline - figure out their
            // relative indices
            let idx1;
            let idx2;
            const events = timeline1.getEvents();
            for (let idx = 0; idx < events.length &&
                (idx1 === undefined || idx2 === undefined); idx++) {
                const evId = events[idx].getId();
                if (evId == eventId1) {
                    idx1 = idx;
                }
                if (evId == eventId2) {
                    idx2 = idx;
                }
            }
            return idx1 - idx2;
        }
        // the events are in different timelines. Iterate through the
        // linkedlist to see which comes first.
        // first work forwards from timeline1
        let tl = timeline1;
        while (tl) {
            if (tl === timeline2) {
                // timeline1 is before timeline2
                return -1;
            }
            tl = tl.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS);
        }
        // now try backwards from timeline1
        tl = timeline1;
        while (tl) {
            if (tl === timeline2) {
                // timeline2 is before timeline1
                return 1;
            }
            tl = tl.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS);
        }
        // the timelines are not contiguous.
        return null;
    }
    /**
     * Get a collection of relations to a given event in this timeline set.
     *
     * @param {String} eventId
     * The ID of the event that you'd like to access relation events for.
     * For example, with annotations, this would be the ID of the event being annotated.
     * @param {String} relationType
     * The type of relation involved, such as "m.annotation", "m.reference", "m.replace", etc.
     * @param {String} eventType
     * The relation event's type, such as "m.reaction", etc.
     * @throws If <code>eventId</code>, <code>relationType</code> or <code>eventType</code>
     * are not valid.
     *
     * @returns {?Relations}
     * A container for relation events or undefined if there are no relation events for
     * the relationType.
     */
    getRelationsForEvent(eventId, relationType, eventType) {
        if (!this.unstableClientRelationAggregation) {
            throw new Error("Client-side relation aggregation is disabled");
        }
        if (!eventId || !relationType || !eventType) {
            throw new Error("Invalid arguments for `getRelationsForEvent`");
        }
        // debuglog("Getting relations for: ", eventId, relationType, eventType);
        const relationsForEvent = this.relations[eventId] || {};
        const relationsWithRelType = relationsForEvent[relationType] || {};
        return relationsWithRelType[eventType];
    }
    /**
     * Set an event as the target event if any Relations exist for it already
     *
     * @param {MatrixEvent} event
     * The event to check as relation target.
     */
    setRelationsTarget(event) {
        if (!this.unstableClientRelationAggregation) {
            return;
        }
        const relationsForEvent = this.relations[event.getId()];
        if (!relationsForEvent) {
            return;
        }
        for (const relationsWithRelType of Object.values(relationsForEvent)) {
            for (const relationsWithEventType of Object.values(relationsWithRelType)) {
                relationsWithEventType.setTargetEvent(event);
            }
        }
    }
    /**
     * Add relation events to the relevant relation collection.
     *
     * @param {MatrixEvent} event
     * The new relation event to be aggregated.
     */
    aggregateRelations(event) {
        if (!this.unstableClientRelationAggregation) {
            return;
        }
        if (event.isRedacted() || event.status === event_1.EventStatus.CANCELLED) {
            return;
        }
        // If the event is currently encrypted, wait until it has been decrypted.
        if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
            event.once("Event.decrypted", () => {
                this.aggregateRelations(event);
            });
            return;
        }
        const relation = event.getRelation();
        if (!relation) {
            return;
        }
        const relatesToEventId = relation.event_id;
        const relationType = relation.rel_type;
        const eventType = event.getType();
        // debuglog("Aggregating relation: ", event.getId(), eventType, relation);
        let relationsForEvent = this.relations[relatesToEventId];
        if (!relationsForEvent) {
            relationsForEvent = this.relations[relatesToEventId] = {};
        }
        let relationsWithRelType = relationsForEvent[relationType];
        if (!relationsWithRelType) {
            relationsWithRelType = relationsForEvent[relationType] = {};
        }
        let relationsWithEventType = relationsWithRelType[eventType];
        let relatesToEvent;
        if (!relationsWithEventType) {
            relationsWithEventType = relationsWithRelType[eventType] = new relations_1.Relations(relationType, eventType, this.room);
            relatesToEvent = this.findEventById(relatesToEventId) || this.room.getPendingEvent(relatesToEventId);
            if (relatesToEvent) {
                relationsWithEventType.setTargetEvent(relatesToEvent);
            }
        }
        relationsWithEventType.addEvent(event);
    }
}
exports.EventTimelineSet = EventTimelineSet;
/**
 * Fires whenever the timeline in a room is updated.
 * @event module:client~MatrixClient#"Room.timeline"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {?Room} room The room, if any, whose timeline was updated.
 * @param {boolean} toStartOfTimeline True if this event was added to the start
 * @param {boolean} removed True if this event has just been removed from the timeline
 * (beginning; oldest) of the timeline e.g. due to pagination.
 *
 * @param {object} data  more data about the event
 *
 * @param {module:models/event-timeline.EventTimeline} data.timeline the timeline the
 * event was added to/removed from
 *
 * @param {boolean} data.liveEvent true if the event was a real-time event
 * added to the end of the live timeline
 *
 * @example
 * matrixClient.on("Room.timeline",
 *                 function(event, room, toStartOfTimeline, removed, data) {
 *   if (!toStartOfTimeline && data.liveEvent) {
 *     var messageToAppend = room.timeline.[room.timeline.length - 1];
 *   }
 * });
 */
/**
 * Fires whenever the live timeline in a room is reset.
 *
 * When we get a 'limited' sync (for example, after a network outage), we reset
 * the live timeline to be empty before adding the recent events to the new
 * timeline. This event is fired after the timeline is reset, and before the
 * new events are added.
 *
 * @event module:client~MatrixClient#"Room.timelineReset"
 * @param {Room} room The room whose live timeline was reset, if any
 * @param {EventTimelineSet} timelineSet timelineSet room whose live timeline was reset
 * @param {boolean} resetAllTimelines True if all timelines were reset.
 */

},{"../logger":106,"./event":113,"./event-timeline":112,"./relations":115,"events":36}],112:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventTimeline = exports.Direction = void 0;
/**
 * @module models/event-timeline
 */
const room_state_1 = require("./room-state");
const event_1 = require("../@types/event");
var Direction;
(function (Direction) {
    Direction["Backward"] = "b";
    Direction["Forward"] = "f";
})(Direction = exports.Direction || (exports.Direction = {}));
class EventTimeline {
    /**
     * Construct a new EventTimeline
     *
     * <p>An EventTimeline represents a contiguous sequence of events in a room.
     *
     * <p>As well as keeping track of the events themselves, it stores the state of
     * the room at the beginning and end of the timeline, and pagination tokens for
     * going backwards and forwards in the timeline.
     *
     * <p>In order that clients can meaningfully maintain an index into a timeline,
     * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is
     * incremented when events are prepended to the timeline. The index of an event
     * relative to baseIndex therefore remains constant.
     *
     * <p>Once a timeline joins up with its neighbour, they are linked together into a
     * doubly-linked list.
     *
     * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of
     * @constructor
     */
    constructor(eventTimelineSet) {
        var _a, _b;
        this.eventTimelineSet = eventTimelineSet;
        this.events = [];
        this.baseIndex = 0;
        this.paginationRequests = {
            [Direction.Backward]: null,
            [Direction.Forward]: null,
        };
        this.roomId = (_b = (_a = eventTimelineSet.room) === null || _a === void 0 ? void 0 : _a.roomId) !== null && _b !== void 0 ? _b : null;
        this.startState = new room_state_1.RoomState(this.roomId);
        this.startState.paginationToken = null;
        this.endState = new room_state_1.RoomState(this.roomId);
        this.endState.paginationToken = null;
        this.prevTimeline = null;
        this.nextTimeline = null;
        // this is used by client.js
        this.paginationRequests = { 'b': null, 'f': null };
        this.name = this.roomId + ":" + new Date().toISOString();
    }
    /**
     * Static helper method to set sender and target properties
     *
     * @param {MatrixEvent} event   the event whose metadata is to be set
     * @param {RoomState} stateContext  the room state to be queried
     * @param {boolean} toStartOfTimeline  if true the event's forwardLooking flag is set false
     */
    static setEventMetadata(event, stateContext, toStartOfTimeline) {
        // We always check if the event doesn't already have the property. We do
        // this to avoid overriding non-sentinel members by sentinel ones when
        // adding the event to a filtered timeline
        if (!event.sender) {
            event.sender = stateContext.getSentinelMember(event.getSender());
        }
        if (!event.target && event.getType() === event_1.EventType.RoomMember) {
            event.target = stateContext.getSentinelMember(event.getStateKey());
        }
        if (event.isState()) {
            // room state has no concept of 'old' or 'current', but we want the
            // room state to regress back to previous values if toStartOfTimeline
            // is set, which means inspecting prev_content if it exists. This
            // is done by toggling the forwardLooking flag.
            if (toStartOfTimeline) {
                event.forwardLooking = false;
            }
        }
    }
    /**
     * Initialise the start and end state with the given events
     *
     * <p>This can only be called before any events are added.
     *
     * @param {MatrixEvent[]} stateEvents list of state events to initialise the
     * state with.
     * @throws {Error} if an attempt is made to call this after addEvent is called.
     */
    initialiseState(stateEvents) {
        if (this.events.length > 0) {
            throw new Error("Cannot initialise state after events are added");
        }
        // We previously deep copied events here and used different copies in
        // the oldState and state events: this decision seems to date back
        // quite a way and was apparently made to fix a bug where modifications
        // made to the start state leaked through to the end state.
        // This really shouldn't be possible though: the events themselves should
        // not change. Duplicating the events uses a lot of extra memory,
        // so we now no longer do it. To assert that they really do never change,
        // freeze them! Note that we can't do this for events in general:
        // although it looks like the only things preventing us are the
        // 'status' flag, forwardLooking (which is only set once when adding to the
        // timeline) and possibly the sender (which seems like it should never be
        // reset but in practice causes a lot of the tests to break).
        for (const e of stateEvents) {
            Object.freeze(e);
        }
        this.startState.setStateEvents(stateEvents);
        this.endState.setStateEvents(stateEvents);
    }
    /**
     * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.
     * All attached listeners will keep receiving state updates from the new live timeline state.
     * The end state of this timeline gets replaced with an independent copy of the current RoomState,
     * and will need a new pagination token if it ever needs to paginate forwards.

     * @param {string} direction   EventTimeline.BACKWARDS to get the state at the
     *   start of the timeline; EventTimeline.FORWARDS to get the state at the end
     *   of the timeline.
     *
     * @return {EventTimeline} the new timeline
     */
    forkLive(direction) {
        const forkState = this.getState(direction);
        const timeline = new EventTimeline(this.eventTimelineSet);
        timeline.startState = forkState.clone();
        // Now clobber the end state of the new live timeline with that from the
        // previous live timeline. It will be identical except that we'll keep
        // using the same RoomMember objects for the 'live' set of members with any
        // listeners still attached
        timeline.endState = forkState;
        // Firstly, we just stole the current timeline's end state, so it needs a new one.
        // Make an immutable copy of the state so back pagination will get the correct sentinels.
        this.endState = forkState.clone();
        return timeline;
    }
    /**
     * Creates an independent timeline, inheriting the directional state from this timeline.
     *
     * @param {string} direction   EventTimeline.BACKWARDS to get the state at the
     *   start of the timeline; EventTimeline.FORWARDS to get the state at the end
     *   of the timeline.
     *
     * @return {EventTimeline} the new timeline
     */
    fork(direction) {
        const forkState = this.getState(direction);
        const timeline = new EventTimeline(this.eventTimelineSet);
        timeline.startState = forkState.clone();
        timeline.endState = forkState.clone();
        return timeline;
    }
    /**
     * Get the ID of the room for this timeline
     * @return {string} room ID
     */
    getRoomId() {
        return this.roomId;
    }
    /**
     * Get the filter for this timeline's timelineSet (if any)
     * @return {Filter} filter
     */
    getFilter() {
        return this.eventTimelineSet.getFilter();
    }
    /**
     * Get the timelineSet for this timeline
     * @return {EventTimelineSet} timelineSet
     */
    getTimelineSet() {
        return this.eventTimelineSet;
    }
    /**
     * Get the base index.
     *
     * <p>This is an index which is incremented when events are prepended to the
     * timeline. An individual event therefore stays at the same index in the array
     * relative to the base index (although note that a given event's index may
     * well be less than the base index, thus giving that event a negative relative
     * index).
     *
     * @return {number}
     */
    getBaseIndex() {
        return this.baseIndex;
    }
    /**
     * Get the list of events in this context
     *
     * @return {MatrixEvent[]} An array of MatrixEvents
     */
    getEvents() {
        return this.events;
    }
    /**
     * Get the room state at the start/end of the timeline
     *
     * @param {string} direction   EventTimeline.BACKWARDS to get the state at the
     *   start of the timeline; EventTimeline.FORWARDS to get the state at the end
     *   of the timeline.
     *
     * @return {RoomState} state at the start/end of the timeline
     */
    getState(direction) {
        if (direction == EventTimeline.BACKWARDS) {
            return this.startState;
        }
        else if (direction == EventTimeline.FORWARDS) {
            return this.endState;
        }
        else {
            throw new Error("Invalid direction '" + direction + "'");
        }
    }
    /**
     * Get a pagination token
     *
     * @param {string} direction   EventTimeline.BACKWARDS to get the pagination
     *   token for going backwards in time; EventTimeline.FORWARDS to get the
     *   pagination token for going forwards in time.
     *
     * @return {?string} pagination token
     */
    getPaginationToken(direction) {
        return this.getState(direction).paginationToken;
    }
    /**
     * Set a pagination token
     *
     * @param {?string} token       pagination token
     *
     * @param {string} direction    EventTimeline.BACKWARDS to set the pagination
     *   token for going backwards in time; EventTimeline.FORWARDS to set the
     *   pagination token for going forwards in time.
     */
    setPaginationToken(token, direction) {
        this.getState(direction).paginationToken = token;
    }
    /**
     * Get the next timeline in the series
     *
     * @param {string} direction EventTimeline.BACKWARDS to get the previous
     *   timeline; EventTimeline.FORWARDS to get the next timeline.
     *
     * @return {?EventTimeline} previous or following timeline, if they have been
     * joined up.
     */
    getNeighbouringTimeline(direction) {
        if (direction == EventTimeline.BACKWARDS) {
            return this.prevTimeline;
        }
        else if (direction == EventTimeline.FORWARDS) {
            return this.nextTimeline;
        }
        else {
            throw new Error("Invalid direction '" + direction + "'");
        }
    }
    /**
     * Set the next timeline in the series
     *
     * @param {EventTimeline} neighbour previous/following timeline
     *
     * @param {string} direction EventTimeline.BACKWARDS to set the previous
     *   timeline; EventTimeline.FORWARDS to set the next timeline.
     *
     * @throws {Error} if an attempt is made to set the neighbouring timeline when
     * it is already set.
     */
    setNeighbouringTimeline(neighbour, direction) {
        if (this.getNeighbouringTimeline(direction)) {
            throw new Error("timeline already has a neighbouring timeline - " +
                "cannot reset neighbour (direction: " + direction + ")");
        }
        if (direction == EventTimeline.BACKWARDS) {
            this.prevTimeline = neighbour;
        }
        else if (direction == EventTimeline.FORWARDS) {
            this.nextTimeline = neighbour;
        }
        else {
            throw new Error("Invalid direction '" + direction + "'");
        }
        // make sure we don't try to paginate this timeline
        this.setPaginationToken(null, direction);
    }
    /**
     * Add a new event to the timeline, and update the state
     *
     * @param {MatrixEvent} event   new event
     * @param {boolean}  atStart     true to insert new event at the start
     */
    addEvent(event, atStart) {
        const stateContext = atStart ? this.startState : this.endState;
        const timelineSet = this.getTimelineSet();
        if (timelineSet.room) {
            EventTimeline.setEventMetadata(event, stateContext, atStart);
            // modify state but only on unfiltered timelineSets
            if (event.isState() &&
                timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {
                stateContext.setStateEvents([event]);
                // it is possible that the act of setting the state event means we
                // can set more metadata (specifically sender/target props), so try
                // it again if the prop wasn't previously set. It may also mean that
                // the sender/target is updated (if the event set was a room member event)
                // so we want to use the *updated* member (new avatar/name) instead.
                //
                // However, we do NOT want to do this on member events if we're going
                // back in time, else we'll set the .sender value for BEFORE the given
                // member event, whereas we want to set the .sender value for the ACTUAL
                // member event itself.
                if (!event.sender || (event.getType() === "m.room.member" && !atStart)) {
                    EventTimeline.setEventMetadata(event, stateContext, atStart);
                }
            }
        }
        let insertIndex;
        if (atStart) {
            insertIndex = 0;
        }
        else {
            insertIndex = this.events.length;
        }
        this.events.splice(insertIndex, 0, event); // insert element
        if (atStart) {
            this.baseIndex++;
        }
    }
    /**
     * Remove an event from the timeline
     *
     * @param {string} eventId  ID of event to be removed
     * @return {?MatrixEvent} removed event, or null if not found
     */
    removeEvent(eventId) {
        for (let i = this.events.length - 1; i >= 0; i--) {
            const ev = this.events[i];
            if (ev.getId() == eventId) {
                this.events.splice(i, 1);
                if (i < this.baseIndex) {
                    this.baseIndex--;
                }
                return ev;
            }
        }
        return null;
    }
    /**
     * Return a string to identify this timeline, for debugging
     *
     * @return {string} name for this timeline
     */
    toString() {
        return this.name;
    }
}
exports.EventTimeline = EventTimeline;
/**
 * Symbolic constant for methods which take a 'direction' argument:
 * refers to the start of the timeline, or backwards in time.
 */
EventTimeline.BACKWARDS = Direction.Backward;
/**
 * Symbolic constant for methods which take a 'direction' argument:
 * refers to the end of the timeline, or forwards in time.
 */
EventTimeline.FORWARDS = Direction.Forward;

},{"../@types/event":58,"./room-state":117}],113:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MatrixEvent = exports.EventStatus = void 0;
/**
 * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for
 * the public classes.
 * @module models/event
 */
const events_1 = require("events");
const logger_1 = require("../logger");
const event_1 = require("../@types/event");
const utils_1 = require("../utils");
/**
 * Enum for event statuses.
 * @readonly
 * @enum {string}
 */
var EventStatus;
(function (EventStatus) {
    /** The event was not sent and will no longer be retried. */
    EventStatus["NOT_SENT"] = "not_sent";
    /** The message is being encrypted */
    EventStatus["ENCRYPTING"] = "encrypting";
    /** The event is in the process of being sent. */
    EventStatus["SENDING"] = "sending";
    /** The event is in a queue waiting to be sent. */
    EventStatus["QUEUED"] = "queued";
    /** The event has been sent to the server, but we have not yet received the echo. */
    EventStatus["SENT"] = "sent";
    /** The event was cancelled before it was successfully sent. */
    EventStatus["CANCELLED"] = "cancelled";
})(EventStatus = exports.EventStatus || (exports.EventStatus = {}));
const interns = {};
function intern(str) {
    if (!interns[str]) {
        interns[str] = str;
    }
    return interns[str];
}
class MatrixEvent extends events_1.EventEmitter {
    /**
     * Construct a Matrix Event object
     * @constructor
     *
     * @param {Object} event The raw event to be wrapped in this DAO
     *
     * @prop {Object} event The raw (possibly encrypted) event. <b>Do not access
     * this property</b> directly unless you absolutely have to. Prefer the getter
     * methods defined on this class. Using the getter methods shields your app
     * from changes to event JSON between Matrix versions.
     *
     * @prop {RoomMember} sender The room member who sent this event, or null e.g.
     * this is a presence event. This is only guaranteed to be set for events that
     * appear in a timeline, ie. do not guarantee that it will be set on state
     * events.
     * @prop {RoomMember} target The room member who is the target of this event, e.g.
     * the invitee, the person being banned, etc.
     * @prop {EventStatus} status The sending status of the event.
     * @prop {Error} error most recent error associated with sending the event, if any
     * @prop {boolean} forwardLooking True if this event is 'forward looking', meaning
     * that getDirectionalContent() will return event.content and not event.prev_content.
     * Default: true. <strong>This property is experimental and may change.</strong>
     */
    constructor(event = {}) {
        super();
        this.event = event;
        this.pushActions = null;
        this._replacingEvent = null;
        this._localRedactionEvent = null;
        this._isCancelled = false;
        this.clearEvent = {};
        /* curve25519 key which we believe belongs to the sender of the event. See
         * getSenderKey()
         */
        this.senderCurve25519Key = null;
        /* ed25519 key which the sender of this event (for olm) or the creator of
         * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()
         */
        this.claimedEd25519Key = null;
        /* curve25519 keys of devices involved in telling us about the
         * senderCurve25519Key and claimedEd25519Key.
         * See getForwardingCurve25519KeyChain().
         */
        this.forwardingCurve25519KeyChain = [];
        /* where the decryption key is untrusted
         */
        this.untrusted = null;
        /* if we have a process decrypting this event, a Promise which resolves
         * when it is finished. Normally null.
         */
        this._decryptionPromise = null;
        /* flag to indicate if we should retry decrypting this event after the
         * first attempt (eg, we have received new data which means that a second
         * attempt may succeed)
         */
        this.retryDecryption = false;
        /* The txnId with which this event was sent if it was during this session,
         * allows for a unique ID which does not change when the event comes back down sync.
         */
        this.txnId = null;
        // XXX: these should be read-only
        this.sender = null;
        this.target = null;
        this.status = null;
        this.error = null;
        this.forwardLooking = true;
        /* If the event is a `m.key.verification.request` (or to_device `m.key.verification.start`) event,
         * `Crypto` will set this the `VerificationRequest` for the event
         * so it can be easily accessed from the timeline.
         */
        this.verificationRequest = null;
        // intern the values of matrix events to force share strings and reduce the
        // amount of needless string duplication. This can save moderate amounts of
        // memory (~10% on a 350MB heap).
        // 'membership' at the event level (rather than the content level) is a legacy
        // field that Element never otherwise looks at, but it will still take up a lot
        // of space if we don't intern it.
        ["state_key", "type", "sender", "room_id", "membership"].forEach((prop) => {
            if (typeof event[prop] !== "string")
                return;
            event[prop] = intern(event[prop]);
        });
        ["membership", "avatar_url", "displayname"].forEach((prop) => {
            var _a;
            if (typeof ((_a = event.content) === null || _a === void 0 ? void 0 : _a[prop]) !== "string")
                return;
            event.content[prop] = intern(event.content[prop]);
        });
        ["rel_type"].forEach((prop) => {
            var _a, _b;
            if (typeof ((_b = (_a = event.content) === null || _a === void 0 ? void 0 : _a["m.relates_to"]) === null || _b === void 0 ? void 0 : _b[prop]) !== "string")
                return;
            event.content["m.relates_to"][prop] = intern(event.content["m.relates_to"][prop]);
        });
        this.txnId = event.txn_id || null;
        this.localTimestamp = Date.now() - this.getAge();
    }
    /**
     * Get the event_id for this event.
     * @return {string} The event ID, e.g. <code>$143350589368169JsLZx:localhost
     * </code>
     */
    getId() {
        return this.event.event_id;
    }
    /**
     * Get the user_id for this event.
     * @return {string} The user ID, e.g. <code>@alice:matrix.org</code>
     */
    getSender() {
        return this.event.sender || this.event.user_id; // v2 / v1
    }
    /**
     * Get the (decrypted, if necessary) type of event.
     *
     * @return {string} The event type, e.g. <code>m.room.message</code>
     */
    getType() {
        return this.clearEvent.type || this.event.type;
    }
    /**
     * Get the (possibly encrypted) type of the event that will be sent to the
     * homeserver.
     *
     * @return {string} The event type.
     */
    getWireType() {
        return this.event.type;
    }
    /**
     * Get the room_id for this event. This will return <code>undefined</code>
     * for <code>m.presence</code> events.
     * @return {string} The room ID, e.g. <code>!cURbafjkfsMDVwdRDQ:matrix.org
     * </code>
     */
    getRoomId() {
        return this.event.room_id;
    }
    /**
     * Get the timestamp of this event.
     * @return {Number} The event timestamp, e.g. <code>1433502692297</code>
     */
    getTs() {
        return this.event.origin_server_ts;
    }
    /**
     * Get the timestamp of this event, as a Date object.
     * @return {Date} The event date, e.g. <code>new Date(1433502692297)</code>
     */
    getDate() {
        return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;
    }
    /**
     * Get the (decrypted, if necessary) event content JSON, even if the event
     * was replaced by another event.
     *
     * @return {Object} The event content JSON, or an empty object.
     */
    getOriginalContent() {
        if (this._localRedactionEvent) {
            return {};
        }
        return (this.clearEvent.content || this.event.content || {});
    }
    /**
     * Get the (decrypted, if necessary) event content JSON,
     * or the content from the replacing event, if any.
     * See `makeReplaced`.
     *
     * @return {Object} The event content JSON, or an empty object.
     */
    getContent() {
        if (this._localRedactionEvent) {
            return {};
        }
        else if (this._replacingEvent) {
            return this._replacingEvent.getContent()["m.new_content"] || {};
        }
        else {
            return this.getOriginalContent();
        }
    }
    /**
     * Get the (possibly encrypted) event content JSON that will be sent to the
     * homeserver.
     *
     * @return {Object} The event content JSON, or an empty object.
     */
    getWireContent() {
        return this.event.content || {};
    }
    /**
     * Get the previous event content JSON. This will only return something for
     * state events which exist in the timeline.
     * @return {Object} The previous event content JSON, or an empty object.
     */
    getPrevContent() {
        // v2 then v1 then default
        return this.getUnsigned().prev_content || this.event.prev_content || {};
    }
    /**
     * Get either 'content' or 'prev_content' depending on if this event is
     * 'forward-looking' or not. This can be modified via event.forwardLooking.
     * In practice, this means we get the chronologically earlier content value
     * for this event (this method should surely be called getEarlierContent)
     * <strong>This method is experimental and may change.</strong>
     * @return {Object} event.content if this event is forward-looking, else
     * event.prev_content.
     */
    getDirectionalContent() {
        return this.forwardLooking ? this.getContent() : this.getPrevContent();
    }
    /**
     * Get the age of this event. This represents the age of the event when the
     * event arrived at the device, and not the age of the event when this
     * function was called.
     * @return {Number} The age of this event in milliseconds.
     */
    getAge() {
        return this.getUnsigned().age || this.event.age; // v2 / v1
    }
    /**
     * Get the age of the event when this function was called.
     * This is the 'age' field adjusted according to how long this client has
     * had the event.
     * @return {Number} The age of this event in milliseconds.
     */
    getLocalAge() {
        return Date.now() - this.localTimestamp;
    }
    /**
     * Get the event state_key if it has one. This will return <code>undefined
     * </code> for message events.
     * @return {string} The event's <code>state_key</code>.
     */
    getStateKey() {
        return this.event.state_key;
    }
    /**
     * Check if this event is a state event.
     * @return {boolean} True if this is a state event.
     */
    isState() {
        return this.event.state_key !== undefined;
    }
    /**
     * Replace the content of this event with encrypted versions.
     * (This is used when sending an event; it should not be used by applications).
     *
     * @internal
     *
     * @param {string} cryptoType type of the encrypted event - typically
     * <tt>"m.room.encrypted"</tt>
     *
     * @param {object} cryptoContent raw 'content' for the encrypted event.
     *
     * @param {string} senderCurve25519Key curve25519 key to record for the
     *   sender of this event.
     *   See {@link module:models/event.MatrixEvent#getSenderKey}.
     *
     * @param {string} claimedEd25519Key claimed ed25519 key to record for the
     *   sender if this event.
     *   See {@link module:models/event.MatrixEvent#getClaimedEd25519Key}
     */
    makeEncrypted(cryptoType, cryptoContent, senderCurve25519Key, claimedEd25519Key) {
        // keep the plain-text data for 'view source'
        this.clearEvent = {
            type: this.event.type,
            content: this.event.content,
        };
        this.event.type = cryptoType;
        this.event.content = cryptoContent;
        this.senderCurve25519Key = senderCurve25519Key;
        this.claimedEd25519Key = claimedEd25519Key;
    }
    /**
     * Check if this event is currently being decrypted.
     *
     * @return {boolean} True if this event is currently being decrypted, else false.
     */
    isBeingDecrypted() {
        return this._decryptionPromise != null;
    }
    getDecryptionPromise() {
        return this._decryptionPromise;
    }
    /**
     * Check if this event is an encrypted event which we failed to decrypt
     *
     * (This implies that we might retry decryption at some point in the future)
     *
     * @return {boolean} True if this event is an encrypted event which we
     *     couldn't decrypt.
     */
    isDecryptionFailure() {
        var _a, _b;
        return ((_b = (_a = this.clearEvent) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.msgtype) === "m.bad.encrypted";
    }
    shouldAttemptDecryption() {
        return this.isEncrypted() && !this.isBeingDecrypted() && this.getClearContent() === null;
    }
    /**
     * Start the process of trying to decrypt this event.
     *
     * (This is used within the SDK: it isn't intended for use by applications)
     *
     * @internal
     *
     * @param {module:crypto} crypto crypto module
     * @param {object} options
     * @param {boolean} options.isRetry True if this is a retry (enables more logging)
     * @param {boolean} options.emit Emits "event.decrypted" if set to true
     *
     * @returns {Promise} promise which resolves (to undefined) when the decryption
     * attempt is completed.
     */
    attemptDecryption(crypto, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            // For backwards compatibility purposes
            // The function signature used to be attemptDecryption(crypto, isRetry)
            if (typeof options === "boolean") {
                options = {
                    isRetry: options,
                };
            }
            // start with a couple of sanity checks.
            if (!this.isEncrypted()) {
                throw new Error("Attempt to decrypt event which isn't encrypted");
            }
            if (this.clearEvent && this.clearEvent.content &&
                this.clearEvent.content.msgtype !== "m.bad.encrypted") {
                // we may want to just ignore this? let's start with rejecting it.
                throw new Error("Attempt to decrypt event which has already been decrypted");
            }
            // if we already have a decryption attempt in progress, then it may
            // fail because it was using outdated info. We now have reason to
            // succeed where it failed before, but we don't want to have multiple
            // attempts going at the same time, so just set a flag that says we have
            // new info.
            //
            if (this._decryptionPromise) {
                logger_1.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`);
                this.retryDecryption = true;
                return this._decryptionPromise;
            }
            this._decryptionPromise = this.decryptionLoop(crypto, options);
            return this._decryptionPromise;
        });
    }
    /**
     * Cancel any room key request for this event and resend another.
     *
     * @param {module:crypto} crypto crypto module
     * @param {string} userId the user who received this event
     *
     * @returns {Promise} a promise that resolves when the request is queued
     */
    cancelAndResendKeyRequest(crypto, userId) {
        const wireContent = this.getWireContent();
        return crypto.requestRoomKey({
            algorithm: wireContent.algorithm,
            room_id: this.getRoomId(),
            session_id: wireContent.session_id,
            sender_key: wireContent.sender_key,
        }, this.getKeyRequestRecipients(userId), true);
    }
    /**
     * Calculate the recipients for keyshare requests.
     *
     * @param {string} userId the user who received this event.
     *
     * @returns {Array} array of recipients
     */
    getKeyRequestRecipients(userId) {
        // send the request to all of our own devices, and the
        // original sending device if it wasn't us.
        const wireContent = this.getWireContent();
        const recipients = [{
                userId, deviceId: '*',
            }];
        const sender = this.getSender();
        if (sender !== userId) {
            recipients.push({
                userId: sender, deviceId: wireContent.device_id,
            });
        }
        return recipients;
    }
    decryptionLoop(crypto, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            // make sure that this method never runs completely synchronously.
            // (doing so would mean that we would clear _decryptionPromise *before*
            // it is set in attemptDecryption - and hence end up with a stuck
            // `_decryptionPromise`).
            yield Promise.resolve();
            // eslint-disable-next-line no-constant-condition
            while (true) {
                this.retryDecryption = false;
                let res;
                let err;
                try {
                    if (!crypto) {
                        res = this.badEncryptedMessage("Encryption not enabled");
                    }
                    else {
                        res = yield crypto.decryptEvent(this);
                        if (options.isRetry === true) {
                            logger_1.logger.info(`Decrypted event on retry (id=${this.getId()})`);
                        }
                    }
                }
                catch (e) {
                    if (e.name !== "DecryptionError") {
                        // not a decryption error: log the whole exception as an error
                        // (and don't bother with a retry)
                        const re = options.isRetry ? 're' : '';
                        logger_1.logger.error(`Error ${re}decrypting event ` +
                            `(id=${this.getId()}): ${e.stack || e}`);
                        this._decryptionPromise = null;
                        this.retryDecryption = false;
                        return;
                    }
                    err = e;
                    // see if we have a retry queued.
                    //
                    // NB: make sure to keep this check in the same tick of the
                    //   event loop as `_decryptionPromise = null` below - otherwise we
                    //   risk a race:
                    //
                    //   * A: we check retryDecryption here and see that it is
                    //        false
                    //   * B: we get a second call to attemptDecryption, which sees
                    //        that _decryptionPromise is set so sets
                    //        retryDecryption
                    //   * A: we continue below, clear _decryptionPromise, and
                    //        never do the retry.
                    //
                    if (this.retryDecryption) {
                        // decryption error, but we have a retry queued.
                        logger_1.logger.log(`Got error decrypting event (id=${this.getId()}: ` +
                            `${e}), but retrying`);
                        continue;
                    }
                    // decryption error, no retries queued. Warn about the error and
                    // set it to m.bad.encrypted.
                    logger_1.logger.warn(`Error decrypting event (id=${this.getId()}): ${e.detailedString}`);
                    res = this.badEncryptedMessage(e.message);
                }
                // at this point, we've either successfully decrypted the event, or have given up
                // (and set res to a 'badEncryptedMessage'). Either way, we can now set the
                // cleartext of the event and raise Event.decrypted.
                //
                // make sure we clear '_decryptionPromise' before sending the 'Event.decrypted' event,
                // otherwise the app will be confused to see `isBeingDecrypted` still set when
                // there isn't an `Event.decrypted` on the way.
                //
                // see also notes on retryDecryption above.
                //
                this._decryptionPromise = null;
                this.retryDecryption = false;
                this.setClearData(res);
                // Before we emit the event, clear the push actions so that they can be recalculated
                // by relevant code. We do this because the clear event has now changed, making it
                // so that existing rules can be re-run over the applicable properties. Stuff like
                // highlighting when the user's name is mentioned rely on this happening. We also want
                // to set the push actions before emitting so that any notification listeners don't
                // pick up the wrong contents.
                this.setPushActions(null);
                if (options.emit !== false) {
                    this.emit("Event.decrypted", this, err);
                }
                return;
            }
        });
    }
    badEncryptedMessage(reason) {
        return {
            clearEvent: {
                type: "m.room.message",
                content: {
                    msgtype: "m.bad.encrypted",
                    body: "** Unable to decrypt: " + reason + " **",
                },
            },
        };
    }
    /**
     * Update the cleartext data on this event.
     *
     * (This is used after decrypting an event; it should not be used by applications).
     *
     * @internal
     *
     * @fires module:models/event.MatrixEvent#"Event.decrypted"
     *
     * @param {module:crypto~EventDecryptionResult} decryptionResult
     *     the decryption result, including the plaintext and some key info
     */
    setClearData(decryptionResult) {
        this.clearEvent = decryptionResult.clearEvent;
        this.senderCurve25519Key =
            decryptionResult.senderCurve25519Key || null;
        this.claimedEd25519Key =
            decryptionResult.claimedEd25519Key || null;
        this.forwardingCurve25519KeyChain =
            decryptionResult.forwardingCurve25519KeyChain || [];
        this.untrusted = decryptionResult.untrusted || false;
    }
    /**
     * Gets the cleartext content for this event. If the event is not encrypted,
     * or encryption has not been completed, this will return null.
     *
     * @returns {Object} The cleartext (decrypted) content for the event
     */
    getClearContent() {
        const ev = this.clearEvent;
        return ev && ev.content ? ev.content : null;
    }
    /**
     * Check if the event is encrypted.
     * @return {boolean} True if this event is encrypted.
     */
    isEncrypted() {
        return !this.isState() && this.event.type === "m.room.encrypted";
    }
    /**
     * The curve25519 key for the device that we think sent this event
     *
     * For an Olm-encrypted event, this is inferred directly from the DH
     * exchange at the start of the session: the curve25519 key is involved in
     * the DH exchange, so only a device which holds the private part of that
     * key can establish such a session.
     *
     * For a megolm-encrypted event, it is inferred from the Olm message which
     * established the megolm session
     *
     * @return {string}
     */
    getSenderKey() {
        return this.senderCurve25519Key;
    }
    /**
     * The additional keys the sender of this encrypted event claims to possess.
     *
     * Just a wrapper for #getClaimedEd25519Key (q.v.)
     *
     * @return {Object<string, string>}
     */
    getKeysClaimed() {
        return {
            ed25519: this.claimedEd25519Key,
        };
    }
    /**
     * Get the ed25519 the sender of this event claims to own.
     *
     * For Olm messages, this claim is encoded directly in the plaintext of the
     * event itself. For megolm messages, it is implied by the m.room_key event
     * which established the megolm session.
     *
     * Until we download the device list of the sender, it's just a claim: the
     * device list gives a proof that the owner of the curve25519 key used for
     * this event (and returned by #getSenderKey) also owns the ed25519 key by
     * signing the public curve25519 key with the ed25519 key.
     *
     * In general, applications should not use this method directly, but should
     * instead use MatrixClient.getEventSenderDeviceInfo.
     *
     * @return {string}
     */
    getClaimedEd25519Key() {
        return this.claimedEd25519Key;
    }
    /**
     * Get the curve25519 keys of the devices which were involved in telling us
     * about the claimedEd25519Key and sender curve25519 key.
     *
     * Normally this will be empty, but in the case of a forwarded megolm
     * session, the sender keys are sent to us by another device (the forwarding
     * device), which we need to trust to do this. In that case, the result will
     * be a list consisting of one entry.
     *
     * If the device that sent us the key (A) got it from another device which
     * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on.
     *
     * @return {string[]} base64-encoded curve25519 keys, from oldest to newest.
     */
    getForwardingCurve25519KeyChain() {
        return this.forwardingCurve25519KeyChain;
    }
    /**
     * Whether the decryption key was obtained from an untrusted source. If so,
     * we cannot verify the authenticity of the message.
     *
     * @return {boolean}
     */
    isKeySourceUntrusted() {
        return this.untrusted;
    }
    getUnsigned() {
        return this.event.unsigned || {};
    }
    unmarkLocallyRedacted() {
        const value = this._localRedactionEvent;
        this._localRedactionEvent = null;
        if (this.event.unsigned) {
            this.event.unsigned.redacted_because = null;
        }
        return !!value;
    }
    markLocallyRedacted(redactionEvent) {
        if (this._localRedactionEvent)
            return;
        this.emit("Event.beforeRedaction", this, redactionEvent);
        this._localRedactionEvent = redactionEvent;
        if (!this.event.unsigned) {
            this.event.unsigned = {};
        }
        this.event.unsigned.redacted_because = redactionEvent.event;
    }
    /**
     * Update the content of an event in the same way it would be by the server
     * if it were redacted before it was sent to us
     *
     * @param {module:models/event.MatrixEvent} redactionEvent
     *     event causing the redaction
     */
    makeRedacted(redactionEvent) {
        // quick sanity-check
        if (!redactionEvent.event) {
            throw new Error("invalid redactionEvent in makeRedacted");
        }
        this._localRedactionEvent = null;
        this.emit("Event.beforeRedaction", this, redactionEvent);
        this._replacingEvent = null;
        // we attempt to replicate what we would see from the server if
        // the event had been redacted before we saw it.
        //
        // The server removes (most of) the content of the event, and adds a
        // "redacted_because" key to the unsigned section containing the
        // redacted event.
        if (!this.event.unsigned) {
            this.event.unsigned = {};
        }
        this.event.unsigned.redacted_because = redactionEvent.event;
        let key;
        for (key in this.event) {
            if (!this.event.hasOwnProperty(key)) {
                continue;
            }
            if (!REDACT_KEEP_KEYS.has(key)) {
                delete this.event[key];
            }
        }
        const keeps = REDACT_KEEP_CONTENT_MAP[this.getType()] || {};
        const content = this.getContent();
        for (key in content) {
            if (!content.hasOwnProperty(key)) {
                continue;
            }
            if (!keeps[key]) {
                delete content[key];
            }
        }
    }
    /**
     * Check if this event has been redacted
     *
     * @return {boolean} True if this event has been redacted
     */
    isRedacted() {
        return Boolean(this.getUnsigned().redacted_because);
    }
    /**
     * Check if this event is a redaction of another event
     *
     * @return {boolean} True if this event is a redaction
     */
    isRedaction() {
        return this.getType() === "m.room.redaction";
    }
    /**
     * Get the (decrypted, if necessary) redaction event JSON
     * if event was redacted
     *
     * @returns {object} The redaction event JSON, or an empty object
     */
    getRedactionEvent() {
        if (!this.isRedacted())
            return null;
        if (this.clearEvent.unsigned) {
            return this.clearEvent.unsigned.redacted_because;
        }
        else if (this.event.unsigned.redacted_because) {
            return this.event.unsigned.redacted_because;
        }
        else {
            return {};
        }
    }
    /**
     * Get the push actions, if known, for this event
     *
     * @return {?Object} push actions
     */
    getPushActions() {
        return this.pushActions;
    }
    /**
     * Set the push actions for this event.
     *
     * @param {Object} pushActions push actions
     */
    setPushActions(pushActions) {
        this.pushActions = pushActions;
    }
    /**
     * Replace the `event` property and recalculate any properties based on it.
     * @param {Object} event the object to assign to the `event` property
     */
    handleRemoteEcho(event) {
        const oldUnsigned = this.getUnsigned();
        const oldId = this.getId();
        this.event = event;
        // if this event was redacted before it was sent, it's locally marked as redacted.
        // At this point, we've received the remote echo for the event, but not yet for
        // the redaction that we are sending ourselves. Preserve the locally redacted
        // state by copying over redacted_because so we don't get a flash of
        // redacted, not-redacted, redacted as remote echos come in
        if (oldUnsigned.redacted_because) {
            if (!this.event.unsigned) {
                this.event.unsigned = {};
            }
            this.event.unsigned.redacted_because = oldUnsigned.redacted_because;
        }
        // successfully sent.
        this.setStatus(null);
        if (this.getId() !== oldId) {
            // emit the event if it changed
            this.emit("Event.localEventIdReplaced", this);
        }
    }
    /**
     * Whether the event is in any phase of sending, send failure, waiting for
     * remote echo, etc.
     *
     * @return {boolean}
     */
    isSending() {
        return !!this.status;
    }
    /**
     * Update the event's sending status and emit an event as well.
     *
     * @param {String} status The new status
     */
    setStatus(status) {
        this.status = status;
        this.emit("Event.status", this, status);
    }
    replaceLocalEventId(eventId) {
        this.event.event_id = eventId;
        this.emit("Event.localEventIdReplaced", this);
    }
    /**
     * Get whether the event is a relation event, and of a given type if
     * `relType` is passed in.
     *
     * @param {string?} relType if given, checks that the relation is of the
     * given type
     * @return {boolean}
     */
    isRelation(relType = undefined) {
        // Relation info is lifted out of the encrypted content when sent to
        // encrypted rooms, so we have to check `getWireContent` for this.
        const content = this.getWireContent();
        const relation = content && content["m.relates_to"];
        return relation && relation.rel_type && relation.event_id &&
            ((relType && relation.rel_type === relType) || !relType);
    }
    /**
     * Get relation info for the event, if any.
     *
     * @return {Object}
     */
    getRelation() {
        if (!this.isRelation()) {
            return null;
        }
        return this.getWireContent()["m.relates_to"];
    }
    /**
     * Set an event that replaces the content of this event, through an m.replace relation.
     *
     * @fires module:models/event.MatrixEvent#"Event.replaced"
     *
     * @param {MatrixEvent?} newEvent the event with the replacing content, if any.
     */
    makeReplaced(newEvent) {
        // don't allow redacted events to be replaced.
        // if newEvent is null we allow to go through though,
        // as with local redaction, the replacing event might get
        // cancelled, which should be reflected on the target event.
        if (this.isRedacted() && newEvent) {
            return;
        }
        if (this._replacingEvent !== newEvent) {
            this._replacingEvent = newEvent;
            this.emit("Event.replaced", this);
        }
    }
    /**
     * Returns the status of any associated edit or redaction
     * (not for reactions/annotations as their local echo doesn't affect the original event),
     * or else the status of the event.
     *
     * @return {EventStatus}
     */
    getAssociatedStatus() {
        if (this._replacingEvent) {
            return this._replacingEvent.status;
        }
        else if (this._localRedactionEvent) {
            return this._localRedactionEvent.status;
        }
        return this.status;
    }
    getServerAggregatedRelation(relType) {
        const relations = this.getUnsigned()["m.relations"];
        if (relations) {
            return relations[relType];
        }
    }
    /**
     * Returns the event ID of the event replacing the content of this event, if any.
     *
     * @return {string?}
     */
    replacingEventId() {
        const replaceRelation = this.getServerAggregatedRelation(event_1.RelationType.Replace);
        if (replaceRelation) {
            return replaceRelation.event_id;
        }
        else if (this._replacingEvent) {
            return this._replacingEvent.getId();
        }
    }
    /**
     * Returns the event replacing the content of this event, if any.
     * Replacements are aggregated on the server, so this would only
     * return an event in case it came down the sync, or for local echo of edits.
     *
     * @return {MatrixEvent?}
     */
    replacingEvent() {
        return this._replacingEvent;
    }
    /**
     * Returns the origin_server_ts of the event replacing the content of this event, if any.
     *
     * @return {Date?}
     */
    replacingEventDate() {
        const replaceRelation = this.getServerAggregatedRelation(event_1.RelationType.Replace);
        if (replaceRelation) {
            const ts = replaceRelation.origin_server_ts;
            if (Number.isFinite(ts)) {
                return new Date(ts);
            }
        }
        else if (this._replacingEvent) {
            return this._replacingEvent.getDate();
        }
    }
    /**
     * Returns the event that wants to redact this event, but hasn't been sent yet.
     * @return {MatrixEvent} the event
     */
    localRedactionEvent() {
        return this._localRedactionEvent;
    }
    /**
     * For relations and redactions, returns the event_id this event is referring to.
     *
     * @return {string?}
     */
    getAssociatedId() {
        const relation = this.getRelation();
        if (relation) {
            return relation.event_id;
        }
        else if (this.isRedaction()) {
            return this.event.redacts;
        }
    }
    /**
     * Checks if this event is associated with another event. See `getAssociatedId`.
     *
     * @return {boolean}
     */
    hasAssocation() {
        return !!this.getAssociatedId();
    }
    /**
     * Update the related id with a new one.
     *
     * Used to replace a local id with remote one before sending
     * an event with a related id.
     *
     * @param {string} eventId the new event id
     */
    updateAssociatedId(eventId) {
        const relation = this.getRelation();
        if (relation) {
            relation.event_id = eventId;
        }
        else if (this.isRedaction()) {
            this.event.redacts = eventId;
        }
    }
    /**
     * Flags an event as cancelled due to future conditions. For example, a verification
     * request event in the same sync transaction may be flagged as cancelled to warn
     * listeners that a cancellation event is coming down the same pipe shortly.
     * @param {boolean} cancelled Whether the event is to be cancelled or not.
     */
    flagCancelled(cancelled = true) {
        this._isCancelled = cancelled;
    }
    /**
     * Gets whether or not the event is flagged as cancelled. See flagCancelled() for
     * more information.
     * @returns {boolean} True if the event is cancelled, false otherwise.
     */
    isCancelled() {
        return this._isCancelled;
    }
    /**
     * Get a copy/snapshot of this event. The returned copy will be loosely linked
     * back to this instance, though will have "frozen" event information. Other
     * properties of this MatrixEvent instance will be copied verbatim, which can
     * mean they are in reference to this instance despite being on the copy too.
     * The reference the snapshot uses does not change, however members aside from
     * the underlying event will not be deeply cloned, thus may be mutated internally.
     * For example, the sender profile will be copied over at snapshot time, and
     * the sender profile internally may mutate without notice to the consumer.
     *
     * This is meant to be used to snapshot the event details themselves, not the
     * features (such as sender) surrounding the event.
     * @returns {MatrixEvent} A snapshot of this event.
     */
    toSnapshot() {
        const ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event)));
        for (const [p, v] of Object.entries(this)) {
            if (p !== "event") { // exclude the thing we just cloned
                ev[p] = v;
            }
        }
        return ev;
    }
    /**
     * Determines if this event is equivalent to the given event. This only checks
     * the event object itself, not the other properties of the event. Intended for
     * use with toSnapshot() to identify events changing.
     * @param {MatrixEvent} otherEvent The other event to check against.
     * @returns {boolean} True if the events are the same, false otherwise.
     */
    isEquivalentTo(otherEvent) {
        if (!otherEvent)
            return false;
        if (otherEvent === this)
            return true;
        const myProps = utils_1.deepSortedObjectEntries(this.event);
        const theirProps = utils_1.deepSortedObjectEntries(otherEvent.event);
        return JSON.stringify(myProps) === JSON.stringify(theirProps);
    }
    /**
     * Summarise the event as JSON for debugging. If encrypted, include both the
     * decrypted and encrypted view of the event. This is named `toJSON` for use
     * with `JSON.stringify` which checks objects for functions named `toJSON`
     * and will call them to customise the output if they are defined.
     *
     * @return {Object}
     */
    toJSON() {
        const event = {
            type: this.getType(),
            sender: this.getSender(),
            content: this.getContent(),
            event_id: this.getId(),
            origin_server_ts: this.getTs(),
            unsigned: this.getUnsigned(),
            room_id: this.getRoomId(),
        };
        // if this is a redaction then attach the redacts key
        if (this.isRedaction()) {
            event.redacts = this.event.redacts;
        }
        if (!this.isEncrypted()) {
            return event;
        }
        return {
            decrypted: event,
            encrypted: this.event,
        };
    }
    setVerificationRequest(request) {
        this.verificationRequest = request;
    }
    setTxnId(txnId) {
        this.txnId = txnId;
    }
    getTxnId() {
        return this.txnId;
    }
}
exports.MatrixEvent = MatrixEvent;
/* REDACT_KEEP_KEYS gives the keys we keep when an event is redacted
 *
 * This is specified here:
 *  http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions
 *
 * Also:
 *  - We keep 'unsigned' since that is created by the local server
 *  - We keep user_id for backwards-compat with v1
 */
const REDACT_KEEP_KEYS = new Set([
    'event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state',
    'content', 'unsigned', 'origin_server_ts',
]);
// a map from event type to the .content keys we keep when an event is redacted
const REDACT_KEEP_CONTENT_MAP = {
    'm.room.member': { 'membership': 1 },
    'm.room.create': { 'creator': 1 },
    'm.room.join_rules': { 'join_rule': 1 },
    'm.room.power_levels': {
        'ban': 1, 'events': 1, 'events_default': 1,
        'kick': 1, 'redact': 1, 'state_default': 1,
        'users': 1, 'users_default': 1,
    },
    'm.room.aliases': { 'aliases': 1 },
};
/**
 * Fires when an event is decrypted
 *
 * @event module:models/event.MatrixEvent#"Event.decrypted"
 *
 * @param {module:models/event.MatrixEvent} event
 *    The matrix event which has been decrypted
 * @param {module:crypto/algorithms/base.DecryptionError?} err
 *    The error that occurred during decryption, or `undefined` if no
 *    error occurred.
 */

},{"../@types/event":58,"../logger":106,"../utils":137,"events":36}],114:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Group = Group;

var utils = _interopRequireWildcard(require("../utils"));

var _events = require("events");

/*
Copyright 2017 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/**
 * @module models/group
 */

/**
 * Construct a new Group.
 *
 * @param {string} groupId The ID of this group.
 *
 * @prop {string} groupId The ID of this group.
 * @prop {string} name The human-readable display name for this group.
 * @prop {string} avatarUrl The mxc URL for this group's avatar.
 * @prop {string} myMembership The logged in user's membership of this group
 * @prop {Object} inviter Infomation about the user who invited the logged in user
 *       to the group, if myMembership is 'invite'.
 * @prop {string} inviter.userId The user ID of the inviter
 */
function Group(groupId) {
  this.groupId = groupId;
  this.name = null;
  this.avatarUrl = null;
  this.myMembership = null;
  this.inviter = null;
}

utils.inherits(Group, _events.EventEmitter);

Group.prototype.setProfile = function (name, avatarUrl) {
  if (this.name === name && this.avatarUrl === avatarUrl) return;
  this.name = name || this.groupId;
  this.avatarUrl = avatarUrl;
  this.emit("Group.profile", this);
};

Group.prototype.setMyMembership = function (membership) {
  if (this.myMembership === membership) return;
  this.myMembership = membership;
  this.emit("Group.myMembership", this);
};
/**
 * Sets the 'inviter' property. This does not emit an event (the inviter
 * will only change when the user is revited / reinvited to a room),
 * so set this before setting myMembership.
 * @param {Object} inviter Infomation about who invited us to the room
 */


Group.prototype.setInviter = function (inviter) {
  this.inviter = inviter;
};
/**
 * Fires whenever a group's profile information is updated.
 * This means the 'name' and 'avatarUrl' properties.
 * @event module:client~MatrixClient#"Group.profile"
 * @param {Group} group The group whose profile was updated.
 * @example
 * matrixClient.on("Group.profile", function(group){
 *   var name = group.name;
 * });
 */

/**
 * Fires whenever the logged in user's membership status of
 * the group is updated.
 * @event module:client~MatrixClient#"Group.myMembership"
 * @param {Group} group The group in which the user's membership changed
 * @example
 * matrixClient.on("Group.myMembership", function(group){
 *   var myMembership = group.myMembership;
 * });
 */

},{"../utils":137,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],115:[function(require,module,exports){
"use strict";
/*
Copyright 2019, 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Relations = void 0;
const events_1 = require("events");
const event_1 = require("./event");
const logger_1 = require("../logger");
const event_2 = require("../@types/event");
/**
 * A container for relation events that supports easy access to common ways of
 * aggregating such events. Each instance holds events that of a single relation
 * type and event type. All of the events also relate to the same original event.
 *
 * The typical way to get one of these containers is via
 * EventTimelineSet#getRelationsForEvent.
 */
class Relations extends events_1.EventEmitter {
    /**
     * @param {RelationType} relationType
     * The type of relation involved, such as "m.annotation", "m.reference",
     * "m.replace", etc.
     * @param {String} eventType
     * The relation event's type, such as "m.reaction", etc.
     * @param {?Room} room
     * Room for this container. May be null for non-room cases, such as the
     * notification timeline.
     */
    constructor(relationType, eventType, room) {
        super();
        this.relationType = relationType;
        this.eventType = eventType;
        this.room = room;
        this.relationEventIds = new Set();
        this.relations = new Set();
        this.annotationsByKey = {};
        this.annotationsBySender = {};
        this.sortedAnnotationsByKey = [];
        this.targetEvent = null;
        this.creationEmitted = false;
        /**
         * Listens for event status changes to remove cancelled events.
         *
         * @param {MatrixEvent} event The event whose status has changed
         * @param {EventStatus} status The new status
         */
        this.onEventStatus = (event, status) => {
            if (!event.isSending()) {
                // Sending is done, so we don't need to listen anymore
                event.removeListener("Event.status", this.onEventStatus);
                return;
            }
            if (status !== event_1.EventStatus.CANCELLED) {
                return;
            }
            // Event was cancelled, remove from the collection
            event.removeListener("Event.status", this.onEventStatus);
            this.removeEvent(event);
        };
        /**
         * For relations that have been redacted, we want to remove them from
         * aggregation data sets and emit an update event.
         *
         * To do so, we listen for `Event.beforeRedaction`, which happens:
         *   - after the server accepted the redaction and remote echoed back to us
         *   - before the original event has been marked redacted in the client
         *
         * @param {MatrixEvent} redactedEvent
         * The original relation event that is about to be redacted.
         */
        this.onBeforeRedaction = (redactedEvent) => __awaiter(this, void 0, void 0, function* () {
            if (!this.relations.has(redactedEvent)) {
                return;
            }
            this.relations.delete(redactedEvent);
            if (this.relationType === event_2.RelationType.Annotation) {
                // Remove the redacted annotation from aggregation by key
                this.removeAnnotationFromAggregation(redactedEvent);
            }
            else if (this.relationType === event_2.RelationType.Replace && this.targetEvent) {
                const lastReplacement = yield this.getLastReplacement();
                this.targetEvent.makeReplaced(lastReplacement);
            }
            redactedEvent.removeListener("Event.beforeRedaction", this.onBeforeRedaction);
            this.emit("Relations.redaction", redactedEvent);
        });
    }
    /**
     * Add relation events to this collection.
     *
     * @param {MatrixEvent} event
     * The new relation event to be added.
     */
    addEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.relationEventIds.has(event.getId())) {
                return;
            }
            const relation = event.getRelation();
            if (!relation) {
                logger_1.logger.error("Event must have relation info");
                return;
            }
            const relationType = relation.rel_type;
            const eventType = event.getType();
            if (this.relationType !== relationType || this.eventType !== eventType) {
                logger_1.logger.error("Event relation info doesn't match this container");
                return;
            }
            // If the event is in the process of being sent, listen for cancellation
            // so we can remove the event from the collection.
            if (event.isSending()) {
                event.on("Event.status", this.onEventStatus);
            }
            this.relations.add(event);
            this.relationEventIds.add(event.getId());
            if (this.relationType === event_2.RelationType.Annotation) {
                this.addAnnotationToAggregation(event);
            }
            else if (this.relationType === event_2.RelationType.Replace && this.targetEvent) {
                const lastReplacement = yield this.getLastReplacement();
                this.targetEvent.makeReplaced(lastReplacement);
            }
            event.on("Event.beforeRedaction", this.onBeforeRedaction);
            this.emit("Relations.add", event);
            this.maybeEmitCreated();
        });
    }
    /**
     * Remove relation event from this collection.
     *
     * @param {MatrixEvent} event
     * The relation event to remove.
     */
    removeEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.relations.has(event)) {
                return;
            }
            const relation = event.getRelation();
            if (!relation) {
                logger_1.logger.error("Event must have relation info");
                return;
            }
            const relationType = relation.rel_type;
            const eventType = event.getType();
            if (this.relationType !== relationType || this.eventType !== eventType) {
                logger_1.logger.error("Event relation info doesn't match this container");
                return;
            }
            this.relations.delete(event);
            if (this.relationType === event_2.RelationType.Annotation) {
                this.removeAnnotationFromAggregation(event);
            }
            else if (this.relationType === event_2.RelationType.Replace && this.targetEvent) {
                const lastReplacement = yield this.getLastReplacement();
                this.targetEvent.makeReplaced(lastReplacement);
            }
            this.emit("Relations.remove", event);
        });
    }
    /**
     * Get all relation events in this collection.
     *
     * These are currently in the order of insertion to this collection, which
     * won't match timeline order in the case of scrollback.
     * TODO: Tweak `addEvent` to insert correctly for scrollback.
     *
     * @return {Array}
     * Relation events in insertion order.
     */
    getRelations() {
        return [...this.relations];
    }
    addAnnotationToAggregation(event) {
        const { key } = event.getRelation();
        if (!key) {
            return;
        }
        let eventsForKey = this.annotationsByKey[key];
        if (!eventsForKey) {
            eventsForKey = this.annotationsByKey[key] = new Set();
            this.sortedAnnotationsByKey.push([key, eventsForKey]);
        }
        // Add the new event to the set for this key
        eventsForKey.add(event);
        // Re-sort the [key, events] pairs in descending order of event count
        this.sortedAnnotationsByKey.sort((a, b) => {
            const aEvents = a[1];
            const bEvents = b[1];
            return bEvents.size - aEvents.size;
        });
        const sender = event.getSender();
        let eventsFromSender = this.annotationsBySender[sender];
        if (!eventsFromSender) {
            eventsFromSender = this.annotationsBySender[sender] = new Set();
        }
        // Add the new event to the set for this sender
        eventsFromSender.add(event);
    }
    removeAnnotationFromAggregation(event) {
        const { key } = event.getRelation();
        if (!key) {
            return;
        }
        const eventsForKey = this.annotationsByKey[key];
        if (eventsForKey) {
            eventsForKey.delete(event);
            // Re-sort the [key, events] pairs in descending order of event count
            this.sortedAnnotationsByKey.sort((a, b) => {
                const aEvents = a[1];
                const bEvents = b[1];
                return bEvents.size - aEvents.size;
            });
        }
        const sender = event.getSender();
        const eventsFromSender = this.annotationsBySender[sender];
        if (eventsFromSender) {
            eventsFromSender.delete(event);
        }
    }
    /**
     * Get all events in this collection grouped by key and sorted by descending
     * event count in each group.
     *
     * This is currently only supported for the annotation relation type.
     *
     * @return {Array}
     * An array of [key, events] pairs sorted by descending event count.
     * The events are stored in a Set (which preserves insertion order).
     */
    getSortedAnnotationsByKey() {
        if (this.relationType !== event_2.RelationType.Annotation) {
            // Other relation types are not grouped currently.
            return null;
        }
        return this.sortedAnnotationsByKey;
    }
    /**
     * Get all events in this collection grouped by sender.
     *
     * This is currently only supported for the annotation relation type.
     *
     * @return {Object}
     * An object with each relation sender as a key and the matching Set of
     * events for that sender as a value.
     */
    getAnnotationsBySender() {
        if (this.relationType !== event_2.RelationType.Annotation) {
            // Other relation types are not grouped currently.
            return null;
        }
        return this.annotationsBySender;
    }
    /**
     * Returns the most recent (and allowed) m.replace relation, if any.
     *
     * This is currently only supported for the m.replace relation type,
     * once the target event is known, see `addEvent`.
     *
     * @return {MatrixEvent?}
     */
    getLastReplacement() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.relationType !== event_2.RelationType.Replace) {
                // Aggregating on last only makes sense for this relation type
                return null;
            }
            if (!this.targetEvent) {
                // Don't know which replacements to accept yet.
                // This method shouldn't be called before the original
                // event is known anyway.
                return null;
            }
            // the all-knowning server tells us that the event at some point had
            // this timestamp for its replacement, so any following replacement should definitely not be less
            const replaceRelation = this.targetEvent.getServerAggregatedRelation(event_2.RelationType.Replace);
            const minTs = replaceRelation && replaceRelation.origin_server_ts;
            const lastReplacement = this.getRelations().reduce((last, event) => {
                if (event.getSender() !== this.targetEvent.getSender()) {
                    return last;
                }
                if (minTs && minTs > event.getTs()) {
                    return last;
                }
                if (last && last.getTs() > event.getTs()) {
                    return last;
                }
                return event;
            }, null);
            if (lastReplacement === null || lastReplacement === void 0 ? void 0 : lastReplacement.shouldAttemptDecryption()) {
                yield lastReplacement.attemptDecryption(this.room.client.crypto);
            }
            else if (lastReplacement === null || lastReplacement === void 0 ? void 0 : lastReplacement.isBeingDecrypted()) {
                yield lastReplacement.getDecryptionPromise();
            }
            return lastReplacement;
        });
    }
    /*
     * @param {MatrixEvent} targetEvent the event the relations are related to.
     */
    setTargetEvent(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.targetEvent) {
                return;
            }
            this.targetEvent = event;
            if (this.relationType === event_2.RelationType.Replace) {
                const replacement = yield this.getLastReplacement();
                // this is the initial update, so only call it if we already have something
                // to not emit Event.replaced needlessly
                if (replacement) {
                    this.targetEvent.makeReplaced(replacement);
                }
            }
            this.maybeEmitCreated();
        });
    }
    maybeEmitCreated() {
        if (this.creationEmitted) {
            return;
        }
        // Only emit we're "created" once we have a target event instance _and_
        // at least one related event.
        if (!this.targetEvent || !this.relations.size) {
            return;
        }
        this.creationEmitted = true;
        this.targetEvent.emit("Event.relationsCreated", this.relationType, this.eventType);
    }
}
exports.Relations = Relations;

},{"../@types/event":58,"../logger":106,"./event":113,"events":36}],116:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoomMember = void 0;
/**
 * @module models/room-member
 */
const events_1 = require("events");
const content_repo_1 = require("../content-repo");
const utils = __importStar(require("../utils"));
class RoomMember extends events_1.EventEmitter {
    /**
     * Construct a new room member.
     *
     * @constructor
     * @alias module:models/room-member
     *
     * @param {string} roomId The room ID of the member.
     * @param {string} userId The user ID of the member.
     * @prop {string} roomId The room ID for this member.
     * @prop {string} userId The user ID of this member.
     * @prop {boolean} typing True if the room member is currently typing.
     * @prop {string} name The human-readable name for this room member. This will be
     * disambiguated with a suffix of " (@user_id:matrix.org)" if another member shares the
     * same displayname.
     * @prop {string} rawDisplayName The ambiguous displayname of this room member.
     * @prop {Number} powerLevel The power level for this room member.
     * @prop {Number} powerLevelNorm The normalised power level (0-100) for this
     * room member.
     * @prop {User} user The User object for this room member, if one exists.
     * @prop {string} membership The membership state for this room member e.g. 'join'.
     * @prop {Object} events The events describing this RoomMember.
     * @prop {MatrixEvent} events.member The m.room.member event for this RoomMember.
     * @prop {boolean} disambiguate True if the member's name is disambiguated.
     */
    constructor(roomId, userId) {
        super();
        this.roomId = roomId;
        this.userId = userId;
        this._isOutOfBand = false;
        // XXX these should be read-only
        this.typing = false;
        this.powerLevel = 0;
        this.powerLevelNorm = 0;
        this.user = null;
        this.membership = null;
        this.disambiguate = false;
        this.events = {
            member: null,
        };
        this.name = userId;
        this.rawDisplayName = userId;
        this.updateModifiedTime();
    }
    /**
     * Mark the member as coming from a channel that is not sync
     */
    markOutOfBand() {
        this._isOutOfBand = true;
    }
    /**
     * @return {boolean} does the member come from a channel that is not sync?
     * This is used to store the member seperately
     * from the sync state so it available across browser sessions.
     */
    isOutOfBand() {
        return this._isOutOfBand;
    }
    /**
     * Update this room member's membership event. May fire "RoomMember.name" if
     * this event updates this member's name.
     * @param {MatrixEvent} event The <code>m.room.member</code> event
     * @param {RoomState} roomState Optional. The room state to take into account
     * when calculating (e.g. for disambiguating users with the same name).
     * @fires module:client~MatrixClient#event:"RoomMember.name"
     * @fires module:client~MatrixClient#event:"RoomMember.membership"
     */
    setMembershipEvent(event, roomState) {
        const displayName = event.getDirectionalContent().displayname;
        if (event.getType() !== "m.room.member") {
            return;
        }
        this._isOutOfBand = false;
        this.events.member = event;
        const oldMembership = this.membership;
        this.membership = event.getDirectionalContent().membership;
        this.disambiguate = shouldDisambiguate(this.userId, displayName, roomState);
        const oldName = this.name;
        this.name = calculateDisplayName(this.userId, displayName, roomState, this.disambiguate);
        this.rawDisplayName = event.getDirectionalContent().displayname || this.userId;
        if (oldMembership !== this.membership) {
            this.updateModifiedTime();
            this.emit("RoomMember.membership", event, this, oldMembership);
        }
        if (oldName !== this.name) {
            this.updateModifiedTime();
            this.emit("RoomMember.name", event, this, oldName);
        }
    }
    /**
     * Update this room member's power level event. May fire
     * "RoomMember.powerLevel" if this event updates this member's power levels.
     * @param {MatrixEvent} powerLevelEvent The <code>m.room.power_levels</code>
     * event
     * @fires module:client~MatrixClient#event:"RoomMember.powerLevel"
     */
    setPowerLevelEvent(powerLevelEvent) {
        if (powerLevelEvent.getType() !== "m.room.power_levels") {
            return;
        }
        const evContent = powerLevelEvent.getDirectionalContent();
        let maxLevel = evContent.users_default || 0;
        const users = evContent.users || {};
        Object.values(users).forEach(function (lvl) {
            maxLevel = Math.max(maxLevel, lvl);
        });
        const oldPowerLevel = this.powerLevel;
        const oldPowerLevelNorm = this.powerLevelNorm;
        if (users[this.userId] !== undefined && Number.isInteger(users[this.userId])) {
            this.powerLevel = users[this.userId];
        }
        else if (evContent.users_default !== undefined) {
            this.powerLevel = evContent.users_default;
        }
        else {
            this.powerLevel = 0;
        }
        this.powerLevelNorm = 0;
        if (maxLevel > 0) {
            this.powerLevelNorm = (this.powerLevel * 100) / maxLevel;
        }
        // emit for changes in powerLevelNorm as well (since the app will need to
        // redraw everyone's level if the max has changed)
        if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) {
            this.updateModifiedTime();
            this.emit("RoomMember.powerLevel", powerLevelEvent, this);
        }
    }
    /**
     * Update this room member's typing event. May fire "RoomMember.typing" if
     * this event changes this member's typing state.
     * @param {MatrixEvent} event The typing event
     * @fires module:client~MatrixClient#event:"RoomMember.typing"
     */
    setTypingEvent(event) {
        if (event.getType() !== "m.typing") {
            return;
        }
        const oldTyping = this.typing;
        this.typing = false;
        const typingList = event.getContent().user_ids;
        if (!Array.isArray(typingList)) {
            // malformed event :/ bail early. TODO: whine?
            return;
        }
        if (typingList.indexOf(this.userId) !== -1) {
            this.typing = true;
        }
        if (oldTyping !== this.typing) {
            this.updateModifiedTime();
            this.emit("RoomMember.typing", event, this);
        }
    }
    /**
     * Update the last modified time to the current time.
     */
    updateModifiedTime() {
        this._modified = Date.now();
    }
    /**
     * Get the timestamp when this RoomMember was last updated. This timestamp is
     * updated when properties on this RoomMember are updated.
     * It is updated <i>before</i> firing events.
     * @return {number} The timestamp
     */
    getLastModifiedTime() {
        return this._modified;
    }
    isKicked() {
        return this.membership === "leave" &&
            this.events.member.getSender() !== this.events.member.getStateKey();
    }
    /**
     * If this member was invited with the is_direct flag set, return
     * the user that invited this member
     * @return {string} user id of the inviter
     */
    getDMInviter() {
        // when not available because that room state hasn't been loaded in,
        // we don't really know, but more likely to not be a direct chat
        if (this.events.member) {
            // TODO: persist the is_direct flag on the member as more member events
            //       come in caused by displayName changes.
            // the is_direct flag is set on the invite member event.
            // This is copied on the prev_content section of the join member event
            // when the invite is accepted.
            const memberEvent = this.events.member;
            let memberContent = memberEvent.getContent();
            let inviteSender = memberEvent.getSender();
            if (memberContent.membership === "join") {
                memberContent = memberEvent.getPrevContent();
                inviteSender = memberEvent.getUnsigned().prev_sender;
            }
            if (memberContent.membership === "invite" && memberContent.is_direct) {
                return inviteSender;
            }
        }
    }
    /**
     * Get the avatar URL for a room member.
     * @param {string} baseUrl The base homeserver URL See
     * {@link module:client~MatrixClient#getHomeserverUrl}.
     * @param {Number} width The desired width of the thumbnail.
     * @param {Number} height The desired height of the thumbnail.
     * @param {string} resizeMethod The thumbnail resize method to use, either
     * "crop" or "scale".
     * @param {Boolean} allowDefault (optional) Passing false causes this method to
     * return null if the user has no avatar image. Otherwise, a default image URL
     * will be returned. Default: true. (Deprecated)
     * @param {Boolean} allowDirectLinks (optional) If true, the avatar URL will be
     * returned even if it is a direct hyperlink rather than a matrix content URL.
     * If false, any non-matrix content URLs will be ignored. Setting this option to
     * true will expose URLs that, if fetched, will leak information about the user
     * to anyone who they share a room with.
     * @return {?string} the avatar URL or null.
     */
    getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault = true, allowDirectLinks) {
        const rawUrl = this.getMxcAvatarUrl();
        if (!rawUrl && !allowDefault) {
            return null;
        }
        const httpUrl = content_repo_1.getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks);
        if (httpUrl) {
            return httpUrl;
        }
        return null;
    }
    /**
     * get the mxc avatar url, either from a state event, or from a lazily loaded member
     * @return {string} the mxc avatar url
     */
    getMxcAvatarUrl() {
        if (this.events.member) {
            return this.events.member.getDirectionalContent().avatar_url;
        }
        else if (this.user) {
            return this.user.avatarUrl;
        }
        return null;
    }
}
exports.RoomMember = RoomMember;
const MXID_PATTERN = /@.+:.+/;
const LTR_RTL_PATTERN = /[\u200E\u200F\u202A-\u202F]/;
function shouldDisambiguate(selfUserId, displayName, roomState) {
    if (!displayName || displayName === selfUserId)
        return false;
    // First check if the displayname is something we consider truthy
    // after stripping it of zero width characters and padding spaces
    if (!utils.removeHiddenChars(displayName))
        return false;
    if (!roomState)
        return false;
    // Next check if the name contains something that look like a mxid
    // If it does, it may be someone trying to impersonate someone else
    // Show full mxid in this case
    if (MXID_PATTERN.test(displayName))
        return true;
    // Also show mxid if the display name contains any LTR/RTL characters as these
    // make it very difficult for us to find similar *looking* display names
    // E.g "Mark" could be cloned by writing "kraM" but in RTL.
    if (LTR_RTL_PATTERN.test(displayName))
        return true;
    // Also show mxid if there are other people with the same or similar
    // displayname, after hidden character removal.
    const userIds = roomState.getUserIdsWithDisplayName(displayName);
    if (userIds.some((u) => u !== selfUserId))
        return true;
    return false;
}
function calculateDisplayName(selfUserId, displayName, roomState, disambiguate) {
    if (disambiguate)
        return displayName + " (" + selfUserId + ")";
    if (!displayName || displayName === selfUserId)
        return selfUserId;
    // First check if the displayname is something we consider truthy
    // after stripping it of zero width characters and padding spaces
    if (!utils.removeHiddenChars(displayName))
        return selfUserId;
    return displayName;
}
/**
 * Fires whenever any room member's name changes.
 * @event module:client~MatrixClient#"RoomMember.name"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomMember} member The member whose RoomMember.name changed.
 * @param {string?} oldName The previous name. Null if the member didn't have a
 *    name previously.
 * @example
 * matrixClient.on("RoomMember.name", function(event, member){
 *   var newName = member.name;
 * });
 */
/**
 * Fires whenever any room member's membership state changes.
 * @event module:client~MatrixClient#"RoomMember.membership"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomMember} member The member whose RoomMember.membership changed.
 * @param {string?} oldMembership The previous membership state. Null if it's a
 *    new member.
 * @example
 * matrixClient.on("RoomMember.membership", function(event, member, oldMembership){
 *   var newState = member.membership;
 * });
 */
/**
 * Fires whenever any room member's typing state changes.
 * @event module:client~MatrixClient#"RoomMember.typing"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomMember} member The member whose RoomMember.typing changed.
 * @example
 * matrixClient.on("RoomMember.typing", function(event, member){
 *   var isTyping = member.typing;
 * });
 */
/**
 * Fires whenever any room member's power level changes.
 * @event module:client~MatrixClient#"RoomMember.powerLevel"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomMember} member The member whose RoomMember.powerLevel changed.
 * @example
 * matrixClient.on("RoomMember.powerLevel", function(event, member){
 *   var newPowerLevel = member.powerLevel;
 *   var newNormPowerLevel = member.powerLevelNorm;
 * });
 */

},{"../content-repo":66,"../utils":137,"events":36}],117:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoomState = void 0;
/**
 * @module models/room-state
 */
const events_1 = require("events");
const room_member_1 = require("./room-member");
const logger_1 = require("../logger");
const utils = __importStar(require("../utils"));
const event_1 = require("../@types/event");
// possible statuses for out-of-band member loading
var OobStatus;
(function (OobStatus) {
    OobStatus[OobStatus["NotStarted"] = 0] = "NotStarted";
    OobStatus[OobStatus["InProgress"] = 1] = "InProgress";
    OobStatus[OobStatus["Finished"] = 2] = "Finished";
})(OobStatus || (OobStatus = {}));
class RoomState extends events_1.EventEmitter {
    /**
     * Construct room state.
     *
     * Room State represents the state of the room at a given point.
     * It can be mutated by adding state events to it.
     * There are two types of room member associated with a state event:
     * normal member objects (accessed via getMember/getMembers) which mutate
     * with the state to represent the current state of that room/user, eg.
     * the object returned by getMember('@bob:example.com') will mutate to
     * get a different display name if Bob later changes his display name
     * in the room.
     * There are also 'sentinel' members (accessed via getSentinelMember).
     * These also represent the state of room members at the point in time
     * represented by the RoomState object, but unlike objects from getMember,
     * sentinel objects will always represent the room state as at the time
     * getSentinelMember was called, so if Bob subsequently changes his display
     * name, a room member object previously acquired with getSentinelMember
     * will still have his old display name. Calling getSentinelMember again
     * after the display name change will return a new RoomMember object
     * with Bob's new display name.
     *
     * @constructor
     * @param {?string} roomId Optional. The ID of the room which has this state.
     * If none is specified it just tracks paginationTokens, useful for notifTimelineSet
     * @param {?object} oobMemberFlags Optional. The state of loading out of bound members.
     * As the timeline might get reset while they are loading, this state needs to be inherited
     * and shared when the room state is cloned for the new timeline.
     * This should only be passed from clone.
     * @prop {Object.<string, RoomMember>} members The room member dictionary, keyed
     * on the user's ID.
     * @prop {Object.<string, Object.<string, MatrixEvent>>} events The state
     * events dictionary, keyed on the event type and then the state_key value.
     * @prop {string} paginationToken The pagination token for this state.
     */
    constructor(roomId, oobMemberFlags = { status: OobStatus.NotStarted }) {
        super();
        this.roomId = roomId;
        this.oobMemberFlags = oobMemberFlags;
        this.sentinels = {}; // userId: RoomMember
        // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)
        this.displayNameToUserIds = {};
        this.userIdsToDisplayNames = {};
        this.tokenToInvite = {}; // 3pid invite state_key to m.room.member invite
        this.joinedMemberCount = null; // cache of the number of joined members
        // joined members count from summary api
        // once set, we know the server supports the summary api
        // and we should only trust that
        // we could also only trust that before OOB members
        // are loaded but doesn't seem worth the hassle atm
        this.summaryJoinedMemberCount = null;
        // same for invited member count
        this.invitedMemberCount = null;
        this.summaryInvitedMemberCount = null;
        // XXX: Should be read-only
        this.members = {}; // userId: RoomMember
        this.events = new Map(); // Map<eventType, Map<stateKey, MatrixEvent>>
        this.paginationToken = null;
        this.updateModifiedTime();
    }
    /**
     * Returns the number of joined members in this room
     * This method caches the result.
     * @return {number} The number of members in this room whose membership is 'join'
     */
    getJoinedMemberCount() {
        if (this.summaryJoinedMemberCount !== null) {
            return this.summaryJoinedMemberCount;
        }
        if (this.joinedMemberCount === null) {
            this.joinedMemberCount = this.getMembers().reduce((count, m) => {
                return m.membership === 'join' ? count + 1 : count;
            }, 0);
        }
        return this.joinedMemberCount;
    }
    /**
     * Set the joined member count explicitly (like from summary part of the sync response)
     * @param {number} count the amount of joined members
     */
    setJoinedMemberCount(count) {
        this.summaryJoinedMemberCount = count;
    }
    /**
     * Returns the number of invited members in this room
     * @return {number} The number of members in this room whose membership is 'invite'
     */
    getInvitedMemberCount() {
        if (this.summaryInvitedMemberCount !== null) {
            return this.summaryInvitedMemberCount;
        }
        if (this.invitedMemberCount === null) {
            this.invitedMemberCount = this.getMembers().reduce((count, m) => {
                return m.membership === 'invite' ? count + 1 : count;
            }, 0);
        }
        return this.invitedMemberCount;
    }
    /**
     * Set the amount of invited members in this room
     * @param {number} count the amount of invited members
     */
    setInvitedMemberCount(count) {
        this.summaryInvitedMemberCount = count;
    }
    /**
     * Get all RoomMembers in this room.
     * @return {Array<RoomMember>} A list of RoomMembers.
     */
    getMembers() {
        return Object.values(this.members);
    }
    /**
     * Get all RoomMembers in this room, excluding the user IDs provided.
     * @param {Array<string>} excludedIds The user IDs to exclude.
     * @return {Array<RoomMember>} A list of RoomMembers.
     */
    getMembersExcept(excludedIds) {
        return this.getMembers().filter((m) => !excludedIds.includes(m.userId));
    }
    /**
     * Get a room member by their user ID.
     * @param {string} userId The room member's user ID.
     * @return {RoomMember} The member or null if they do not exist.
     */
    getMember(userId) {
        return this.members[userId] || null;
    }
    /**
     * Get a room member whose properties will not change with this room state. You
     * typically want this if you want to attach a RoomMember to a MatrixEvent which
     * may no longer be represented correctly by Room.currentState or Room.oldState.
     * The term 'sentinel' refers to the fact that this RoomMember is an unchanging
     * guardian for state at this particular point in time.
     * @param {string} userId The room member's user ID.
     * @return {RoomMember} The member or null if they do not exist.
     */
    getSentinelMember(userId) {
        if (!userId)
            return null;
        let sentinel = this.sentinels[userId];
        if (sentinel === undefined) {
            sentinel = new room_member_1.RoomMember(this.roomId, userId);
            const member = this.members[userId];
            if (member) {
                sentinel.setMembershipEvent(member.events.member, this);
            }
            this.sentinels[userId] = sentinel;
        }
        return sentinel;
    }
    getStateEvents(eventType, stateKey) {
        if (!this.events.has(eventType)) {
            // no match
            return stateKey === undefined ? [] : null;
        }
        if (stateKey === undefined) { // return all values
            return Array.from(this.events.get(eventType).values());
        }
        const event = this.events.get(eventType).get(stateKey);
        return event ? event : null;
    }
    /**
     * Creates a copy of this room state so that mutations to either won't affect the other.
     * @return {RoomState} the copy of the room state
     */
    clone() {
        const copy = new RoomState(this.roomId, this.oobMemberFlags);
        // Ugly hack: because setStateEvents will mark
        // members as susperseding future out of bound members
        // if loading is in progress (through oobMemberFlags)
        // since these are not new members, we're merely copying them
        // set the status to not started
        // after copying, we set back the status
        const status = this.oobMemberFlags.status;
        this.oobMemberFlags.status = OobStatus.NotStarted;
        Array.from(this.events.values()).forEach((eventsByStateKey) => {
            copy.setStateEvents(Array.from(eventsByStateKey.values()));
        });
        // Ugly hack: see above
        this.oobMemberFlags.status = status;
        if (this.summaryInvitedMemberCount !== null) {
            copy.setInvitedMemberCount(this.getInvitedMemberCount());
        }
        if (this.summaryJoinedMemberCount !== null) {
            copy.setJoinedMemberCount(this.getJoinedMemberCount());
        }
        // copy out of band flags if needed
        if (this.oobMemberFlags.status == OobStatus.Finished) {
            // copy markOutOfBand flags
            this.getMembers().forEach((member) => {
                if (member.isOutOfBand()) {
                    const copyMember = copy.getMember(member.userId);
                    copyMember.markOutOfBand();
                }
            });
        }
        return copy;
    }
    /**
     * Add previously unknown state events.
     * When lazy loading members while back-paginating,
     * the relevant room state for the timeline chunk at the end
     * of the chunk can be set with this method.
     * @param {MatrixEvent[]} events state events to prepend
     */
    setUnknownStateEvents(events) {
        const unknownStateEvents = events.filter((event) => {
            return !this.events.has(event.getType()) ||
                !this.events.get(event.getType()).has(event.getStateKey());
        });
        this.setStateEvents(unknownStateEvents);
    }
    /**
     * Add an array of one or more state MatrixEvents, overwriting
     * any existing state with the same {type, stateKey} tuple. Will fire
     * "RoomState.events" for every event added. May fire "RoomState.members"
     * if there are <code>m.room.member</code> events.
     * @param {MatrixEvent[]} stateEvents a list of state events for this room.
     * @fires module:client~MatrixClient#event:"RoomState.members"
     * @fires module:client~MatrixClient#event:"RoomState.newMember"
     * @fires module:client~MatrixClient#event:"RoomState.events"
     */
    setStateEvents(stateEvents) {
        this.updateModifiedTime();
        // update the core event dict
        stateEvents.forEach((event) => {
            if (event.getRoomId() !== this.roomId) {
                return;
            }
            if (!event.isState()) {
                return;
            }
            const lastStateEvent = this.getStateEventMatching(event);
            this.setStateEvent(event);
            if (event.getType() === event_1.EventType.RoomMember) {
                this.updateDisplayNameCache(event.getStateKey(), event.getContent().displayname);
                this.updateThirdPartyTokenCache(event);
            }
            this.emit("RoomState.events", event, this, lastStateEvent);
        });
        // update higher level data structures. This needs to be done AFTER the
        // core event dict as these structures may depend on other state events in
        // the given array (e.g. disambiguating display names in one go to do both
        // clashing names rather than progressively which only catches 1 of them).
        stateEvents.forEach((event) => {
            if (event.getRoomId() !== this.roomId) {
                return;
            }
            if (!event.isState()) {
                return;
            }
            if (event.getType() === event_1.EventType.RoomMember) {
                const userId = event.getStateKey();
                // leave events apparently elide the displayname or avatar_url,
                // so let's fake one up so that we don't leak user ids
                // into the timeline
                if (event.getContent().membership === "leave" ||
                    event.getContent().membership === "ban") {
                    event.getContent().avatar_url =
                        event.getContent().avatar_url ||
                            event.getPrevContent().avatar_url;
                    event.getContent().displayname =
                        event.getContent().displayname ||
                            event.getPrevContent().displayname;
                }
                const member = this.getOrCreateMember(userId, event);
                member.setMembershipEvent(event, this);
                this.updateMember(member);
                this.emit("RoomState.members", event, this, member);
            }
            else if (event.getType() === event_1.EventType.RoomPowerLevels) {
                // events with unknown state keys should be ignored
                // and should not aggregate onto members power levels
                if (event.getStateKey() !== "") {
                    return;
                }
                const members = Object.values(this.members);
                members.forEach((member) => {
                    // We only propagate `RoomState.members` event if the
                    // power levels has been changed
                    // large room suffer from large re-rendering especially when not needed
                    const oldLastModified = member.getLastModifiedTime();
                    member.setPowerLevelEvent(event);
                    if (oldLastModified !== member.getLastModifiedTime()) {
                        this.emit("RoomState.members", event, this, member);
                    }
                });
                // assume all our sentinels are now out-of-date
                this.sentinels = {};
            }
        });
    }
    /**
     * Looks up a member by the given userId, and if it doesn't exist,
     * create it and emit the `RoomState.newMember` event.
     * This method makes sure the member is added to the members dictionary
     * before emitting, as this is done from setStateEvents and setOutOfBandMember.
     * @param {string} userId the id of the user to look up
     * @param {MatrixEvent} event the membership event for the (new) member. Used to emit.
     * @fires module:client~MatrixClient#event:"RoomState.newMember"
     * @returns {RoomMember} the member, existing or newly created.
     */
    getOrCreateMember(userId, event) {
        let member = this.members[userId];
        if (!member) {
            member = new room_member_1.RoomMember(this.roomId, userId);
            // add member to members before emitting any events,
            // as event handlers often lookup the member
            this.members[userId] = member;
            this.emit("RoomState.newMember", event, this, member);
        }
        return member;
    }
    setStateEvent(event) {
        if (!this.events.has(event.getType())) {
            this.events.set(event.getType(), new Map());
        }
        this.events.get(event.getType()).set(event.getStateKey(), event);
    }
    getStateEventMatching(event) {
        if (!this.events.has(event.getType()))
            return null;
        return this.events.get(event.getType()).get(event.getStateKey());
    }
    updateMember(member) {
        // this member may have a power level already, so set it.
        const pwrLvlEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, "");
        if (pwrLvlEvent) {
            member.setPowerLevelEvent(pwrLvlEvent);
        }
        // blow away the sentinel which is now outdated
        delete this.sentinels[member.userId];
        this.members[member.userId] = member;
        this.joinedMemberCount = null;
        this.invitedMemberCount = null;
    }
    /**
     * Get the out-of-band members loading state, whether loading is needed or not.
     * Note that loading might be in progress and hence isn't needed.
     * @return {boolean} whether or not the members of this room need to be loaded
     */
    needsOutOfBandMembers() {
        return this.oobMemberFlags.status === OobStatus.NotStarted;
    }
    /**
     * Mark this room state as waiting for out-of-band members,
     * ensuring it doesn't ask for them to be requested again
     * through needsOutOfBandMembers
     */
    markOutOfBandMembersStarted() {
        if (this.oobMemberFlags.status !== OobStatus.NotStarted) {
            return;
        }
        this.oobMemberFlags.status = OobStatus.InProgress;
    }
    /**
     * Mark this room state as having failed to fetch out-of-band members
     */
    markOutOfBandMembersFailed() {
        if (this.oobMemberFlags.status !== OobStatus.InProgress) {
            return;
        }
        this.oobMemberFlags.status = OobStatus.NotStarted;
    }
    /**
     * Clears the loaded out-of-band members
     */
    clearOutOfBandMembers() {
        let count = 0;
        Object.keys(this.members).forEach((userId) => {
            const member = this.members[userId];
            if (member.isOutOfBand()) {
                ++count;
                delete this.members[userId];
            }
        });
        logger_1.logger.log(`LL: RoomState removed ${count} members...`);
        this.oobMemberFlags.status = OobStatus.NotStarted;
    }
    /**
     * Sets the loaded out-of-band members.
     * @param {MatrixEvent[]} stateEvents array of membership state events
     */
    setOutOfBandMembers(stateEvents) {
        logger_1.logger.log(`LL: RoomState about to set ${stateEvents.length} OOB members ...`);
        if (this.oobMemberFlags.status !== OobStatus.InProgress) {
            return;
        }
        logger_1.logger.log(`LL: RoomState put in finished state ...`);
        this.oobMemberFlags.status = OobStatus.Finished;
        stateEvents.forEach((e) => this.setOutOfBandMember(e));
    }
    /**
     * Sets a single out of band member, used by both setOutOfBandMembers and clone
     * @param {MatrixEvent} stateEvent membership state event
     */
    setOutOfBandMember(stateEvent) {
        if (stateEvent.getType() !== event_1.EventType.RoomMember) {
            return;
        }
        const userId = stateEvent.getStateKey();
        const existingMember = this.getMember(userId);
        // never replace members received as part of the sync
        if (existingMember && !existingMember.isOutOfBand()) {
            return;
        }
        const member = this.getOrCreateMember(userId, stateEvent);
        member.setMembershipEvent(stateEvent, this);
        // needed to know which members need to be stored seperately
        // as they are not part of the sync accumulator
        // this is cleared by setMembershipEvent so when it's updated through /sync
        member.markOutOfBand();
        this.updateDisplayNameCache(member.userId, member.name);
        this.setStateEvent(stateEvent);
        this.updateMember(member);
        this.emit("RoomState.members", stateEvent, this, member);
    }
    /**
     * Set the current typing event for this room.
     * @param {MatrixEvent} event The typing event
     */
    setTypingEvent(event) {
        Object.values(this.members).forEach(function (member) {
            member.setTypingEvent(event);
        });
    }
    /**
     * Get the m.room.member event which has the given third party invite token.
     *
     * @param {string} token The token
     * @return {?MatrixEvent} The m.room.member event or null
     */
    getInviteForThreePidToken(token) {
        return this.tokenToInvite[token] || null;
    }
    /**
     * Update the last modified time to the current time.
     */
    updateModifiedTime() {
        this.modified = Date.now();
    }
    /**
     * Get the timestamp when this room state was last updated. This timestamp is
     * updated when this object has received new state events.
     * @return {number} The timestamp
     */
    getLastModifiedTime() {
        return this.modified;
    }
    /**
     * Get user IDs with the specified or similar display names.
     * @param {string} displayName The display name to get user IDs from.
     * @return {string[]} An array of user IDs or an empty array.
     */
    getUserIdsWithDisplayName(displayName) {
        return this.displayNameToUserIds[utils.removeHiddenChars(displayName)] || [];
    }
    /**
     * Returns true if userId is in room, event is not redacted and either sender of
     * mxEvent or has power level sufficient to redact events other than their own.
     * @param {MatrixEvent} mxEvent The event to test permission for
     * @param {string} userId The user ID of the user to test permission for
     * @return {boolean} true if the given used ID can redact given event
     */
    maySendRedactionForEvent(mxEvent, userId) {
        const member = this.getMember(userId);
        if (!member || member.membership === 'leave')
            return false;
        if (mxEvent.status || mxEvent.isRedacted())
            return false;
        // The user may have been the sender, but they can't redact their own message
        // if redactions are blocked.
        const canRedact = this.maySendEvent(event_1.EventType.RoomRedaction, userId);
        if (mxEvent.getSender() === userId)
            return canRedact;
        return this.hasSufficientPowerLevelFor('redact', member.powerLevel);
    }
    /**
     * Returns true if the given power level is sufficient for action
     * @param {string} action The type of power level to check
     * @param {number} powerLevel The power level of the member
     * @return {boolean} true if the given power level is sufficient
     */
    hasSufficientPowerLevelFor(action, powerLevel) {
        const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, "");
        let powerLevels = {};
        if (powerLevelsEvent) {
            powerLevels = powerLevelsEvent.getContent();
        }
        let requiredLevel = 50;
        if (utils.isNumber(powerLevels[action])) {
            requiredLevel = powerLevels[action];
        }
        return powerLevel >= requiredLevel;
    }
    /**
     * Short-form for maySendEvent('m.room.message', userId)
     * @param {string} userId The user ID of the user to test permission for
     * @return {boolean} true if the given user ID should be permitted to send
     *                   message events into the given room.
     */
    maySendMessage(userId) {
        return this.maySendEventOfType(event_1.EventType.RoomMessage, userId, false);
    }
    /**
     * Returns true if the given user ID has permission to send a normal
     * event of type `eventType` into this room.
     * @param {string} eventType The type of event to test
     * @param {string} userId The user ID of the user to test permission for
     * @return {boolean} true if the given user ID should be permitted to send
     *                        the given type of event into this room,
     *                        according to the room's state.
     */
    maySendEvent(eventType, userId) {
        return this.maySendEventOfType(eventType, userId, false);
    }
    /**
     * Returns true if the given MatrixClient has permission to send a state
     * event of type `stateEventType` into this room.
     * @param {string} stateEventType The type of state events to test
     * @param {MatrixClient} cli The client to test permission for
     * @return {boolean} true if the given client should be permitted to send
     *                        the given type of state event into this room,
     *                        according to the room's state.
     */
    mayClientSendStateEvent(stateEventType, cli) {
        if (cli.isGuest()) {
            return false;
        }
        return this.maySendStateEvent(stateEventType, cli.credentials.userId);
    }
    /**
     * Returns true if the given user ID has permission to send a state
     * event of type `stateEventType` into this room.
     * @param {string} stateEventType The type of state events to test
     * @param {string} userId The user ID of the user to test permission for
     * @return {boolean} true if the given user ID should be permitted to send
     *                        the given type of state event into this room,
     *                        according to the room's state.
     */
    maySendStateEvent(stateEventType, userId) {
        return this.maySendEventOfType(stateEventType, userId, true);
    }
    /**
     * Returns true if the given user ID has permission to send a normal or state
     * event of type `eventType` into this room.
     * @param {string} eventType The type of event to test
     * @param {string} userId The user ID of the user to test permission for
     * @param {boolean} state If true, tests if the user may send a state
     event of this type. Otherwise tests whether
     they may send a regular event.
     * @return {boolean} true if the given user ID should be permitted to send
     *                        the given type of event into this room,
     *                        according to the room's state.
     */
    maySendEventOfType(eventType, userId, state) {
        const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, '');
        let powerLevels;
        let eventsLevels = {};
        let stateDefault = 0;
        let eventsDefault = 0;
        let powerLevel = 0;
        if (powerLevelsEvent) {
            powerLevels = powerLevelsEvent.getContent();
            eventsLevels = powerLevels.events || {};
            if (Number.isSafeInteger(powerLevels.state_default)) {
                stateDefault = powerLevels.state_default;
            }
            else {
                stateDefault = 50;
            }
            const userPowerLevel = powerLevels.users && powerLevels.users[userId];
            if (Number.isSafeInteger(userPowerLevel)) {
                powerLevel = userPowerLevel;
            }
            else if (Number.isSafeInteger(powerLevels.users_default)) {
                powerLevel = powerLevels.users_default;
            }
            if (Number.isSafeInteger(powerLevels.events_default)) {
                eventsDefault = powerLevels.events_default;
            }
        }
        let requiredLevel = state ? stateDefault : eventsDefault;
        if (Number.isSafeInteger(eventsLevels[eventType])) {
            requiredLevel = eventsLevels[eventType];
        }
        return powerLevel >= requiredLevel;
    }
    /**
     * Returns true if the given user ID has permission to trigger notification
     * of type `notifLevelKey`
     * @param {string} notifLevelKey The level of notification to test (eg. 'room')
     * @param {string} userId The user ID of the user to test permission for
     * @return {boolean} true if the given user ID has permission to trigger a
     *                        notification of this type.
     */
    mayTriggerNotifOfType(notifLevelKey, userId) {
        const member = this.getMember(userId);
        if (!member) {
            return false;
        }
        const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, '');
        let notifLevel = 50;
        if (powerLevelsEvent &&
            powerLevelsEvent.getContent() &&
            powerLevelsEvent.getContent().notifications &&
            utils.isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])) {
            notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];
        }
        return member.powerLevel >= notifLevel;
    }
    /**
     * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
     * @returns {string} the join_rule applied to this room
     */
    getJoinRule() {
        const joinRuleEvent = this.getStateEvents(event_1.EventType.RoomJoinRules, "");
        const joinRuleContent = joinRuleEvent ? joinRuleEvent.getContent() : {};
        return joinRuleContent["join_rule"] || "invite";
    }
    updateThirdPartyTokenCache(memberEvent) {
        if (!memberEvent.getContent().third_party_invite) {
            return;
        }
        const token = (memberEvent.getContent().third_party_invite.signed || {}).token;
        if (!token) {
            return;
        }
        const threePidInvite = this.getStateEvents(event_1.EventType.RoomThirdPartyInvite, token);
        if (!threePidInvite) {
            return;
        }
        this.tokenToInvite[token] = memberEvent;
    }
    updateDisplayNameCache(userId, displayName) {
        const oldName = this.userIdsToDisplayNames[userId];
        delete this.userIdsToDisplayNames[userId];
        if (oldName) {
            // Remove the old name from the cache.
            // We clobber the user_id > name lookup but the name -> [user_id] lookup
            // means we need to remove that user ID from that array rather than nuking
            // the lot.
            const strippedOldName = utils.removeHiddenChars(oldName);
            const existingUserIds = this.displayNameToUserIds[strippedOldName];
            if (existingUserIds) {
                // remove this user ID from this array
                const filteredUserIDs = existingUserIds.filter((id) => id !== userId);
                this.displayNameToUserIds[strippedOldName] = filteredUserIDs;
            }
        }
        this.userIdsToDisplayNames[userId] = displayName;
        const strippedDisplayname = displayName && utils.removeHiddenChars(displayName);
        // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js
        if (strippedDisplayname) {
            if (!this.displayNameToUserIds[strippedDisplayname]) {
                this.displayNameToUserIds[strippedDisplayname] = [];
            }
            this.displayNameToUserIds[strippedDisplayname].push(userId);
        }
    }
}
exports.RoomState = RoomState;
/**
 * Fires whenever the event dictionary in room state is updated.
 * @event module:client~MatrixClient#"RoomState.events"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomState} state The room state whose RoomState.events dictionary
 * was updated.
 * @param {MatrixEvent} prevEvent The event being replaced by the new state, if
 * known. Note that this can differ from `getPrevContent()` on the new state event
 * as this is the store's view of the last state, not the previous state provided
 * by the server.
 * @example
 * matrixClient.on("RoomState.events", function(event, state, prevEvent){
 *   var newStateEvent = event;
 * });
 */
/**
 * Fires whenever a member in the members dictionary is updated in any way.
 * @event module:client~MatrixClient#"RoomState.members"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomState} state The room state whose RoomState.members dictionary
 * was updated.
 * @param {RoomMember} member The room member that was updated.
 * @example
 * matrixClient.on("RoomState.members", function(event, state, member){
 *   var newMembershipState = member.membership;
 * });
 */
/**
 * Fires whenever a member is added to the members dictionary. The RoomMember
 * will not be fully populated yet (e.g. no membership state) but will already
 * be available in the members dictionary.
 * @event module:client~MatrixClient#"RoomState.newMember"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {RoomState} state The room state whose RoomState.members dictionary
 * was updated with a new entry.
 * @param {RoomMember} member The room member that was added.
 * @example
 * matrixClient.on("RoomState.newMember", function(event, state, member){
 *   // add event listeners on 'member'
 * });
 */

},{"../@types/event":58,"../logger":106,"../utils":137,"./room-member":116,"events":36}],118:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoomSummary = void 0;
/**
 * Construct a new Room Summary. A summary can be used for display on a recent
 * list, without having to load the entire room list into memory.
 * @constructor
 * @param {string} roomId Required. The ID of this room.
 * @param {Object} info Optional. The summary info. Additional keys are supported.
 * @param {string} info.title The title of the room (e.g. <code>m.room.name</code>)
 * @param {string} info.desc The description of the room (e.g.
 * <code>m.room.topic</code>)
 * @param {Number} info.numMembers The number of joined users.
 * @param {string[]} info.aliases The list of aliases for this room.
 * @param {Number} info.timestamp The timestamp for this room.
 */
class RoomSummary {
    constructor(roomId, info) {
        this.roomId = roomId;
    }
}
exports.RoomSummary = RoomSummary;

},{}],119:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Room = exports.NotificationCountType = void 0;
/**
 * @module models/room
 */
const events_1 = require("events");
const event_timeline_set_1 = require("./event-timeline-set");
const event_timeline_1 = require("./event-timeline");
const content_repo_1 = require("../content-repo");
const utils = __importStar(require("../utils"));
const utils_1 = require("../utils");
const event_1 = require("./event");
const room_member_1 = require("./room-member");
const room_summary_1 = require("./room-summary");
const logger_1 = require("../logger");
const ReEmitter_1 = require("../ReEmitter");
const event_2 = require("../@types/event");
const client_1 = require("../client");
// These constants are used as sane defaults when the homeserver doesn't support
// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be
// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the
// room versions which are considered okay for people to run without being asked
// to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers
// return an m.room_versions capability.
const KNOWN_SAFE_ROOM_VERSION = '6';
const SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6'];
function synthesizeReceipt(userId, event, receiptType) {
    // console.log("synthesizing receipt for "+event.getId());
    // This is really ugly because JS has no way to express an object literal
    // where the name of a key comes from an expression
    const fakeReceipt = {
        content: {},
        type: "m.receipt",
        room_id: event.getRoomId(),
    };
    fakeReceipt.content[event.getId()] = {};
    fakeReceipt.content[event.getId()][receiptType] = {};
    fakeReceipt.content[event.getId()][receiptType][userId] = {
        ts: event.getTs(),
    };
    return new event_1.MatrixEvent(fakeReceipt);
}
var NotificationCountType;
(function (NotificationCountType) {
    NotificationCountType["Highlight"] = "highlight";
    NotificationCountType["Total"] = "total";
})(NotificationCountType = exports.NotificationCountType || (exports.NotificationCountType = {}));
class Room extends events_1.EventEmitter {
    /**
     * Construct a new Room.
     *
     * <p>For a room, we store an ordered sequence of timelines, which may or may not
     * be continuous. Each timeline lists a series of events, as well as tracking
     * the room state at the start and the end of the timeline. It also tracks
     * forward and backward pagination tokens, as well as containing links to the
     * next timeline in the sequence.
     *
     * <p>There is one special timeline - the 'live' timeline, which represents the
     * timeline to which events are being added in real-time as they are received
     * from the /sync API. Note that you should not retain references to this
     * timeline - even if it is the current timeline right now, it may not remain
     * so if the server gives us a timeline gap in /sync.
     *
     * <p>In order that we can find events from their ids later, we also maintain a
     * map from event_id to timeline and index.
     *
     * @constructor
     * @alias module:models/room
     * @param {string} roomId Required. The ID of this room.
     * @param {MatrixClient} client Required. The client, used to lazy load members.
     * @param {string} myUserId Required. The ID of the syncing user.
     * @param {Object=} opts Configuration options
     * @param {*} opts.storageToken Optional. The token which a data store can use
     * to remember the state of the room. What this means is dependent on the store
     * implementation.
     *
     * @param {String=} opts.pendingEventOrdering Controls where pending messages
     * appear in a room's timeline. If "<b>chronological</b>", messages will appear
     * in the timeline when the call to <code>sendEvent</code> was made. If
     * "<b>detached</b>", pending messages will appear in a separate list,
     * accessible via {@link module:models/room#getPendingEvents}. Default:
     * "chronological".
     * @param {boolean} [opts.timelineSupport = false] Set to true to enable improved
     * timeline support.
     * @param {boolean} [opts.unstableClientRelationAggregation = false]
     * Optional. Set to true to enable client-side aggregation of event relations
     * via `EventTimelineSet#getRelationsForEvent`.
     * This feature is currently unstable and the API may change without notice.
     *
     * @prop {string} roomId The ID of this room.
     * @prop {string} name The human-readable display name for this room.
     * @prop {string} normalizedName The un-homoglyphed name for this room.
     * @prop {Array<MatrixEvent>} timeline The live event timeline for this room,
     * with the oldest event at index 0. Present for backwards compatibility -
     * prefer getLiveTimeline().getEvents().
     * @prop {object} tags Dict of room tags; the keys are the tag name and the values
     * are any metadata associated with the tag - e.g. { "fav" : { order: 1 } }
     * @prop {object} accountData Dict of per-room account_data events; the keys are the
     * event type and the values are the events.
     * @prop {RoomState} oldState The state of the room at the time of the oldest
     * event in the live timeline. Present for backwards compatibility -
     * prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).
     * @prop {RoomState} currentState The state of the room at the time of the
     * newest event in the timeline. Present for backwards compatibility -
     * prefer getLiveTimeline().getState(EventTimeline.FORWARDS).
     * @prop {RoomSummary} summary The room summary.
     * @prop {*} storageToken A token which a data store can use to remember
     * the state of the room.
     */
    constructor(roomId, client, myUserId, opts = {}) {
        super();
        this.roomId = roomId;
        this.client = client;
        this.myUserId = myUserId;
        this.opts = opts;
        this.txnToEvent = {}; // Pending in-flight requests { string: MatrixEvent }
        // receipts should clobber based on receipt_type and user_id pairs hence
        // the form of this structure. This is sub-optimal for the exposed APIs
        // which pass in an event ID and get back some receipts, so we also store
        // a pre-cached list for this purpose.
        this.receipts = {}; // { receipt_type: { user_id: IReceipt } }
        this.receiptCacheByEventId = {}; // { event_id: IReceipt2[] }
        // only receipts that came from the server, not synthesized ones
        this.realReceipts = {};
        this.notificationCounts = {};
        // any filtered timeline sets we're maintaining for this room
        this.filteredTimelineSets = {}; // filter_id: timelineSet
        // read by megolm via getter; boolean value - null indicates "use global value"
        this.blacklistUnverifiedDevices = null;
        this.selfMembership = null;
        this.summaryHeroes = null;
        // flags to stop logspam about missing m.room.create events
        this.getTypeWarning = false;
        this.getVersionWarning = false;
        this.tags = {}; // $tagName: { $metadata: $value }
        this.accountData = {}; // $eventType: $event
        this.summary = null;
        // In some cases, we add listeners for every displayed Matrix event, so it's
        // common to have quite a few more than the default limit.
        this.setMaxListeners(100);
        this.reEmitter = new ReEmitter_1.ReEmitter(this);
        opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological";
        if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) {
            throw new Error("opts.pendingEventOrdering MUST be either 'chronological' or " +
                "'detached'. Got: '" + opts.pendingEventOrdering + "'");
        }
        this.name = roomId;
        // all our per-room timeline sets. the first one is the unfiltered ones;
        // the subsequent ones are the filtered ones in no particular order.
        this.timelineSets = [new event_timeline_set_1.EventTimelineSet(this, opts)];
        this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), ["Room.timeline", "Room.timelineReset"]);
        this.fixUpLegacyTimelineFields();
        if (this.opts.pendingEventOrdering == "detached") {
            this.pendingEventList = [];
            const serializedPendingEventList = client.sessionStore.store.getItem(pendingEventsKey(this.roomId));
            if (serializedPendingEventList) {
                JSON.parse(serializedPendingEventList)
                    .forEach((serializedEvent) => __awaiter(this, void 0, void 0, function* () {
                    const event = new event_1.MatrixEvent(serializedEvent);
                    if (event.getType() === event_2.EventType.RoomMessageEncrypted) {
                        yield event.attemptDecryption(this.client.crypto);
                    }
                    event.setStatus(event_1.EventStatus.NOT_SENT);
                    this.addPendingEvent(event, event.getTxnId());
                }));
            }
        }
        // awaited by getEncryptionTargetMembers while room members are loading
        if (!this.opts.lazyLoadMembers) {
            this.membersPromise = Promise.resolve(false);
        }
        else {
            this.membersPromise = null;
        }
    }
    /**
     * Bulk decrypt critical events in a room
     *
     * Critical events represents the minimal set of events to decrypt
     * for a typical UI to function properly
     *
     * - Last event of every room (to generate likely message preview)
     * - All events up to the read receipt (to calculate an accurate notification count)
     *
     * @returns {Promise} Signals when all events have been decrypted
     */
    decryptCriticalEvents() {
        const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId(), true);
        const events = this.getLiveTimeline().getEvents();
        const readReceiptTimelineIndex = events.findIndex(matrixEvent => {
            return matrixEvent.event.event_id === readReceiptEventId;
        });
        const decryptionPromises = events
            .slice(readReceiptTimelineIndex)
            .filter(event => event.shouldAttemptDecryption())
            .reverse()
            .map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));
        return Promise.allSettled(decryptionPromises);
    }
    /**
     * Bulk decrypt events in a room
     *
     * @returns {Promise} Signals when all events have been decrypted
     */
    decryptAllEvents() {
        const decryptionPromises = this
            .getUnfilteredTimelineSet()
            .getLiveTimeline()
            .getEvents()
            .filter(event => event.shouldAttemptDecryption())
            .reverse()
            .map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));
        return Promise.allSettled(decryptionPromises);
    }
    /**
     * Gets the version of the room
     * @returns {string} The version of the room, or null if it could not be determined
     */
    getVersion() {
        const createEvent = this.currentState.getStateEvents(event_2.EventType.RoomCreate, "");
        if (!createEvent) {
            if (!this.getVersionWarning) {
                logger_1.logger.warn("[getVersion] Room " + this.roomId + " does not have an m.room.create event");
                this.getVersionWarning = true;
            }
            return '1';
        }
        const ver = createEvent.getContent()['room_version'];
        if (ver === undefined)
            return '1';
        return ver;
    }
    /**
     * Determines whether this room needs to be upgraded to a new version
     * @returns {string?} What version the room should be upgraded to, or null if
     *     the room does not require upgrading at this time.
     * @deprecated Use #getRecommendedVersion() instead
     */
    shouldUpgradeToVersion() {
        // TODO: Remove this function.
        // This makes assumptions about which versions are safe, and can easily
        // be wrong. Instead, people are encouraged to use getRecommendedVersion
        // which determines a safer value. This function doesn't use that function
        // because this is not async-capable, and to avoid breaking the contract
        // we're deprecating this.
        if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {
            return KNOWN_SAFE_ROOM_VERSION;
        }
        return null;
    }
    /**
     * Determines the recommended room version for the room. This returns an
     * object with 3 properties: <code>version</code> as the new version the
     * room should be upgraded to (may be the same as the current version);
     * <code>needsUpgrade</code> to indicate if the room actually can be
     * upgraded (ie: does the current version not match?); and <code>urgent</code>
     * to indicate if the new version patches a vulnerability in a previous
     * version.
     * @returns {Promise<{version: string, needsUpgrade: boolean, urgent: boolean}>}
     * Resolves to the version the room should be upgraded to.
     */
    getRecommendedVersion() {
        return __awaiter(this, void 0, void 0, function* () {
            const capabilities = yield this.client.getCapabilities();
            let versionCap = capabilities["m.room_versions"];
            if (!versionCap) {
                versionCap = {
                    default: KNOWN_SAFE_ROOM_VERSION,
                    available: {},
                };
                for (const safeVer of SAFE_ROOM_VERSIONS) {
                    versionCap.available[safeVer] = client_1.RoomVersionStability.Stable;
                }
            }
            let result = this.checkVersionAgainstCapability(versionCap);
            if (result.urgent && result.needsUpgrade) {
                // Something doesn't feel right: we shouldn't need to update
                // because the version we're on should be in the protocol's
                // namespace. This usually means that the server was updated
                // before the client was, making us think the newest possible
                // room version is not stable. As a solution, we'll refresh
                // the capability we're using to determine this.
                logger_1.logger.warn("Refreshing room version capability because the server looks " +
                    "to be supporting a newer room version we don't know about.");
                const caps = yield this.client.getCapabilities(true);
                versionCap = caps["m.room_versions"];
                if (!versionCap) {
                    logger_1.logger.warn("No room version capability - assuming upgrade required.");
                    return result;
                }
                else {
                    result = this.checkVersionAgainstCapability(versionCap);
                }
            }
            return result;
        });
    }
    checkVersionAgainstCapability(versionCap) {
        const currentVersion = this.getVersion();
        logger_1.logger.log(`[${this.roomId}] Current version: ${currentVersion}`);
        logger_1.logger.log(`[${this.roomId}] Version capability: `, versionCap);
        const result = {
            version: currentVersion,
            needsUpgrade: false,
            urgent: false,
        };
        // If the room is on the default version then nothing needs to change
        if (currentVersion === versionCap.default)
            return result;
        const stableVersions = Object.keys(versionCap.available)
            .filter((v) => versionCap.available[v] === 'stable');
        // Check if the room is on an unstable version. We determine urgency based
        // off the version being in the Matrix spec namespace or not (if the version
        // is in the current namespace and unstable, the room is probably vulnerable).
        if (!stableVersions.includes(currentVersion)) {
            result.version = versionCap.default;
            result.needsUpgrade = true;
            result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);
            if (result.urgent) {
                logger_1.logger.warn(`URGENT upgrade required on ${this.roomId}`);
            }
            else {
                logger_1.logger.warn(`Non-urgent upgrade required on ${this.roomId}`);
            }
            return result;
        }
        // The room is on a stable, but non-default, version by this point.
        // No upgrade needed.
        return result;
    }
    /**
     * Determines whether the given user is permitted to perform a room upgrade
     * @param {String} userId The ID of the user to test against
     * @returns {boolean} True if the given user is permitted to upgrade the room
     */
    userMayUpgradeRoom(userId) {
        return this.currentState.maySendStateEvent(event_2.EventType.RoomTombstone, userId);
    }
    /**
     * Get the list of pending sent events for this room
     *
     * @return {module:models/event.MatrixEvent[]} A list of the sent events
     * waiting for remote echo.
     *
     * @throws If <code>opts.pendingEventOrdering</code> was not 'detached'
     */
    getPendingEvents() {
        if (this.opts.pendingEventOrdering !== "detached") {
            throw new Error("Cannot call getPendingEvents with pendingEventOrdering == " +
                this.opts.pendingEventOrdering);
        }
        return this.pendingEventList;
    }
    /**
     * Removes a pending event for this room
     *
     * @param {string} eventId
     * @return {boolean} True if an element was removed.
     */
    removePendingEvent(eventId) {
        if (this.opts.pendingEventOrdering !== "detached") {
            throw new Error("Cannot call removePendingEvent with pendingEventOrdering == " +
                this.opts.pendingEventOrdering);
        }
        const removed = utils.removeElement(this.pendingEventList, function (ev) {
            return ev.getId() == eventId;
        }, false);
        this.savePendingEvents();
        return removed;
    }
    /**
     * Check whether the pending event list contains a given event by ID.
     * If pending event ordering is not "detached" then this returns false.
     *
     * @param {string} eventId The event ID to check for.
     * @return {boolean}
     */
    hasPendingEvent(eventId) {
        if (this.opts.pendingEventOrdering !== "detached") {
            return false;
        }
        return this.pendingEventList.some(event => event.getId() === eventId);
    }
    /**
     * Get a specific event from the pending event list, if configured, null otherwise.
     *
     * @param {string} eventId The event ID to check for.
     * @return {MatrixEvent}
     */
    getPendingEvent(eventId) {
        if (this.opts.pendingEventOrdering !== "detached") {
            return null;
        }
        return this.pendingEventList.find(event => event.getId() === eventId);
    }
    /**
     * Get the live unfiltered timeline for this room.
     *
     * @return {module:models/event-timeline~EventTimeline} live timeline
     */
    getLiveTimeline() {
        return this.getUnfilteredTimelineSet().getLiveTimeline();
    }
    /**
     * Get the timestamp of the last message in the room
     *
     * @return {number} the timestamp of the last message in the room
     */
    getLastActiveTimestamp() {
        const timeline = this.getLiveTimeline();
        const events = timeline.getEvents();
        if (events.length) {
            const lastEvent = events[events.length - 1];
            return lastEvent.getTs();
        }
        else {
            return Number.MIN_SAFE_INTEGER;
        }
    }
    /**
     * @return {string} the membership type (join | leave | invite) for the logged in user
     */
    getMyMembership() {
        return this.selfMembership;
    }
    /**
     * If this room is a DM we're invited to,
     * try to find out who invited us
     * @return {string} user id of the inviter
     */
    getDMInviter() {
        if (this.myUserId) {
            const me = this.getMember(this.myUserId);
            if (me) {
                return me.getDMInviter();
            }
        }
        if (this.selfMembership === "invite") {
            // fall back to summary information
            const memberCount = this.getInvitedAndJoinedMemberCount();
            if (memberCount == 2 && this.summaryHeroes.length) {
                return this.summaryHeroes[0];
            }
        }
    }
    /**
     * Assuming this room is a DM room, tries to guess with which user.
     * @return {string} user id of the other member (could be syncing user)
     */
    guessDMUserId() {
        const me = this.getMember(this.myUserId);
        if (me) {
            const inviterId = me.getDMInviter();
            if (inviterId) {
                return inviterId;
            }
        }
        // remember, we're assuming this room is a DM,
        // so returning the first member we find should be fine
        const hasHeroes = Array.isArray(this.summaryHeroes) &&
            this.summaryHeroes.length;
        if (hasHeroes) {
            return this.summaryHeroes[0];
        }
        const members = this.currentState.getMembers();
        const anyMember = members.find((m) => m.userId !== this.myUserId);
        if (anyMember) {
            return anyMember.userId;
        }
        // it really seems like I'm the only user in the room
        // so I probably created a room with just me in it
        // and marked it as a DM. Ok then
        return this.myUserId;
    }
    getAvatarFallbackMember() {
        const memberCount = this.getInvitedAndJoinedMemberCount();
        if (memberCount > 2) {
            return;
        }
        const hasHeroes = Array.isArray(this.summaryHeroes) &&
            this.summaryHeroes.length;
        if (hasHeroes) {
            const availableMember = this.summaryHeroes.map((userId) => {
                return this.getMember(userId);
            }).find((member) => !!member);
            if (availableMember) {
                return availableMember;
            }
        }
        const members = this.currentState.getMembers();
        // could be different than memberCount
        // as this includes left members
        if (members.length <= 2) {
            const availableMember = members.find((m) => {
                return m.userId !== this.myUserId;
            });
            if (availableMember) {
                return availableMember;
            }
        }
        // if all else fails, try falling back to a user,
        // and create a one-off member for it
        if (hasHeroes) {
            const availableUser = this.summaryHeroes.map((userId) => {
                return this.client.getUser(userId);
            }).find((user) => !!user);
            if (availableUser) {
                const member = new room_member_1.RoomMember(this.roomId, availableUser.userId);
                member.user = availableUser;
                return member;
            }
        }
    }
    /**
     * Sets the membership this room was received as during sync
     * @param {string} membership join | leave | invite
     */
    updateMyMembership(membership) {
        const prevMembership = this.selfMembership;
        this.selfMembership = membership;
        if (prevMembership !== membership) {
            if (membership === "leave") {
                this.cleanupAfterLeaving();
            }
            this.emit("Room.myMembership", this, membership, prevMembership);
        }
    }
    loadMembersFromServer() {
        return __awaiter(this, void 0, void 0, function* () {
            const lastSyncToken = this.client.store.getSyncToken();
            const queryString = utils.encodeParams({
                not_membership: "leave",
                at: lastSyncToken,
            });
            const path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: this.roomId });
            const http = this.client.http;
            const response = yield http.authedRequest(undefined, "GET", path);
            return response.chunk;
        });
    }
    loadMembers() {
        return __awaiter(this, void 0, void 0, function* () {
            // were the members loaded from the server?
            let fromServer = false;
            let rawMembersEvents = yield this.client.store.getOutOfBandMembers(this.roomId);
            if (rawMembersEvents === null) {
                fromServer = true;
                rawMembersEvents = yield this.loadMembersFromServer();
                logger_1.logger.log(`LL: got ${rawMembersEvents.length} ` +
                    `members from server for room ${this.roomId}`);
            }
            const memberEvents = rawMembersEvents.map(this.client.getEventMapper());
            return { memberEvents, fromServer };
        });
    }
    /**
     * Preloads the member list in case lazy loading
     * of memberships is in use. Can be called multiple times,
     * it will only preload once.
     * @return {Promise} when preloading is done and
     * accessing the members on the room will take
     * all members in the room into account
     */
    loadMembersIfNeeded() {
        if (this.membersPromise) {
            return this.membersPromise;
        }
        // mark the state so that incoming messages while
        // the request is in flight get marked as superseding
        // the OOB members
        this.currentState.markOutOfBandMembersStarted();
        const inMemoryUpdate = this.loadMembers().then((result) => {
            this.currentState.setOutOfBandMembers(result.memberEvents);
            // now the members are loaded, start to track the e2e devices if needed
            if (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId)) {
                this.client.crypto.trackRoomDevices(this.roomId);
            }
            return result.fromServer;
        }).catch((err) => {
            // allow retries on fail
            this.membersPromise = null;
            this.currentState.markOutOfBandMembersFailed();
            throw err;
        });
        // update members in storage, but don't wait for it
        inMemoryUpdate.then((fromServer) => {
            if (fromServer) {
                const oobMembers = this.currentState.getMembers()
                    .filter((m) => m.isOutOfBand())
                    .map((m) => m.events.member.event);
                logger_1.logger.log(`LL: telling store to write ${oobMembers.length}`
                    + ` members for room ${this.roomId}`);
                const store = this.client.store;
                return store.setOutOfBandMembers(this.roomId, oobMembers)
                    // swallow any IDB error as we don't want to fail
                    // because of this
                    .catch((err) => {
                    logger_1.logger.log("LL: storing OOB room members failed, oh well", err);
                });
            }
        }).catch((err) => {
            // as this is not awaited anywhere,
            // at least show the error in the console
            logger_1.logger.error(err);
        });
        this.membersPromise = inMemoryUpdate;
        return this.membersPromise;
    }
    /**
     * Removes the lazily loaded members from storage if needed
     */
    clearLoadedMembersIfNeeded() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.opts.lazyLoadMembers && this.membersPromise) {
                yield this.loadMembersIfNeeded();
                yield this.client.store.clearOutOfBandMembers(this.roomId);
                this.currentState.clearOutOfBandMembers();
                this.membersPromise = null;
            }
        });
    }
    /**
     * called when sync receives this room in the leave section
     * to do cleanup after leaving a room. Possibly called multiple times.
     */
    cleanupAfterLeaving() {
        this.clearLoadedMembersIfNeeded().catch((err) => {
            logger_1.logger.error(`error after clearing loaded members from ` +
                `room ${this.roomId} after leaving`);
            logger_1.logger.log(err);
        });
    }
    /**
     * Reset the live timeline of all timelineSets, and start new ones.
     *
     * <p>This is used when /sync returns a 'limited' timeline.
     *
     * @param {string=} backPaginationToken   token for back-paginating the new timeline
     * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline,
     * if absent or null, all timelines are reset, removing old ones (including the previous live
     * timeline which would otherwise be unable to paginate forwards without this token).
     * Removing just the old live timeline whilst preserving previous ones is not supported.
     */
    resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
        for (let i = 0; i < this.timelineSets.length; i++) {
            this.timelineSets[i].resetLiveTimeline(backPaginationToken, forwardPaginationToken);
        }
        this.fixUpLegacyTimelineFields();
    }
    /**
     * Fix up this.timeline, this.oldState and this.currentState
     *
     * @private
     */
    fixUpLegacyTimelineFields() {
        // maintain this.timeline as a reference to the live timeline,
        // and this.oldState and this.currentState as references to the
        // state at the start and end of that timeline. These are more
        // for backwards-compatibility than anything else.
        this.timeline = this.getLiveTimeline().getEvents();
        this.oldState = this.getLiveTimeline()
            .getState(event_timeline_1.EventTimeline.BACKWARDS);
        this.currentState = this.getLiveTimeline()
            .getState(event_timeline_1.EventTimeline.FORWARDS);
    }
    /**
     * Returns whether there are any devices in the room that are unverified
     *
     * Note: Callers should first check if crypto is enabled on this device. If it is
     * disabled, then we aren't tracking room devices at all, so we can't answer this, and an
     * error will be thrown.
     *
     * @return {boolean} the result
     */
    hasUnverifiedDevices() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.client.isRoomEncrypted(this.roomId)) {
                return false;
            }
            const e2eMembers = yield this.getEncryptionTargetMembers();
            for (const member of e2eMembers) {
                const devices = this.client.getStoredDevicesForUser(member.userId);
                if (devices.some((device) => device.isUnverified())) {
                    return true;
                }
            }
            return false;
        });
    }
    /**
     * Return the timeline sets for this room.
     * @return {EventTimelineSet[]} array of timeline sets for this room
     */
    getTimelineSets() {
        return this.timelineSets;
    }
    /**
     * Helper to return the main unfiltered timeline set for this room
     * @return {EventTimelineSet} room's unfiltered timeline set
     */
    getUnfilteredTimelineSet() {
        return this.timelineSets[0];
    }
    /**
     * Get the timeline which contains the given event from the unfiltered set, if any
     *
     * @param {string} eventId  event ID to look for
     * @return {?module:models/event-timeline~EventTimeline} timeline containing
     * the given event, or null if unknown
     */
    getTimelineForEvent(eventId) {
        return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);
    }
    /**
     * Add a new timeline to this room's unfiltered timeline set
     *
     * @return {module:models/event-timeline~EventTimeline} newly-created timeline
     */
    addTimeline() {
        return this.getUnfilteredTimelineSet().addTimeline();
    }
    /**
     * Get an event which is stored in our unfiltered timeline set
     *
     * @param {string} eventId  event ID to look for
     * @return {?module:models/event.MatrixEvent} the given event, or undefined if unknown
     */
    findEventById(eventId) {
        return this.getUnfilteredTimelineSet().findEventById(eventId);
    }
    /**
     * Get one of the notification counts for this room
     * @param {String} type The type of notification count to get. default: 'total'
     * @return {Number} The notification count, or undefined if there is no count
     *                  for this type.
     */
    getUnreadNotificationCount(type = NotificationCountType.Total) {
        return this.notificationCounts[type];
    }
    /**
     * Set one of the notification counts for this room
     * @param {String} type The type of notification count to set.
     * @param {Number} count The new count
     */
    setUnreadNotificationCount(type, count) {
        this.notificationCounts[type] = count;
    }
    setSummary(summary) {
        const heroes = summary["m.heroes"];
        const joinedCount = summary["m.joined_member_count"];
        const invitedCount = summary["m.invited_member_count"];
        if (Number.isInteger(joinedCount)) {
            this.currentState.setJoinedMemberCount(joinedCount);
        }
        if (Number.isInteger(invitedCount)) {
            this.currentState.setInvitedMemberCount(invitedCount);
        }
        if (Array.isArray(heroes)) {
            // be cautious about trusting server values,
            // and make sure heroes doesn't contain our own id
            // just to be sure
            this.summaryHeroes = heroes.filter((userId) => {
                return userId !== this.myUserId;
            });
        }
    }
    /**
     * Whether to send encrypted messages to devices within this room.
     * @param {Boolean} value true to blacklist unverified devices, null
     * to use the global value for this room.
     */
    setBlacklistUnverifiedDevices(value) {
        this.blacklistUnverifiedDevices = value;
    }
    /**
     * Whether to send encrypted messages to devices within this room.
     * @return {Boolean} true if blacklisting unverified devices, null
     * if the global value should be used for this room.
     */
    getBlacklistUnverifiedDevices() {
        return this.blacklistUnverifiedDevices;
    }
    /**
     * Get the avatar URL for a room if one was set.
     * @param {String} baseUrl The homeserver base URL. See
     * {@link module:client~MatrixClient#getHomeserverUrl}.
     * @param {Number} width The desired width of the thumbnail.
     * @param {Number} height The desired height of the thumbnail.
     * @param {string} resizeMethod The thumbnail resize method to use, either
     * "crop" or "scale".
     * @param {boolean} allowDefault True to allow an identicon for this room if an
     * avatar URL wasn't explicitly set. Default: true. (Deprecated)
     * @return {?string} the avatar URL or null.
     */
    getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault = true) {
        const roomAvatarEvent = this.currentState.getStateEvents(event_2.EventType.RoomAvatar, "");
        if (!roomAvatarEvent && !allowDefault) {
            return null;
        }
        const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;
        if (mainUrl) {
            return content_repo_1.getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);
        }
        return null;
    }
    /**
     * Get the mxc avatar url for the room, if one was set.
     * @return {string} the mxc avatar url or falsy
     */
    getMxcAvatarUrl() {
        var _a, _b;
        return ((_b = (_a = this.currentState.getStateEvents(event_2.EventType.RoomAvatar, "")) === null || _a === void 0 ? void 0 : _a.getContent()) === null || _b === void 0 ? void 0 : _b.url) || null;
    }
    /**
     * Get the aliases this room has according to the room's state
     * The aliases returned by this function may not necessarily
     * still point to this room.
     * @return {array} The room's alias as an array of strings
     */
    getAliases() {
        const aliasStrings = [];
        const aliasEvents = this.currentState.getStateEvents(event_2.EventType.RoomAliases);
        if (aliasEvents) {
            for (let i = 0; i < aliasEvents.length; ++i) {
                const aliasEvent = aliasEvents[i];
                if (Array.isArray(aliasEvent.getContent().aliases)) {
                    const filteredAliases = aliasEvent.getContent().aliases.filter(a => {
                        if (typeof (a) !== "string")
                            return false;
                        if (a[0] !== '#')
                            return false;
                        if (!a.endsWith(`:${aliasEvent.getStateKey()}`))
                            return false;
                        // It's probably valid by here.
                        return true;
                    });
                    Array.prototype.push.apply(aliasStrings, filteredAliases);
                }
            }
        }
        return aliasStrings;
    }
    /**
     * Get this room's canonical alias
     * The alias returned by this function may not necessarily
     * still point to this room.
     * @return {?string} The room's canonical alias, or null if there is none
     */
    getCanonicalAlias() {
        const canonicalAlias = this.currentState.getStateEvents(event_2.EventType.RoomCanonicalAlias, "");
        if (canonicalAlias) {
            return canonicalAlias.getContent().alias || null;
        }
        return null;
    }
    /**
     * Get this room's alternative aliases
     * @return {array} The room's alternative aliases, or an empty array
     */
    getAltAliases() {
        const canonicalAlias = this.currentState.getStateEvents(event_2.EventType.RoomCanonicalAlias, "");
        if (canonicalAlias) {
            return canonicalAlias.getContent().alt_aliases || [];
        }
        return [];
    }
    /**
     * Add events to a timeline
     *
     * <p>Will fire "Room.timeline" for each event added.
     *
     * @param {MatrixEvent[]} events A list of events to add.
     *
     * @param {boolean} toStartOfTimeline   True to add these events to the start
     * (oldest) instead of the end (newest) of the timeline. If true, the oldest
     * event will be the <b>last</b> element of 'events'.
     *
     * @param {module:models/event-timeline~EventTimeline} timeline   timeline to
     *    add events to.
     *
     * @param {string=} paginationToken   token for the next batch of events
     *
     * @fires module:client~MatrixClient#event:"Room.timeline"
     *
     */
    addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken) {
        timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);
    }
    /**
     * Get a member from the current room state.
     * @param {string} userId The user ID of the member.
     * @return {RoomMember} The member or <code>null</code>.
     */
    getMember(userId) {
        return this.currentState.getMember(userId);
    }
    /**
     * Get all currently loaded members from the current
     * room state.
     * @returns {RoomMember[]} Room members
     */
    getMembers() {
        return this.currentState.getMembers();
    }
    /**
     * Get a list of members whose membership state is "join".
     * @return {RoomMember[]} A list of currently joined members.
     */
    getJoinedMembers() {
        return this.getMembersWithMembership("join");
    }
    /**
     * Returns the number of joined members in this room
     * This method caches the result.
     * This is a wrapper around the method of the same name in roomState, returning
     * its result for the room's current state.
     * @return {number} The number of members in this room whose membership is 'join'
     */
    getJoinedMemberCount() {
        return this.currentState.getJoinedMemberCount();
    }
    /**
     * Returns the number of invited members in this room
     * @return {number} The number of members in this room whose membership is 'invite'
     */
    getInvitedMemberCount() {
        return this.currentState.getInvitedMemberCount();
    }
    /**
     * Returns the number of invited + joined members in this room
     * @return {number} The number of members in this room whose membership is 'invite' or 'join'
     */
    getInvitedAndJoinedMemberCount() {
        return this.getInvitedMemberCount() + this.getJoinedMemberCount();
    }
    /**
     * Get a list of members with given membership state.
     * @param {string} membership The membership state.
     * @return {RoomMember[]} A list of members with the given membership state.
     */
    getMembersWithMembership(membership) {
        return this.currentState.getMembers().filter(function (m) {
            return m.membership === membership;
        });
    }
    /**
     * Get a list of members we should be encrypting for in this room
     * @return {Promise<RoomMember[]>} A list of members who
     * we should encrypt messages for in this room.
     */
    getEncryptionTargetMembers() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadMembersIfNeeded();
            let members = this.getMembersWithMembership("join");
            if (this.shouldEncryptForInvitedMembers()) {
                members = members.concat(this.getMembersWithMembership("invite"));
            }
            return members;
        });
    }
    /**
     * Determine whether we should encrypt messages for invited users in this room
     * @return {boolean} if we should encrypt messages for invited users
     */
    shouldEncryptForInvitedMembers() {
        var _a;
        const ev = this.currentState.getStateEvents(event_2.EventType.RoomHistoryVisibility, "");
        return ((_a = ev === null || ev === void 0 ? void 0 : ev.getContent()) === null || _a === void 0 ? void 0 : _a.history_visibility) !== "joined";
    }
    /**
     * Get the default room name (i.e. what a given user would see if the
     * room had no m.room.name)
     * @param {string} userId The userId from whose perspective we want
     * to calculate the default name
     * @return {string} The default room name
     */
    getDefaultRoomName(userId) {
        return this.calculateRoomName(userId, true);
    }
    /**
     * Check if the given user_id has the given membership state.
     * @param {string} userId The user ID to check.
     * @param {string} membership The membership e.g. <code>'join'</code>
     * @return {boolean} True if this user_id has the given membership state.
     */
    hasMembershipState(userId, membership) {
        const member = this.getMember(userId);
        if (!member) {
            return false;
        }
        return member.membership === membership;
    }
    /**
     * Add a timelineSet for this room with the given filter
     * @param {Filter} filter The filter to be applied to this timelineSet
     * @return {EventTimelineSet} The timelineSet
     */
    getOrCreateFilteredTimelineSet(filter) {
        if (this.filteredTimelineSets[filter.filterId]) {
            return this.filteredTimelineSets[filter.filterId];
        }
        const opts = Object.assign({ filter: filter }, this.opts);
        const timelineSet = new event_timeline_set_1.EventTimelineSet(this, opts);
        this.reEmitter.reEmit(timelineSet, ["Room.timeline", "Room.timelineReset"]);
        this.filteredTimelineSets[filter.filterId] = timelineSet;
        this.timelineSets.push(timelineSet);
        // populate up the new timelineSet with filtered events from our live
        // unfiltered timeline.
        //
        // XXX: This is risky as our timeline
        // may have grown huge and so take a long time to filter.
        // see https://github.com/vector-im/vector-web/issues/2109
        const unfilteredLiveTimeline = this.getLiveTimeline();
        unfilteredLiveTimeline.getEvents().forEach(function (event) {
            timelineSet.addLiveEvent(event);
        });
        // find the earliest unfiltered timeline
        let timeline = unfilteredLiveTimeline;
        while (timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS)) {
            timeline = timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS);
        }
        timelineSet.getLiveTimeline().setPaginationToken(timeline.getPaginationToken(event_timeline_1.EventTimeline.BACKWARDS), event_timeline_1.EventTimeline.BACKWARDS);
        // alternatively, we could try to do something like this to try and re-paginate
        // in the filtered events from nothing, but Mark says it's an abuse of the API
        // to do so:
        //
        // timelineSet.resetLiveTimeline(
        //      unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)
        // );
        return timelineSet;
    }
    /**
     * Forget the timelineSet for this room with the given filter
     *
     * @param {Filter} filter the filter whose timelineSet is to be forgotten
     */
    removeFilteredTimelineSet(filter) {
        const timelineSet = this.filteredTimelineSets[filter.filterId];
        delete this.filteredTimelineSets[filter.filterId];
        const i = this.timelineSets.indexOf(timelineSet);
        if (i > -1) {
            this.timelineSets.splice(i, 1);
        }
    }
    /**
     * Add an event to the end of this room's live timelines. Will fire
     * "Room.timeline".
     *
     * @param {MatrixEvent} event Event to be added
     * @param {string?} duplicateStrategy 'ignore' or 'replace'
     * @param {boolean} fromCache whether the sync response came from cache
     * @fires module:client~MatrixClient#event:"Room.timeline"
     * @private
     */
    addLiveEvent(event, duplicateStrategy, fromCache = false) {
        if (event.isRedaction()) {
            const redactId = event.event.redacts;
            // if we know about this event, redact its contents now.
            const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
            if (redactedEvent) {
                redactedEvent.makeRedacted(event);
                // If this is in the current state, replace it with the redacted version
                if (redactedEvent.getStateKey()) {
                    const currentStateEvent = this.currentState.getStateEvents(redactedEvent.getType(), redactedEvent.getStateKey());
                    if (currentStateEvent.getId() === redactedEvent.getId()) {
                        this.currentState.setStateEvents([redactedEvent]);
                    }
                }
                this.emit("Room.redaction", event, this);
                // TODO: we stash user displaynames (among other things) in
                // RoomMember objects which are then attached to other events
                // (in the sender and target fields). We should get those
                // RoomMember objects to update themselves when the events that
                // they are based on are changed.
            }
            // FIXME: apply redactions to notification list
            // NB: We continue to add the redaction event to the timeline so
            // clients can say "so and so redacted an event" if they wish to. Also
            // this may be needed to trigger an update.
        }
        if (event.getUnsigned().transaction_id) {
            const existingEvent = this.txnToEvent[event.getUnsigned().transaction_id];
            if (existingEvent) {
                // remote echo of an event we sent earlier
                this.handleRemoteEcho(event, existingEvent);
                return;
            }
        }
        // add to our timeline sets
        for (let i = 0; i < this.timelineSets.length; i++) {
            this.timelineSets[i].addLiveEvent(event, duplicateStrategy, fromCache);
        }
        // synthesize and inject implicit read receipts
        // Done after adding the event because otherwise the app would get a read receipt
        // pointing to an event that wasn't yet in the timeline
        // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.
        if (event.sender && event.getType() !== event_2.EventType.RoomRedaction) {
            this.addReceipt(synthesizeReceipt(event.sender.userId, event, "m.read"), true);
            // Any live events from a user could be taken as implicit
            // presence information: evidence that they are currently active.
            // ...except in a world where we use 'user.currentlyActive' to reduce
            // presence spam, this isn't very useful - we'll get a transition when
            // they are no longer currently active anyway. So don't bother to
            // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.
        }
    }
    /**
     * Add a pending outgoing event to this room.
     *
     * <p>The event is added to either the pendingEventList, or the live timeline,
     * depending on the setting of opts.pendingEventOrdering.
     *
     * <p>This is an internal method, intended for use by MatrixClient.
     *
     * @param {module:models/event.MatrixEvent} event The event to add.
     *
     * @param {string} txnId Transaction id for this outgoing event
     *
     * @fires module:client~MatrixClient#event:"Room.localEchoUpdated"
     *
     * @throws if the event doesn't have status SENDING, or we aren't given a
     * unique transaction id.
     */
    addPendingEvent(event, txnId) {
        if (event.status !== event_1.EventStatus.SENDING && event.status !== event_1.EventStatus.NOT_SENT) {
            throw new Error("addPendingEvent called on an event with status " +
                event.status);
        }
        if (this.txnToEvent[txnId]) {
            throw new Error("addPendingEvent called on an event with known txnId " +
                txnId);
        }
        // call setEventMetadata to set up event.sender etc
        // as event is shared over all timelineSets, we set up its metadata based
        // on the unfiltered timelineSet.
        event_timeline_1.EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS), false);
        this.txnToEvent[txnId] = event;
        if (this.opts.pendingEventOrdering == "detached") {
            if (this.pendingEventList.some((e) => e.status === event_1.EventStatus.NOT_SENT)) {
                logger_1.logger.warn("Setting event as NOT_SENT due to messages in the same state");
                event.setStatus(event_1.EventStatus.NOT_SENT);
            }
            this.pendingEventList.push(event);
            this.savePendingEvents();
            if (event.isRelation()) {
                // For pending events, add them to the relations collection immediately.
                // (The alternate case below already covers this as part of adding to
                // the timeline set.)
                this.aggregateNonLiveRelation(event);
            }
            if (event.isRedaction()) {
                const redactId = event.event.redacts;
                let redactedEvent = this.pendingEventList &&
                    this.pendingEventList.find(e => e.getId() === redactId);
                if (!redactedEvent) {
                    redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
                }
                if (redactedEvent) {
                    redactedEvent.markLocallyRedacted(event);
                    this.emit("Room.redaction", event, this);
                }
            }
        }
        else {
            for (let i = 0; i < this.timelineSets.length; i++) {
                const timelineSet = this.timelineSets[i];
                if (timelineSet.getFilter()) {
                    if (timelineSet.getFilter().filterRoomTimeline([event]).length) {
                        timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false);
                    }
                }
                else {
                    timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false);
                }
            }
        }
        this.emit("Room.localEchoUpdated", event, this, null, null);
    }
    /**
     * Persists all pending events to local storage
     *
     * If the current room is encrypted only encrypted events will be persisted
     * all messages that are not yet encrypted will be discarded
     *
     * This is because the flow of EVENT_STATUS transition is
     * queued => sending => encrypting => sending => sent
     *
     * Steps 3 and 4 are skipped for unencrypted room.
     * It is better to discard an unencrypted message rather than persisting
     * it locally for everyone to read
     */
    savePendingEvents() {
        if (this.pendingEventList) {
            const pendingEvents = this.pendingEventList.map(event => {
                return Object.assign(Object.assign({}, event.event), { txn_id: event.getTxnId() });
            }).filter(event => {
                // Filter out the unencrypted messages if the room is encrypted
                const isEventEncrypted = event.type === event_2.EventType.RoomMessageEncrypted;
                const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId);
                return isEventEncrypted || !isRoomEncrypted;
            });
            const { store } = this.client.sessionStore;
            if (this.pendingEventList.length > 0) {
                store.setItem(pendingEventsKey(this.roomId), JSON.stringify(pendingEvents));
            }
            else {
                store.removeItem(pendingEventsKey(this.roomId));
            }
        }
    }
    /**
     * Used to aggregate the local echo for a relation, and also
     * for re-applying a relation after it's redaction has been cancelled,
     * as the local echo for the redaction of the relation would have
     * un-aggregated the relation. Note that this is different from regular messages,
     * which are just kept detached for their local echo.
     *
     * Also note that live events are aggregated in the live EventTimelineSet.
     * @param {module:models/event.MatrixEvent} event the relation event that needs to be aggregated.
     */
    aggregateNonLiveRelation(event) {
        // TODO: We should consider whether this means it would be a better
        // design to lift the relations handling up to the room instead.
        for (let i = 0; i < this.timelineSets.length; i++) {
            const timelineSet = this.timelineSets[i];
            if (timelineSet.getFilter()) {
                if (timelineSet.getFilter().filterRoomTimeline([event]).length) {
                    timelineSet.aggregateRelations(event);
                }
            }
            else {
                timelineSet.aggregateRelations(event);
            }
        }
    }
    /**
     * Deal with the echo of a message we sent.
     *
     * <p>We move the event to the live timeline if it isn't there already, and
     * update it.
     *
     * @param {module:models/event.MatrixEvent} remoteEvent   The event received from
     *    /sync
     * @param {module:models/event.MatrixEvent} localEvent    The local echo, which
     *    should be either in the pendingEventList or the timeline.
     *
     * @fires module:client~MatrixClient#event:"Room.localEchoUpdated"
     * @private
     */
    handleRemoteEcho(remoteEvent, localEvent) {
        const oldEventId = localEvent.getId();
        const newEventId = remoteEvent.getId();
        const oldStatus = localEvent.status;
        logger_1.logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} ` +
            `old status ${oldStatus}`);
        // no longer pending
        delete this.txnToEvent[remoteEvent.getUnsigned().transaction_id];
        // if it's in the pending list, remove it
        if (this.pendingEventList) {
            this.removePendingEvent(oldEventId);
        }
        // replace the event source (this will preserve the plaintext payload if
        // any, which is good, because we don't want to try decoding it again).
        localEvent.handleRemoteEcho(remoteEvent.event);
        for (let i = 0; i < this.timelineSets.length; i++) {
            const timelineSet = this.timelineSets[i];
            // if it's already in the timeline, update the timeline map. If it's not, add it.
            timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
        }
        this.emit("Room.localEchoUpdated", localEvent, this, oldEventId, oldStatus);
    }
    /**
     * Update the status / event id on a pending event, to reflect its transmission
     * progress.
     *
     * <p>This is an internal method.
     *
     * @param {MatrixEvent} event      local echo event
     * @param {EventStatus} newStatus  status to assign
     * @param {string} newEventId      new event id to assign. Ignored unless
     *    newStatus == EventStatus.SENT.
     * @fires module:client~MatrixClient#event:"Room.localEchoUpdated"
     */
    updatePendingEvent(event, newStatus, newEventId) {
        logger_1.logger.log(`setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +
            `event ID ${event.getId()} -> ${newEventId}`);
        // if the message was sent, we expect an event id
        if (newStatus == event_1.EventStatus.SENT && !newEventId) {
            throw new Error("updatePendingEvent called with status=SENT, " +
                "but no new event id");
        }
        // SENT races against /sync, so we have to special-case it.
        if (newStatus == event_1.EventStatus.SENT) {
            const timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId);
            if (timeline) {
                // we've already received the event via the event stream.
                // nothing more to do here.
                return;
            }
        }
        const oldStatus = event.status;
        const oldEventId = event.getId();
        if (!oldStatus) {
            throw new Error("updatePendingEventStatus called on an event which is " +
                "not a local echo.");
        }
        const allowed = ALLOWED_TRANSITIONS[oldStatus];
        if (!allowed || allowed.indexOf(newStatus) < 0) {
            throw new Error("Invalid EventStatus transition " + oldStatus + "->" +
                newStatus);
        }
        event.setStatus(newStatus);
        if (newStatus == event_1.EventStatus.SENT) {
            // update the event id
            event.replaceLocalEventId(newEventId);
            // if the event was already in the timeline (which will be the case if
            // opts.pendingEventOrdering==chronological), we need to update the
            // timeline map.
            for (let i = 0; i < this.timelineSets.length; i++) {
                this.timelineSets[i].replaceEventId(oldEventId, newEventId);
            }
        }
        else if (newStatus == event_1.EventStatus.CANCELLED) {
            // remove it from the pending event list, or the timeline.
            if (this.pendingEventList) {
                const idx = this.pendingEventList.findIndex(ev => ev.getId() === oldEventId);
                if (idx !== -1) {
                    const [removedEvent] = this.pendingEventList.splice(idx, 1);
                    if (removedEvent.isRedaction()) {
                        this.revertRedactionLocalEcho(removedEvent);
                    }
                }
            }
            this.removeEvent(oldEventId);
        }
        this.savePendingEvents();
        this.emit("Room.localEchoUpdated", event, this, oldEventId, oldStatus);
    }
    revertRedactionLocalEcho(redactionEvent) {
        const redactId = redactionEvent.event.redacts;
        if (!redactId) {
            return;
        }
        const redactedEvent = this.getUnfilteredTimelineSet()
            .findEventById(redactId);
        if (redactedEvent) {
            redactedEvent.unmarkLocallyRedacted();
            // re-render after undoing redaction
            this.emit("Room.redactionCancelled", redactionEvent, this);
            // reapply relation now redaction failed
            if (redactedEvent.isRelation()) {
                this.aggregateNonLiveRelation(redactedEvent);
            }
        }
    }
    /**
     * Add some events to this room. This can include state events, message
     * events and typing notifications. These events are treated as "live" so
     * they will go to the end of the timeline.
     *
     * @param {MatrixEvent[]} events A list of events to add.
     *
     * @param {string} duplicateStrategy Optional. Applies to events in the
     * timeline only. If this is 'replace' then if a duplicate is encountered, the
     * event passed to this function will replace the existing event in the
     * timeline. If this is not specified, or is 'ignore', then the event passed to
     * this function will be ignored entirely, preserving the existing event in the
     * timeline. Events are identical based on their event ID <b>only</b>.
     *
     * @param {boolean} fromCache whether the sync response came from cache
     * @throws If <code>duplicateStrategy</code> is not falsey, 'replace' or 'ignore'.
     */
    addLiveEvents(events, duplicateStrategy, fromCache = false) {
        let i;
        if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) {
            throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");
        }
        // sanity check that the live timeline is still live
        for (i = 0; i < this.timelineSets.length; i++) {
            const liveTimeline = this.timelineSets[i].getLiveTimeline();
            if (liveTimeline.getPaginationToken(event_timeline_1.EventTimeline.FORWARDS)) {
                throw new Error("live timeline " + i + " is no longer live - it has a pagination token " +
                    "(" + liveTimeline.getPaginationToken(event_timeline_1.EventTimeline.FORWARDS) + ")");
            }
            if (liveTimeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS)) {
                throw new Error("live timeline " + i + " is no longer live - " +
                    "it has a neighbouring timeline");
            }
        }
        for (i = 0; i < events.length; i++) {
            // TODO: We should have a filter to say "only add state event
            // types X Y Z to the timeline".
            this.addLiveEvent(events[i], duplicateStrategy, fromCache);
        }
    }
    /**
     * Adds/handles ephemeral events such as typing notifications and read receipts.
     * @param {MatrixEvent[]} events A list of events to process
     */
    addEphemeralEvents(events) {
        for (const event of events) {
            if (event.getType() === 'm.typing') {
                this.currentState.setTypingEvent(event);
            }
            else if (event.getType() === 'm.receipt') {
                this.addReceipt(event);
            } // else ignore - life is too short for us to care about these events
        }
    }
    /**
     * Removes events from this room.
     * @param {String[]} eventIds A list of eventIds to remove.
     */
    removeEvents(eventIds) {
        for (let i = 0; i < eventIds.length; ++i) {
            this.removeEvent(eventIds[i]);
        }
    }
    /**
     * Removes a single event from this room.
     *
     * @param {String} eventId  The id of the event to remove
     *
     * @return {boolean} true if the event was removed from any of the room's timeline sets
     */
    removeEvent(eventId) {
        let removedAny = false;
        for (let i = 0; i < this.timelineSets.length; i++) {
            const removed = this.timelineSets[i].removeEvent(eventId);
            if (removed) {
                if (removed.isRedaction()) {
                    this.revertRedactionLocalEcho(removed);
                }
                removedAny = true;
            }
        }
        return removedAny;
    }
    /**
     * Recalculate various aspects of the room, including the room name and
     * room summary. Call this any time the room's current state is modified.
     * May fire "Room.name" if the room name is updated.
     * @fires module:client~MatrixClient#event:"Room.name"
     */
    recalculate() {
        // set fake stripped state events if this is an invite room so logic remains
        // consistent elsewhere.
        const membershipEvent = this.currentState.getStateEvents(event_2.EventType.RoomMember, this.myUserId);
        if (membershipEvent && membershipEvent.getContent().membership === "invite") {
            const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];
            strippedStateEvents.forEach((strippedEvent) => {
                const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);
                if (!existingEvent) {
                    // set the fake stripped event instead
                    this.currentState.setStateEvents([new event_1.MatrixEvent({
                            type: strippedEvent.type,
                            state_key: strippedEvent.state_key,
                            content: strippedEvent.content,
                            event_id: "$fake" + Date.now(),
                            room_id: this.roomId,
                            user_id: this.myUserId,
                        })]);
                }
            });
        }
        const oldName = this.name;
        this.name = this.calculateRoomName(this.myUserId);
        this.normalizedName = utils_1.normalize(this.name);
        this.summary = new room_summary_1.RoomSummary(this.roomId, {
            title: this.name,
        });
        if (oldName !== this.name) {
            this.emit("Room.name", this);
        }
    }
    /**
     * Get a list of user IDs who have <b>read up to</b> the given event.
     * @param {MatrixEvent} event the event to get read receipts for.
     * @return {String[]} A list of user IDs.
     */
    getUsersReadUpTo(event) {
        return this.getReceiptsForEvent(event).filter(function (receipt) {
            return receipt.type === "m.read";
        }).map(function (receipt) {
            return receipt.userId;
        });
    }
    /**
     * Get the ID of the event that a given user has read up to, or null if we
     * have received no read receipts from them.
     * @param {String} userId The user ID to get read receipt event ID for
     * @param {Boolean} ignoreSynthesized If true, return only receipts that have been
     *                                    sent by the server, not implicit ones generated
     *                                    by the JS SDK.
     * @return {String} ID of the latest event that the given user has read, or null.
     */
    getEventReadUpTo(userId, ignoreSynthesized = false) {
        let receipts = this.receipts;
        if (ignoreSynthesized) {
            receipts = this.realReceipts;
        }
        if (receipts["m.read"] === undefined ||
            receipts["m.read"][userId] === undefined) {
            return null;
        }
        return receipts["m.read"][userId].eventId;
    }
    /**
     * Determines if the given user has read a particular event ID with the known
     * history of the room. This is not a definitive check as it relies only on
     * what is available to the room at the time of execution.
     * @param {String} userId The user ID to check the read state of.
     * @param {String} eventId The event ID to check if the user read.
     * @returns {Boolean} True if the user has read the event, false otherwise.
     */
    hasUserReadEvent(userId, eventId) {
        const readUpToId = this.getEventReadUpTo(userId, false);
        if (readUpToId === eventId)
            return true;
        if (this.timeline.length
            && this.timeline[this.timeline.length - 1].getSender()
            && this.timeline[this.timeline.length - 1].getSender() === userId) {
            // It doesn't matter where the event is in the timeline, the user has read
            // it because they've sent the latest event.
            return true;
        }
        for (let i = this.timeline.length - 1; i >= 0; --i) {
            const ev = this.timeline[i];
            // If we encounter the target event first, the user hasn't read it
            // however if we encounter the readUpToId first then the user has read
            // it. These rules apply because we're iterating bottom-up.
            if (ev.getId() === eventId)
                return false;
            if (ev.getId() === readUpToId)
                return true;
        }
        // We don't know if the user has read it, so assume not.
        return false;
    }
    /**
     * Get a list of receipts for the given event.
     * @param {MatrixEvent} event the event to get receipts for
     * @return {Object[]} A list of receipts with a userId, type and data keys or
     * an empty list.
     */
    getReceiptsForEvent(event) {
        return this.receiptCacheByEventId[event.getId()] || [];
    }
    /**
     * Add a receipt event to the room.
     * @param {MatrixEvent} event The m.receipt event.
     * @param {Boolean} fake True if this event is implicit
     */
    addReceipt(event, fake = false) {
        if (!fake) {
            this.addReceiptsToStructure(event, this.realReceipts);
            // we don't bother caching real receipts by event ID
            // as there's nothing that would read it.
        }
        this.addReceiptsToStructure(event, this.receipts);
        this.receiptCacheByEventId = this.buildReceiptCache(this.receipts);
        // send events after we've regenerated the cache, otherwise things that
        // listened for the event would read from a stale cache
        this.emit("Room.receipt", event, this);
    }
    /**
     * Add a receipt event to the room.
     * @param {MatrixEvent} event The m.receipt event.
     * @param {Object} receipts The object to add receipts to
     */
    addReceiptsToStructure(event, receipts) {
        const content = event.getContent();
        Object.keys(content).forEach((eventId) => {
            Object.keys(content[eventId]).forEach((receiptType) => {
                Object.keys(content[eventId][receiptType]).forEach((userId) => {
                    const receipt = content[eventId][receiptType][userId];
                    if (!receipts[receiptType]) {
                        receipts[receiptType] = {};
                    }
                    const existingReceipt = receipts[receiptType][userId];
                    if (!existingReceipt) {
                        receipts[receiptType][userId] = {};
                    }
                    else {
                        // we only want to add this receipt if we think it is later
                        // than the one we already have. (This is managed
                        // server-side, but because we synthesize RRs locally we
                        // have to do it here too.)
                        const ordering = this.getUnfilteredTimelineSet().compareEventOrdering(existingReceipt.eventId, eventId);
                        if (ordering !== null && ordering >= 0) {
                            return;
                        }
                    }
                    receipts[receiptType][userId] = {
                        eventId: eventId,
                        data: receipt,
                    };
                });
            });
        });
    }
    /**
     * Build and return a map of receipts by event ID
     * @param {Object} receipts A map of receipts
     * @return {Object} Map of receipts by event ID
     */
    buildReceiptCache(receipts) {
        const receiptCacheByEventId = {};
        Object.keys(receipts).forEach(function (receiptType) {
            Object.keys(receipts[receiptType]).forEach(function (userId) {
                const receipt = receipts[receiptType][userId];
                if (!receiptCacheByEventId[receipt.eventId]) {
                    receiptCacheByEventId[receipt.eventId] = [];
                }
                receiptCacheByEventId[receipt.eventId].push({
                    userId: userId,
                    type: receiptType,
                    data: receipt.data,
                });
            });
        });
        return receiptCacheByEventId;
    }
    /**
     * Add a temporary local-echo receipt to the room to reflect in the
     * client the fact that we've sent one.
     * @param {string} userId The user ID if the receipt sender
     * @param {MatrixEvent} e The event that is to be acknowledged
     * @param {string} receiptType The type of receipt
     */
    addLocalEchoReceipt(userId, e, receiptType) {
        this.addReceipt(synthesizeReceipt(userId, e, receiptType), true);
    }
    /**
     * Update the room-tag event for the room.  The previous one is overwritten.
     * @param {MatrixEvent} event the m.tag event
     */
    addTags(event) {
        // event content looks like:
        // content: {
        //    tags: {
        //       $tagName: { $metadata: $value },
        //       $tagName: { $metadata: $value },
        //    }
        // }
        // XXX: do we need to deep copy here?
        this.tags = event.getContent().tags || {};
        // XXX: we could do a deep-comparison to see if the tags have really
        // changed - but do we want to bother?
        this.emit("Room.tags", event, this);
    }
    /**
     * Update the account_data events for this room, overwriting events of the same type.
     * @param {Array<MatrixEvent>} events an array of account_data events to add
     */
    addAccountData(events) {
        for (let i = 0; i < events.length; i++) {
            const event = events[i];
            if (event.getType() === "m.tag") {
                this.addTags(event);
            }
            const lastEvent = this.accountData[event.getType()];
            this.accountData[event.getType()] = event;
            this.emit("Room.accountData", event, this, lastEvent);
        }
    }
    /**
     * Access account_data event of given event type for this room
     * @param {string} type the type of account_data event to be accessed
     * @return {?MatrixEvent} the account_data event in question
     */
    getAccountData(type) {
        return this.accountData[type];
    }
    /**
     * Returns whether the syncing user has permission to send a message in the room
     * @return {boolean} true if the user should be permitted to send
     *                   message events into the room.
     */
    maySendMessage() {
        return this.getMyMembership() === 'join' &&
            this.currentState.maySendEvent(event_2.EventType.RoomMessage, this.myUserId);
    }
    /**
     * Returns whether the given user has permissions to issue an invite for this room.
     * @param {string} userId the ID of the Matrix user to check permissions for
     * @returns {boolean} true if the user should be permitted to issue invites for this room.
     */
    canInvite(userId) {
        let canInvite = this.getMyMembership() === "join";
        const powerLevelsEvent = this.currentState.getStateEvents(event_2.EventType.RoomPowerLevels, "");
        const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();
        const me = this.getMember(userId);
        if (powerLevels && me && powerLevels.invite > me.powerLevel) {
            canInvite = false;
        }
        return canInvite;
    }
    /**
     * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
     * @returns {string} the join_rule applied to this room
     */
    getJoinRule() {
        return this.currentState.getJoinRule();
    }
    /**
     * Returns the type of the room from the `m.room.create` event content or undefined if none is set
     * @returns {?string} the type of the room. Currently only RoomType.Space is known.
     */
    getType() {
        const createEvent = this.currentState.getStateEvents(event_2.EventType.RoomCreate, "");
        if (!createEvent) {
            if (!this.getTypeWarning) {
                logger_1.logger.warn("[getType] Room " + this.roomId + " does not have an m.room.create event");
                this.getTypeWarning = true;
            }
            return undefined;
        }
        return createEvent.getContent()[event_2.RoomCreateTypeField];
    }
    /**
     * Returns whether the room is a space-room as defined by MSC1772.
     * @returns {boolean} true if the room's type is RoomType.Space
     */
    isSpaceRoom() {
        return this.getType() === event_2.RoomType.Space;
    }
    /**
     * This is an internal method. Calculates the name of the room from the current
     * room state.
     * @param {string} userId The client's user ID. Used to filter room members
     * correctly.
     * @param {boolean} ignoreRoomNameEvent Return the implicit room name that we'd see if there
     * was no m.room.name event.
     * @return {string} The calculated room name.
     */
    calculateRoomName(userId, ignoreRoomNameEvent = false) {
        if (!ignoreRoomNameEvent) {
            // check for an alias, if any. for now, assume first alias is the
            // official one.
            const mRoomName = this.currentState.getStateEvents(event_2.EventType.RoomName, "");
            if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {
                return mRoomName.getContent().name;
            }
        }
        let alias = this.getCanonicalAlias();
        if (!alias) {
            const aliases = this.getAltAliases();
            if (aliases.length) {
                alias = aliases[0];
            }
        }
        if (alias) {
            return alias;
        }
        const joinedMemberCount = this.currentState.getJoinedMemberCount();
        const invitedMemberCount = this.currentState.getInvitedMemberCount();
        // -1 because these numbers include the syncing user
        const inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;
        // get members that are NOT ourselves and are actually in the room.
        let otherNames = null;
        if (this.summaryHeroes) {
            // if we have a summary, the member state events
            // should be in the room state
            otherNames = this.summaryHeroes.map((userId) => {
                const member = this.getMember(userId);
                return member ? member.name : userId;
            });
        }
        else {
            let otherMembers = this.currentState.getMembers().filter((m) => {
                return m.userId !== userId &&
                    (m.membership === "invite" || m.membership === "join");
            });
            // make sure members have stable order
            otherMembers.sort((a, b) => a.userId.localeCompare(b.userId));
            // only 5 first members, immitate summaryHeroes
            otherMembers = otherMembers.slice(0, 5);
            otherNames = otherMembers.map((m) => m.name);
        }
        if (inviteJoinCount) {
            return memberNamesToRoomName(otherNames, inviteJoinCount);
        }
        const myMembership = this.getMyMembership();
        // if I have created a room and invited people throuh
        // 3rd party invites
        if (myMembership == 'join') {
            const thirdPartyInvites = this.currentState.getStateEvents(event_2.EventType.RoomThirdPartyInvite);
            if (thirdPartyInvites && thirdPartyInvites.length) {
                const thirdPartyNames = thirdPartyInvites.map((i) => {
                    return i.getContent().display_name;
                });
                return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`;
            }
        }
        // let's try to figure out who was here before
        let leftNames = otherNames;
        // if we didn't have heroes, try finding them in the room state
        if (!leftNames.length) {
            leftNames = this.currentState.getMembers().filter((m) => {
                return m.userId !== userId &&
                    m.membership !== "invite" &&
                    m.membership !== "join";
            }).map((m) => m.name);
        }
        if (leftNames.length) {
            return `Empty room (was ${memberNamesToRoomName(leftNames)})`;
        }
        else {
            return "Empty room";
        }
    }
}
exports.Room = Room;
/**
 * @param {string} roomId ID of the current room
 * @returns {string} Storage key to retrieve pending events
 */
function pendingEventsKey(roomId) {
    return `mx_pending_events_${roomId}`;
}
/* a map from current event status to a list of allowed next statuses
     */
const ALLOWED_TRANSITIONS = {};
ALLOWED_TRANSITIONS[event_1.EventStatus.ENCRYPTING] = [
    event_1.EventStatus.SENDING,
    event_1.EventStatus.NOT_SENT,
];
ALLOWED_TRANSITIONS[event_1.EventStatus.SENDING] = [
    event_1.EventStatus.ENCRYPTING,
    event_1.EventStatus.QUEUED,
    event_1.EventStatus.NOT_SENT,
    event_1.EventStatus.SENT,
];
ALLOWED_TRANSITIONS[event_1.EventStatus.QUEUED] =
    [event_1.EventStatus.SENDING, event_1.EventStatus.CANCELLED];
ALLOWED_TRANSITIONS[event_1.EventStatus.SENT] =
    [];
ALLOWED_TRANSITIONS[event_1.EventStatus.NOT_SENT] =
    [event_1.EventStatus.SENDING, event_1.EventStatus.QUEUED, event_1.EventStatus.CANCELLED];
ALLOWED_TRANSITIONS[event_1.EventStatus.CANCELLED] =
    [];
// TODO i18n
function memberNamesToRoomName(names, count = (names.length + 1)) {
    const countWithoutMe = count - 1;
    if (!names.length) {
        return "Empty room";
    }
    else if (names.length === 1 && countWithoutMe <= 1) {
        return names[0];
    }
    else if (names.length === 2 && countWithoutMe <= 2) {
        return `${names[0]} and ${names[1]}`;
    }
    else {
        const plural = countWithoutMe > 1;
        if (plural) {
            return `${names[0]} and ${countWithoutMe} others`;
        }
        else {
            return `${names[0]} and 1 other`;
        }
    }
}
/**
 * Fires when an event we had previously received is redacted.
 *
 * (Note this is *not* fired when the redaction happens before we receive the
 * event).
 *
 * @event module:client~MatrixClient#"Room.redaction"
 * @param {MatrixEvent} event The matrix redaction event
 * @param {Room} room The room containing the redacted event
 */
/**
 * Fires when an event that was previously redacted isn't anymore.
 * This happens when the redaction couldn't be sent and
 * was subsequently cancelled by the user. Redactions have a local echo
 * which is undone in this scenario.
 *
 * @event module:client~MatrixClient#"Room.redactionCancelled"
 * @param {MatrixEvent} event The matrix redaction event that was cancelled.
 * @param {Room} room The room containing the unredacted event
 */
/**
 * Fires whenever the name of a room is updated.
 * @event module:client~MatrixClient#"Room.name"
 * @param {Room} room The room whose Room.name was updated.
 * @example
 * matrixClient.on("Room.name", function(room){
 *   var newName = room.name;
 * });
 */
/**
 * Fires whenever a receipt is received for a room
 * @event module:client~MatrixClient#"Room.receipt"
 * @param {event} event The receipt event
 * @param {Room} room The room whose receipts was updated.
 * @example
 * matrixClient.on("Room.receipt", function(event, room){
 *   var receiptContent = event.getContent();
 * });
 */
/**
 * Fires whenever a room's tags are updated.
 * @event module:client~MatrixClient#"Room.tags"
 * @param {event} event The tags event
 * @param {Room} room The room whose Room.tags was updated.
 * @example
 * matrixClient.on("Room.tags", function(event, room){
 *   var newTags = event.getContent().tags;
 *   if (newTags["favourite"]) showStar(room);
 * });
 */
/**
 * Fires whenever a room's account_data is updated.
 * @event module:client~MatrixClient#"Room.accountData"
 * @param {event} event The account_data event
 * @param {Room} room The room whose account_data was updated.
 * @param {MatrixEvent} prevEvent The event being replaced by
 * the new account data, if known.
 * @example
 * matrixClient.on("Room.accountData", function(event, room, oldEvent){
 *   if (event.getType() === "m.room.colorscheme") {
 *       applyColorScheme(event.getContents());
 *   }
 * });
 */
/**
 * Fires when the status of a transmitted event is updated.
 *
 * <p>When an event is first transmitted, a temporary copy of the event is
 * inserted into the timeline, with a temporary event id, and a status of
 * 'SENDING'.
 *
 * <p>Once the echo comes back from the server, the content of the event
 * (MatrixEvent.event) is replaced by the complete event from the homeserver,
 * thus updating its event id, as well as server-generated fields such as the
 * timestamp. Its status is set to null.
 *
 * <p>Once the /send request completes, if the remote echo has not already
 * arrived, the event is updated with a new event id and the status is set to
 * 'SENT'. The server-generated fields are of course not updated yet.
 *
 * <p>If the /send fails, In this case, the event's status is set to
 * 'NOT_SENT'. If it is later resent, the process starts again, setting the
 * status to 'SENDING'. Alternatively, the message may be cancelled, which
 * removes the event from the room, and sets the status to 'CANCELLED'.
 *
 * <p>This event is raised to reflect each of the transitions above.
 *
 * @event module:client~MatrixClient#"Room.localEchoUpdated"
 *
 * @param {MatrixEvent} event The matrix event which has been updated
 *
 * @param {Room} room The room containing the redacted event
 *
 * @param {string} oldEventId The previous event id (the temporary event id,
 *    except when updating a successfully-sent event when its echo arrives)
 *
 * @param {EventStatus} oldStatus The previous event status.
 */
/**
 * Fires when the logged in user's membership in the room is updated.
 *
 * @event module:models/room~Room#"Room.myMembership"
 * @param {Room} room The room in which the membership has been updated
 * @param {string} membership The new membership value
 * @param {string} prevMembership The previous membership value
 */

},{"../@types/event":58,"../ReEmitter":61,"../client":64,"../content-repo":66,"../logger":106,"../utils":137,"./event":113,"./event-timeline":112,"./event-timeline-set":111,"./room-member":116,"./room-summary":118,"events":36}],120:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SearchResult = SearchResult;

var _eventContext = require("./event-context");

/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/**
 * @module models/search-result
 */

/**
 * Construct a new SearchResult
 *
 * @param {number} rank   where this SearchResult ranks in the results
 * @param {event-context.EventContext} eventContext  the matching event and its
 *    context
 *
 * @constructor
 */
function SearchResult(rank, eventContext) {
  this.rank = rank;
  this.context = eventContext;
}
/**
 * Create a SearchResponse from the response to /search
 * @static
 * @param {Object} jsonObj
 * @param {function} eventMapper
 * @return {SearchResult}
 */


SearchResult.fromJson = function (jsonObj, eventMapper) {
  var jsonContext = jsonObj.context || {};
  var events_before = jsonContext.events_before || [];
  var events_after = jsonContext.events_after || [];
  var context = new _eventContext.EventContext(eventMapper(jsonObj.result));
  context.setPaginateToken(jsonContext.start, true);
  context.addEvents(events_before.map(eventMapper), true);
  context.addEvents(events_after.map(eventMapper), false);
  context.setPaginateToken(jsonContext.end, false);
  return new SearchResult(jsonObj.rank, context);
};

},{"./event-context":110}],121:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.User = void 0;
/**
 * @module models/user
 */
const events_1 = require("events");
class User extends events_1.EventEmitter {
    /**
     * Construct a new User. A User must have an ID and can optionally have extra
     * information associated with it.
     * @constructor
     * @param {string} userId Required. The ID of this user.
     * @prop {string} userId The ID of the user.
     * @prop {Object} info The info object supplied in the constructor.
     * @prop {string} displayName The 'displayname' of the user if known.
     * @prop {string} avatarUrl The 'avatar_url' of the user if known.
     * @prop {string} presence The presence enum if known.
     * @prop {string} presenceStatusMsg The presence status message if known.
     * @prop {Number} lastActiveAgo The time elapsed in ms since the user interacted
     *                proactively with the server, or we saw a message from the user
     * @prop {Number} lastPresenceTs Timestamp (ms since the epoch) for when we last
     *                received presence data for this user.  We can subtract
     *                lastActiveAgo from this to approximate an absolute value for
     *                when a user was last active.
     * @prop {Boolean} currentlyActive Whether we should consider lastActiveAgo to be
     *               an approximation and that the user should be seen as active 'now'
     * @prop {string} unstable_statusMessage The status message for the user, if known. This is
     *                different from the presenceStatusMsg in that this is not tied to
     *                the user's presence, and should be represented differently.
     * @prop {Object} events The events describing this user.
     * @prop {MatrixEvent} events.presence The m.presence event for this user.
     */
    constructor(userId) {
        super();
        this.userId = userId;
        this.presenceStatusMsg = null;
        this.presence = "offline";
        this.lastActiveAgo = 0;
        this.lastPresenceTs = 0;
        this.currentlyActive = false;
        this.events = {
            presence: null,
            profile: null,
        };
        // eslint-disable-next-line camelcase
        this.unstable_statusMessage = "";
        this.displayName = userId;
        this.rawDisplayName = userId;
        this.avatarUrl = null;
        this.updateModifiedTime();
    }
    /**
     * Update this User with the given presence event. May fire "User.presence",
     * "User.avatarUrl" and/or "User.displayName" if this event updates this user's
     * properties.
     * @param {MatrixEvent} event The <code>m.presence</code> event.
     * @fires module:client~MatrixClient#event:"User.presence"
     * @fires module:client~MatrixClient#event:"User.displayName"
     * @fires module:client~MatrixClient#event:"User.avatarUrl"
     */
    setPresenceEvent(event) {
        if (event.getType() !== "m.presence") {
            return;
        }
        const firstFire = this.events.presence === null;
        this.events.presence = event;
        const eventsToFire = [];
        if (event.getContent().presence !== this.presence || firstFire) {
            eventsToFire.push("User.presence");
        }
        if (event.getContent().avatar_url &&
            event.getContent().avatar_url !== this.avatarUrl) {
            eventsToFire.push("User.avatarUrl");
        }
        if (event.getContent().displayname &&
            event.getContent().displayname !== this.displayName) {
            eventsToFire.push("User.displayName");
        }
        if (event.getContent().currently_active !== undefined &&
            event.getContent().currently_active !== this.currentlyActive) {
            eventsToFire.push("User.currentlyActive");
        }
        this.presence = event.getContent().presence;
        eventsToFire.push("User.lastPresenceTs");
        if (event.getContent().status_msg) {
            this.presenceStatusMsg = event.getContent().status_msg;
        }
        if (event.getContent().displayname) {
            this.displayName = event.getContent().displayname;
        }
        if (event.getContent().avatar_url) {
            this.avatarUrl = event.getContent().avatar_url;
        }
        this.lastActiveAgo = event.getContent().last_active_ago;
        this.lastPresenceTs = Date.now();
        this.currentlyActive = event.getContent().currently_active;
        this.updateModifiedTime();
        for (let i = 0; i < eventsToFire.length; i++) {
            this.emit(eventsToFire[i], event, this);
        }
    }
    /**
     * Manually set this user's display name. No event is emitted in response to this
     * as there is no underlying MatrixEvent to emit with.
     * @param {string} name The new display name.
     */
    setDisplayName(name) {
        const oldName = this.displayName;
        if (typeof name === "string") {
            this.displayName = name;
        }
        else {
            this.displayName = undefined;
        }
        if (name !== oldName) {
            this.updateModifiedTime();
        }
    }
    /**
     * Manually set this user's non-disambiguated display name. No event is emitted
     * in response to this as there is no underlying MatrixEvent to emit with.
     * @param {string} name The new display name.
     */
    setRawDisplayName(name) {
        if (typeof name === "string") {
            this.rawDisplayName = name;
        }
        else {
            this.rawDisplayName = undefined;
        }
    }
    /**
     * Manually set this user's avatar URL. No event is emitted in response to this
     * as there is no underlying MatrixEvent to emit with.
     * @param {string} url The new avatar URL.
     */
    setAvatarUrl(url) {
        const oldUrl = this.avatarUrl;
        this.avatarUrl = url;
        if (url !== oldUrl) {
            this.updateModifiedTime();
        }
    }
    /**
     * Update the last modified time to the current time.
     */
    updateModifiedTime() {
        this.modified = Date.now();
    }
    /**
     * Get the timestamp when this User was last updated. This timestamp is
     * updated when this User receives a new Presence event which has updated a
     * property on this object. It is updated <i>before</i> firing events.
     * @return {number} The timestamp
     */
    getLastModifiedTime() {
        return this.modified;
    }
    /**
     * Get the absolute timestamp when this User was last known active on the server.
     * It is *NOT* accurate if this.currentlyActive is true.
     * @return {number} The timestamp
     */
    getLastActiveTs() {
        return this.lastPresenceTs - this.lastActiveAgo;
    }
    /**
     * Manually set the user's status message.
     * @param {MatrixEvent} event The <code>im.vector.user_status</code> event.
     * @fires module:client~MatrixClient#event:"User.unstable_statusMessage"
     */
    // eslint-disable-next-line camelcase
    unstable_updateStatusMessage(event) {
        if (!event.getContent())
            this.unstable_statusMessage = "";
        else
            this.unstable_statusMessage = event.getContent()["status"];
        this.updateModifiedTime();
        this.emit("User.unstable_statusMessage", this);
    }
}
exports.User = User;
/**
 * Fires whenever any user's lastPresenceTs changes,
 * ie. whenever any presence event is received for a user.
 * @event module:client~MatrixClient#"User.lastPresenceTs"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {User} user The user whose User.lastPresenceTs changed.
 * @example
 * matrixClient.on("User.lastPresenceTs", function(event, user){
 *   var newlastPresenceTs = user.lastPresenceTs;
 * });
 */
/**
 * Fires whenever any user's presence changes.
 * @event module:client~MatrixClient#"User.presence"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {User} user The user whose User.presence changed.
 * @example
 * matrixClient.on("User.presence", function(event, user){
 *   var newPresence = user.presence;
 * });
 */
/**
 * Fires whenever any user's currentlyActive changes.
 * @event module:client~MatrixClient#"User.currentlyActive"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {User} user The user whose User.currentlyActive changed.
 * @example
 * matrixClient.on("User.currentlyActive", function(event, user){
 *   var newCurrentlyActive = user.currentlyActive;
 * });
 */
/**
 * Fires whenever any user's display name changes.
 * @event module:client~MatrixClient#"User.displayName"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {User} user The user whose User.displayName changed.
 * @example
 * matrixClient.on("User.displayName", function(event, user){
 *   var newName = user.displayName;
 * });
 */
/**
 * Fires whenever any user's avatar URL changes.
 * @event module:client~MatrixClient#"User.avatarUrl"
 * @param {MatrixEvent} event The matrix event which caused this event to fire.
 * @param {User} user The user whose User.avatarUrl changed.
 * @example
 * matrixClient.on("User.avatarUrl", function(event, user){
 *   var newUrl = user.avatarUrl;
 * });
 */

},{"events":36}],122:[function(require,module,exports){
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PushProcessor = PushProcessor;

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _utils = require("./utils");

var _logger = require("./logger");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

/**
 * @module pushprocessor
 */
var RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride']; // The default override rules to apply to the push rules that arrive from the server.
// We do this for two reasons:
//   1. Synapse is unlikely to send us the push rule in an incremental sync - see
//      https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for
//      more details.
//   2. We often want to start using push rules ahead of the server supporting them,
//      and so we can put them here.

var DEFAULT_OVERRIDE_RULES = [{
  // For homeservers which don't support MSC1930 yet
  rule_id: ".m.rule.tombstone",
  "default": true,
  enabled: true,
  conditions: [{
    kind: "event_match",
    key: "type",
    pattern: "m.room.tombstone"
  }, {
    kind: "event_match",
    key: "state_key",
    pattern: ""
  }],
  actions: ["notify", {
    set_tweak: "highlight",
    value: true
  }]
}, {
  // For homeservers which don't support MSC2153 yet
  rule_id: ".m.rule.reaction",
  "default": true,
  enabled: true,
  conditions: [{
    kind: "event_match",
    key: "type",
    pattern: "m.reaction"
  }],
  actions: ["dont_notify"]
}];
/**
 * Construct a Push Processor.
 * @constructor
 * @param {Object} client The Matrix client object to use
 */

function PushProcessor(client) {
  var _this = this;

  var cachedGlobToRegex = {// $glob: RegExp,
  };

  var matchingRuleFromKindSet = function matchingRuleFromKindSet(ev, kindset) {
    for (var ruleKindIndex = 0; ruleKindIndex < RULEKINDS_IN_ORDER.length; ++ruleKindIndex) {
      var kind = RULEKINDS_IN_ORDER[ruleKindIndex];
      var ruleset = kindset[kind];

      if (!ruleset) {
        continue;
      }

      for (var ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {
        var rule = ruleset[ruleIndex];

        if (!rule.enabled) {
          continue;
        }

        var rawrule = templateRuleToRaw(kind, rule);

        if (!rawrule) {
          continue;
        }

        if (_this.ruleMatchesEvent(rawrule, ev)) {
          rule.kind = kind;
          return rule;
        }
      }
    }

    return null;
  };

  var templateRuleToRaw = function templateRuleToRaw(kind, tprule) {
    var rawrule = {
      'rule_id': tprule.rule_id,
      'actions': tprule.actions,
      'conditions': []
    };

    switch (kind) {
      case 'underride':
      case 'override':
        rawrule.conditions = tprule.conditions;
        break;

      case 'room':
        if (!tprule.rule_id) {
          return null;
        }

        rawrule.conditions.push({
          'kind': 'event_match',
          'key': 'room_id',
          'value': tprule.rule_id
        });
        break;

      case 'sender':
        if (!tprule.rule_id) {
          return null;
        }

        rawrule.conditions.push({
          'kind': 'event_match',
          'key': 'user_id',
          'value': tprule.rule_id
        });
        break;

      case 'content':
        if (!tprule.pattern) {
          return null;
        }

        rawrule.conditions.push({
          'kind': 'event_match',
          'key': 'content.body',
          'pattern': tprule.pattern
        });
        break;
    }

    return rawrule;
  };

  var eventFulfillsCondition = function eventFulfillsCondition(cond, ev) {
    var condition_functions = {
      "event_match": eventFulfillsEventMatchCondition,
      "contains_display_name": eventFulfillsDisplayNameCondition,
      "room_member_count": eventFulfillsRoomMemberCountCondition,
      "sender_notification_permission": eventFulfillsSenderNotifPermCondition
    };

    if (condition_functions[cond.kind]) {
      return condition_functions[cond.kind](cond, ev);
    } // unknown conditions: we previously matched all unknown conditions,
    // but given that rules can be added to the base rules on a server,
    // it's probably better to not match unknown conditions.


    return false;
  };

  var eventFulfillsSenderNotifPermCondition = function eventFulfillsSenderNotifPermCondition(cond, ev) {
    var notifLevelKey = cond['key'];

    if (!notifLevelKey) {
      return false;
    }

    var room = client.getRoom(ev.getRoomId());

    if (!room || !room.currentState) {
      return false;
    } // Note that this should not be the current state of the room but the state at
    // the point the event is in the DAG. Unfortunately the js-sdk does not store
    // this.


    return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender());
  };

  var eventFulfillsRoomMemberCountCondition = function eventFulfillsRoomMemberCountCondition(cond, ev) {
    if (!cond.is) {
      return false;
    }

    var room = client.getRoom(ev.getRoomId());

    if (!room || !room.currentState || !room.currentState.members) {
      return false;
    }

    var memberCount = room.currentState.getJoinedMemberCount();
    var m = cond.is.match(/^([=<>]*)([0-9]*)$/);

    if (!m) {
      return false;
    }

    var ineq = m[1];
    var rhs = parseInt(m[2]);

    if (isNaN(rhs)) {
      return false;
    }

    switch (ineq) {
      case '':
      case '==':
        return memberCount == rhs;

      case '<':
        return memberCount < rhs;

      case '>':
        return memberCount > rhs;

      case '<=':
        return memberCount <= rhs;

      case '>=':
        return memberCount >= rhs;

      default:
        return false;
    }
  };

  var eventFulfillsDisplayNameCondition = function eventFulfillsDisplayNameCondition(cond, ev) {
    var content = ev.getContent();

    if (ev.isEncrypted() && ev.getClearContent()) {
      content = ev.getClearContent();
    }

    if (!content || !content.body || typeof content.body != 'string') {
      return false;
    }

    var room = client.getRoom(ev.getRoomId());

    if (!room || !room.currentState || !room.currentState.members || !room.currentState.getMember(client.credentials.userId)) {
      return false;
    }

    var displayName = room.currentState.getMember(client.credentials.userId).name; // N.B. we can't use \b as it chokes on unicode. however \W seems to be okay
    // as shorthand for [^0-9A-Za-z_].

    var pat = new RegExp("(^|\\W)" + (0, _utils.escapeRegExp)(displayName) + "(\\W|$)", 'i');
    return content.body.search(pat) > -1;
  };

  var eventFulfillsEventMatchCondition = function eventFulfillsEventMatchCondition(cond, ev) {
    if (!cond.key) {
      return false;
    }

    var val = valueForDottedKey(cond.key, ev);

    if (typeof val !== 'string') {
      return false;
    }

    if (cond.value) {
      return cond.value === val;
    }

    if (typeof cond.pattern !== 'string') {
      return false;
    }

    var regex;

    if (cond.key == 'content.body') {
      regex = createCachedRegex('(^|\\W)', cond.pattern, '(\\W|$)');
    } else {
      regex = createCachedRegex('^', cond.pattern, '$');
    }

    return !!val.match(regex);
  };

  var createCachedRegex = function createCachedRegex(prefix, glob, suffix) {
    if (cachedGlobToRegex[glob]) {
      return cachedGlobToRegex[glob];
    }

    cachedGlobToRegex[glob] = new RegExp(prefix + (0, _utils.globToRegexp)(glob) + suffix, 'i');
    return cachedGlobToRegex[glob];
  };

  var valueForDottedKey = function valueForDottedKey(key, ev) {
    var parts = key.split('.');
    var val; // special-case the first component to deal with encrypted messages

    var firstPart = parts[0];

    if (firstPart === 'content') {
      val = ev.getContent();
      parts.shift();
    } else if (firstPart === 'type') {
      val = ev.getType();
      parts.shift();
    } else {
      // use the raw event for any other fields
      val = ev.event;
    }

    while (parts.length > 0) {
      var thisPart = parts.shift();

      if ((0, _utils.isNullOrUndefined)(val[thisPart])) {
        return null;
      }

      val = val[thisPart];
    }

    return val;
  };

  var matchingRuleForEventWithRulesets = function matchingRuleForEventWithRulesets(ev, rulesets) {
    if (!rulesets) {
      return null;
    }

    if (ev.getSender() === client.credentials.userId) {
      return null;
    }

    return matchingRuleFromKindSet(ev, rulesets.global);
  };

  var pushActionsForEventAndRulesets = function pushActionsForEventAndRulesets(ev, rulesets) {
    var rule = matchingRuleForEventWithRulesets(ev, rulesets);

    if (!rule) {
      return {};
    }

    var actionObj = PushProcessor.actionListToActionsObject(rule.actions); // Some actions are implicit in some situations: we add those here

    if (actionObj.tweaks.highlight === undefined) {
      // if it isn't specified, highlight if it's a content
      // rule but otherwise not
      actionObj.tweaks.highlight = rule.kind == 'content';
    }

    return actionObj;
  };

  this.ruleMatchesEvent = function (rule, ev) {
    var ret = true;

    for (var i = 0; i < rule.conditions.length; ++i) {
      var cond = rule.conditions[i];
      ret &= eventFulfillsCondition(cond, ev);
    } //console.log("Rule "+rule.rule_id+(ret ? " matches" : " doesn't match"));


    return ret;
  };
  /**
   * Get the user's push actions for the given event
   *
   * @param {module:models/event.MatrixEvent} ev
   *
   * @return {PushAction}
   */


  this.actionsForEvent = function (ev) {
    return pushActionsForEventAndRulesets(ev, client.pushRules);
  };
  /**
   * Get one of the users push rules by its ID
   *
   * @param {string} ruleId The ID of the rule to search for
   * @return {object} The push rule, or null if no such rule was found
   */


  this.getPushRuleById = function (ruleId) {
    for (var _i = 0, _arr = ['global']; _i < _arr.length; _i++) {
      var scope = _arr[_i];
      if (client.pushRules[scope] === undefined) continue;

      var _iterator = _createForOfIteratorHelper(RULEKINDS_IN_ORDER),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var kind = _step.value;
          if (client.pushRules[scope][kind] === undefined) continue;

          var _iterator2 = _createForOfIteratorHelper(client.pushRules[scope][kind]),
              _step2;

          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var rule = _step2.value;
              if (rule.rule_id === ruleId) return rule;
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }

    return null;
  };
}
/**
 * Convert a list of actions into a object with the actions as keys and their values
 * eg. [ 'notify', { set_tweak: 'sound', value: 'default' } ]
 *     becomes { notify: true, tweaks: { sound: 'default' } }
 * @param {array} actionlist The actions list
 *
 * @return {object} A object with key 'notify' (true or false) and an object of actions
 */


PushProcessor.actionListToActionsObject = function (actionlist) {
  var actionobj = {
    'notify': false,
    'tweaks': {}
  };

  for (var i = 0; i < actionlist.length; ++i) {
    var action = actionlist[i];

    if (action === 'notify') {
      actionobj.notify = true;
    } else if ((0, _typeof2["default"])(action) === 'object') {
      if (action.value === undefined) {
        action.value = true;
      }

      actionobj.tweaks[action.set_tweak] = action.value;
    }
  }

  return actionobj;
};
/**
 * Rewrites conditions on a client's push rules to match the defaults
 * where applicable. Useful for upgrading push rules to more strict
 * conditions when the server is falling behind on defaults.
 * @param {object} incomingRules The client's existing push rules
 * @returns {object} The rewritten rules
 */


PushProcessor.rewriteDefaultRules = function (incomingRules) {
  var newRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone
  // These lines are mostly to make the tests happy. We shouldn't run into these
  // properties missing in practice.

  if (!newRules) newRules = {};
  if (!newRules.global) newRules.global = {};
  if (!newRules.global.override) newRules.global.override = []; // Merge the client-level defaults with the ones from the server

  var globalOverrides = newRules.global.override;

  var _iterator3 = _createForOfIteratorHelper(DEFAULT_OVERRIDE_RULES),
      _step3;

  try {
    var _loop = function _loop() {
      var override = _step3.value;
      var existingRule = globalOverrides.find(function (r) {
        return r.rule_id === override.rule_id;
      });

      if (existingRule) {
        // Copy over the actions, default, and conditions. Don't touch the user's
        // preference.
        existingRule["default"] = override["default"];
        existingRule.conditions = override.conditions;
        existingRule.actions = override.actions;
      } else {
        // Add the rule
        var ruleId = override.rule_id;

        _logger.logger.warn("Adding default global override for ".concat(ruleId));

        globalOverrides.push(override);
      }
    };

    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      _loop();
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }

  return newRules;
};
/**
 * @typedef {Object} PushAction
 * @type {Object}
 * @property {boolean} notify Whether this event should notify the user or not.
 * @property {Object} tweaks How this event should be notified.
 * @property {boolean} tweaks.highlight Whether this event should be highlighted
 * on the UI.
 * @property {boolean} tweaks.sound Whether this notification should produce a
 * noise.
 */

},{"./logger":106,"./utils":137,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/typeof":24}],123:[function(require,module,exports){
"use strict";
/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.randomUppercaseString = exports.randomLowercaseString = exports.randomString = void 0;
const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS = "0123456789";
function randomString(len) {
    return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);
}
exports.randomString = randomString;
function randomLowercaseString(len) {
    return randomStringFrom(len, LOWERCASE);
}
exports.randomLowercaseString = randomLowercaseString;
function randomUppercaseString(len) {
    return randomStringFrom(len, UPPERCASE);
}
exports.randomUppercaseString = randomUppercaseString;
function randomStringFrom(len, chars) {
    let ret = "";
    for (let i = 0; i < len; ++i) {
        ret += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return ret;
}

},{}],124:[function(require,module,exports){
(function (global){(function (){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setNow = setNow;
exports.setTimeout = setTimeout;
exports.clearTimeout = clearTimeout;

var _logger = require("./logger");

/*
Copyright 2016 OpenMarket Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/* A re-implementation of the javascript callback functions (setTimeout,
 * clearTimeout; setInterval and clearInterval are not yet implemented) which
 * try to improve handling of large clock jumps (as seen when
 * suspending/resuming the system).
 *
 * In particular, if a timeout would have fired while the system was suspended,
 * it will instead fire as soon as possible after resume.
 */
// we schedule a callback at least this often, to check if we've missed out on
// some wall-clock time due to being suspended.
var TIMER_CHECK_PERIOD_MS = 1000; // counter, for making up ids to return from setTimeout

var _count = 0; // the key for our callback with the real global.setTimeout

var _realCallbackKey; // a sorted list of the callbacks to be run.
// each is an object with keys [runAt, func, params, key].


var _callbackList = []; // var debuglog = logger.log.bind(logger);

var debuglog = function debuglog() {};
/**
 * Replace the function used by this module to get the current time.
 *
 * Intended for use by the unit tests.
 *
 * @param {function} [f] function which should return a millisecond counter
 *
 * @internal
 */


function setNow(f) {
  _now = f || Date.now;
}

var _now = Date.now;
/**
 * reimplementation of window.setTimeout, which will call the callback if
 * the wallclock time goes past the deadline.
 *
 * @param {function} func   callback to be called after a delay
 * @param {Number} delayMs  number of milliseconds to delay by
 *
 * @return {Number} an identifier for this callback, which may be passed into
 *                   clearTimeout later.
 */

function setTimeout(func, delayMs) {
  delayMs = delayMs || 0;

  if (delayMs < 0) {
    delayMs = 0;
  }

  var params = Array.prototype.slice.call(arguments, 2);
  var runAt = _now() + delayMs;
  var key = _count++;
  debuglog("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")");
  var data = {
    runAt: runAt,
    func: func,
    params: params,
    key: key
  }; // figure out where it goes in the list

  var idx = binarySearch(_callbackList, function (el) {
    return el.runAt - runAt;
  });

  _callbackList.splice(idx, 0, data);

  _scheduleRealCallback();

  return key;
}
/**
 * reimplementation of window.clearTimeout, which mirrors setTimeout
 *
 * @param {Number} key   result from an earlier setTimeout call
 */


function clearTimeout(key) {
  if (_callbackList.length === 0) {
    return;
  } // remove the element from the list


  var i;

  for (i = 0; i < _callbackList.length; i++) {
    var cb = _callbackList[i];

    if (cb.key == key) {
      _callbackList.splice(i, 1);

      break;
    }
  } // iff it was the first one in the list, reschedule our callback.


  if (i === 0) {
    _scheduleRealCallback();
  }
} // use the real global.setTimeout to schedule a callback to _runCallbacks.


function _scheduleRealCallback() {
  if (_realCallbackKey) {
    global.clearTimeout(_realCallbackKey);
  }

  var first = _callbackList[0];

  if (!first) {
    debuglog("_scheduleRealCallback: no more callbacks, not rescheduling");
    return;
  }

  var now = _now();

  var delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);
  debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs);
  _realCallbackKey = global.setTimeout(_runCallbacks, delayMs);
}

function _runCallbacks() {
  var cb;

  var now = _now();

  debuglog("_runCallbacks: now:", now); // get the list of things to call

  var callbacksToRun = [];

  while (true) {
    var first = _callbackList[0];

    if (!first || first.runAt > now) {
      break;
    }

    cb = _callbackList.shift();
    debuglog("_runCallbacks: popping", cb.key);
    callbacksToRun.push(cb);
  } // reschedule the real callback before running our functions, to
  // keep the codepaths the same whether or not our functions
  // register their own setTimeouts.


  _scheduleRealCallback();

  for (var i = 0; i < callbacksToRun.length; i++) {
    cb = callbacksToRun[i];

    try {
      cb.func.apply(global, cb.params);
    } catch (e) {
      _logger.logger.error("Uncaught exception in callback function", e.stack || e);
    }
  }
}
/* search in a sorted array.
 *
 * returns the index of the last element for which func returns
 * greater than zero, or array.length if no such element exists.
 */


function binarySearch(array, func) {
  // min is inclusive, max exclusive.
  var min = 0;
  var max = array.length;

  while (min < max) {
    var mid = min + max >> 1;
    var res = func(array[mid]);

    if (res > 0) {
      // the element at 'mid' is too big; set it as the new max.
      max = mid;
    } else {
      // the element at 'mid' is too small. 'min' is inclusive, so +1.
      min = mid + 1;
    }
  } // presumably, min==max now.


  return min;
}

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./logger":106}],125:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MatrixScheduler = MatrixScheduler;

var utils = _interopRequireWildcard(require("./utils"));

var _logger = require("./logger");

/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/**
 * This is an internal module which manages queuing, scheduling and retrying
 * of requests.
 * @module scheduler
 */
var DEBUG = false; // set true to enable console logging.

/**
 * Construct a scheduler for Matrix. Requires
 * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided
 * with a way of processing events.
 * @constructor
 * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry
 * algorithm to apply when determining when to try to send an event again.
 * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.
 * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing
 * algorithm to apply when determining which events should be sent before the
 * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}.
 */

function MatrixScheduler(retryAlgorithm, queueAlgorithm) {
  this.retryAlgorithm = retryAlgorithm || MatrixScheduler.RETRY_BACKOFF_RATELIMIT;
  this.queueAlgorithm = queueAlgorithm || MatrixScheduler.QUEUE_MESSAGES;
  this._queues = {// queueName: [{
    //  event: MatrixEvent,  // event to send
    //  defer: Deferred,  // defer to resolve/reject at the END of the retries
    //  attempts: Number  // number of times we've called processFn
    // }, ...]
  };
  this._activeQueues = [];
  this._procFn = null;
}
/**
 * Retrieve a queue based on an event. The event provided does not need to be in
 * the queue.
 * @param {MatrixEvent} event An event to get the queue for.
 * @return {?Array<MatrixEvent>} A shallow copy of events in the queue or null.
 * Modifying this array will not modify the list itself. Modifying events in
 * this array <i>will</i> modify the underlying event in the queue.
 * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.
 */


MatrixScheduler.prototype.getQueueForEvent = function (event) {
  var name = this.queueAlgorithm(event);

  if (!name || !this._queues[name]) {
    return null;
  }

  return this._queues[name].map(function (obj) {
    return obj.event;
  });
};
/**
 * Remove this event from the queue. The event is equal to another event if they
 * have the same ID returned from event.getId().
 * @param {MatrixEvent} event The event to remove.
 * @return {boolean} True if this event was removed.
 */


MatrixScheduler.prototype.removeEventFromQueue = function (event) {
  var name = this.queueAlgorithm(event);

  if (!name || !this._queues[name]) {
    return false;
  }

  var removed = false;
  utils.removeElement(this._queues[name], function (element) {
    if (element.event.getId() === event.getId()) {
      // XXX we should probably reject the promise?
      // https://github.com/matrix-org/matrix-js-sdk/issues/496
      removed = true;
      return true;
    }
  });
  return removed;
};
/**
 * Set the process function. Required for events in the queue to be processed.
 * If set after events have been added to the queue, this will immediately start
 * processing them.
 * @param {module:scheduler~processFn} fn The function that can process events
 * in the queue.
 */


MatrixScheduler.prototype.setProcessFunction = function (fn) {
  this._procFn = fn;

  _startProcessingQueues(this);
};
/**
 * Queue an event if it is required and start processing queues.
 * @param {MatrixEvent} event The event that may be queued.
 * @return {?Promise} A promise if the event was queued, which will be
 * resolved or rejected in due time, else null.
 */


MatrixScheduler.prototype.queueEvent = function (event) {
  var queueName = this.queueAlgorithm(event);

  if (!queueName) {
    return null;
  } // add the event to the queue and make a deferred for it.


  if (!this._queues[queueName]) {
    this._queues[queueName] = [];
  }

  var defer = utils.defer();

  this._queues[queueName].push({
    event: event,
    defer: defer,
    attempts: 0
  });

  debuglog("Queue algorithm dumped event %s into queue '%s'", event.getId(), queueName);

  _startProcessingQueues(this);

  return defer.promise;
};
/**
 * Retries events up to 4 times using exponential backoff. This produces wait
 * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the
 * failure was due to a rate limited request, the time specified in the error is
 * waited before being retried.
 * @param {MatrixEvent} event
 * @param {Number} attempts
 * @param {MatrixError} err
 * @return {Number}
 * @see module:scheduler~retryAlgorithm
 */


MatrixScheduler.RETRY_BACKOFF_RATELIMIT = function (event, attempts, err) {
  if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) {
    // client error; no amount of retrying with save you now.
    return -1;
  } // we ship with browser-request which returns { cors: rejected } when trying
  // with no connection, so if we match that, give up since they have no conn.


  if (err.cors === "rejected") {
    return -1;
  } // if event that we are trying to send is too large in any way then retrying won't help


  if (err.name === "M_TOO_LARGE") {
    return -1;
  }

  if (err.name === "M_LIMIT_EXCEEDED") {
    var waitTime = err.data.retry_after_ms;

    if (waitTime > 0) {
      return waitTime;
    }
  }

  if (attempts > 4) {
    return -1; // give up
  }

  return 1000 * Math.pow(2, attempts);
};
/**
 * Queues <code>m.room.message</code> events and lets other events continue
 * concurrently.
 * @param {MatrixEvent} event
 * @return {string}
 * @see module:scheduler~queueAlgorithm
 */


MatrixScheduler.QUEUE_MESSAGES = function (event) {
  // enqueue messages or events that associate with another event (redactions and relations)
  if (event.getType() === "m.room.message" || event.hasAssocation()) {
    // put these events in the 'message' queue.
    return "message";
  } // allow all other events continue concurrently.


  return null;
};

function _startProcessingQueues(scheduler) {
  if (!scheduler._procFn) {
    return;
  } // for each inactive queue with events in them


  Object.keys(scheduler._queues).filter(function (queueName) {
    return scheduler._activeQueues.indexOf(queueName) === -1 && scheduler._queues[queueName].length > 0;
  }).forEach(function (queueName) {
    // mark the queue as active
    scheduler._activeQueues.push(queueName); // begin processing the head of the queue


    debuglog("Spinning up queue: '%s'", queueName);

    _processQueue(scheduler, queueName);
  });
}

function _processQueue(scheduler, queueName) {
  // get head of queue
  var obj = _peekNextEvent(scheduler, queueName);

  if (!obj) {
    // queue is empty. Mark as inactive and stop recursing.
    var index = scheduler._activeQueues.indexOf(queueName);

    if (index >= 0) {
      scheduler._activeQueues.splice(index, 1);
    }

    debuglog("Stopping queue '%s' as it is now empty", queueName);
    return;
  }

  debuglog("Queue '%s' has %s pending events", queueName, scheduler._queues[queueName].length); // fire the process function and if it resolves, resolve the deferred. Else
  // invoke the retry algorithm.
  // First wait for a resolved promise, so the resolve handlers for
  // the deferred of the previously sent event can run.
  // This way enqueued relations/redactions to enqueued events can receive
  // the remove id of their target before being sent.

  Promise.resolve().then(function () {
    return scheduler._procFn(obj.event);
  }).then(function (res) {
    // remove this from the queue
    _removeNextEvent(scheduler, queueName);

    debuglog("Queue '%s' sent event %s", queueName, obj.event.getId());
    obj.defer.resolve(res); // keep processing

    _processQueue(scheduler, queueName);
  }, function (err) {
    obj.attempts += 1; // ask the retry algorithm when/if we should try again

    var waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);
    debuglog("retry(%s) err=%s event_id=%s waitTime=%s", obj.attempts, err, obj.event.getId(), waitTimeMs);

    if (waitTimeMs === -1) {
      // give up (you quitter!)
      debuglog("Queue '%s' giving up on event %s", queueName, obj.event.getId()); // remove this from the queue

      _removeNextEvent(scheduler, queueName);

      obj.defer.reject(err); // process next event

      _processQueue(scheduler, queueName);
    } else {
      setTimeout(function () {
        _processQueue(scheduler, queueName);
      }, waitTimeMs);
    }
  });
}

function _peekNextEvent(scheduler, queueName) {
  var queue = scheduler._queues[queueName];

  if (!Array.isArray(queue)) {
    return null;
  }

  return queue[0];
}

function _removeNextEvent(scheduler, queueName) {
  var queue = scheduler._queues[queueName];

  if (!Array.isArray(queue)) {
    return null;
  }

  return queue.shift();
}

function debuglog() {
  if (DEBUG) {
    _logger.logger.log.apply(_logger.logger, arguments);
  }
}
/**
 * The retry algorithm to apply when retrying events. To stop retrying, return
 * <code>-1</code>. If this event was part of a queue, it will be removed from
 * the queue.
 * @callback retryAlgorithm
 * @param {MatrixEvent} event The event being retried.
 * @param {Number} attempts The number of failed attempts. This will always be
 * >= 1.
 * @param {MatrixError} err The most recent error message received when trying
 * to send this event.
 * @return {Number} The number of milliseconds to wait before trying again. If
 * this is 0, the request will be immediately retried. If this is
 * <code>-1</code>, the event will be marked as
 * {@link module:models/event.EventStatus.NOT_SENT} and will not be retried.
 */

/**
 * The queuing algorithm to apply to events. This function must be idempotent as
 * it may be called multiple times with the same event. All queues created are
 * serviced in a FIFO manner. To send the event ASAP, return <code>null</code>
 * which will not put this event in a queue. Events that fail to send that form
 * part of a queue will be removed from the queue and the next event in the
 * queue will be sent.
 * @callback queueAlgorithm
 * @param {MatrixEvent} event The event to be sent.
 * @return {string} The name of the queue to put the event into. If a queue with
 * this name does not exist, it will be created. If this is <code>null</code>,
 * the event is not put into a queue and will be sent concurrently.
 */

/**
* The function to invoke to process (send) events in the queue.
* @callback processFn
* @param {MatrixEvent} event The event to send.
* @return {Promise} Resolved/rejected depending on the outcome of the request.
*/

},{"./logger":106,"./utils":137,"@babel/runtime/helpers/interopRequireWildcard":13}],126:[function(require,module,exports){
"use strict";
/*
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SERVICE_TYPES = void 0;
var SERVICE_TYPES;
(function (SERVICE_TYPES) {
    SERVICE_TYPES["IS"] = "SERVICE_TYPE_IS";
    SERVICE_TYPES["IM"] = "SERVICE_TYPE_IM";
})(SERVICE_TYPES = exports.SERVICE_TYPES || (exports.SERVICE_TYPES = {}));

},{}],127:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LocalIndexedDBStoreBackend = LocalIndexedDBStoreBackend;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _syncAccumulator = require("../sync-accumulator");

var utils = _interopRequireWildcard(require("../utils"));

var IndexedDBHelpers = _interopRequireWildcard(require("../indexeddb-helpers"));

var _logger = require("../logger");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var VERSION = 3;

function createDatabase(db) {
  // Make user store, clobber based on user ID. (userId property of User objects)
  db.createObjectStore("users", {
    keyPath: ["userId"]
  }); // Make account data store, clobber based on event type.
  // (event.type property of MatrixEvent objects)

  db.createObjectStore("accountData", {
    keyPath: ["type"]
  }); // Make /sync store (sync tokens, room data, etc), always clobber (const key).

  db.createObjectStore("sync", {
    keyPath: ["clobber"]
  });
}

function upgradeSchemaV2(db) {
  var oobMembersStore = db.createObjectStore("oob_membership_events", {
    keyPath: ["room_id", "state_key"]
  });
  oobMembersStore.createIndex("room", "room_id");
}

function upgradeSchemaV3(db) {
  db.createObjectStore("client_options", {
    keyPath: ["clobber"]
  });
}
/**
 * Helper method to collect results from a Cursor and promiseify it.
 * @param {ObjectStore|Index} store The store to perform openCursor on.
 * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor.
 * @param {Function} resultMapper A function which is repeatedly called with a
 * Cursor.
 * Return the data you want to keep.
 * @return {Promise<T[]>} Resolves to an array of whatever you returned from
 * resultMapper.
 */


function selectQuery(store, keyRange, resultMapper) {
  var query = store.openCursor(keyRange);
  return new Promise(function (resolve, reject) {
    var results = [];

    query.onerror = function (event) {
      reject(new Error("Query failed: " + event.target.errorCode));
    }; // collect results


    query.onsuccess = function (event) {
      var cursor = event.target.result;

      if (!cursor) {
        resolve(results);
        return; // end of results
      }

      results.push(resultMapper(cursor));
      cursor["continue"]();
    };
  });
}

function txnAsPromise(txn) {
  return new Promise(function (resolve, reject) {
    txn.oncomplete = function (event) {
      resolve(event);
    };

    txn.onerror = function (event) {
      reject(event.target.error);
    };
  });
}

function reqAsEventPromise(req) {
  return new Promise(function (resolve, reject) {
    req.onsuccess = function (event) {
      resolve(event);
    };

    req.onerror = function (event) {
      reject(event.target.error);
    };
  });
}

function reqAsPromise(req) {
  return new Promise(function (resolve, reject) {
    req.onsuccess = function () {
      return resolve(req);
    };

    req.onerror = function (err) {
      return reject(err);
    };
  });
}

function reqAsCursorPromise(req) {
  return reqAsEventPromise(req).then(function (event) {
    return event.target.result;
  });
}
/**
 * Does the actual reading from and writing to the indexeddb
 *
 * Construct a new Indexed Database store backend. This requires a call to
 * <code>connect()</code> before this store can be used.
 * @constructor
 * @param {Object} indexedDBInterface The Indexed DB interface e.g
 * <code>window.indexedDB</code>
 * @param {string=} dbName Optional database name. The same name must be used
 * to open the same database.
 */


function LocalIndexedDBStoreBackend(indexedDBInterface, dbName) {
  this.indexedDB = indexedDBInterface;
  this._dbName = "matrix-js-sdk:" + (dbName || "default");
  this.db = null;
  this._disconnected = true;
  this._syncAccumulator = new _syncAccumulator.SyncAccumulator();
  this._isNewlyCreated = false;
}

LocalIndexedDBStoreBackend.exists = function (indexedDB, dbName) {
  dbName = "matrix-js-sdk:" + (dbName || "default");
  return IndexedDBHelpers.exists(indexedDB, dbName);
};

LocalIndexedDBStoreBackend.prototype = {
  /**
   * Attempt to connect to the database. This can fail if the user does not
   * grant permission.
   * @return {Promise} Resolves if successfully connected.
   */
  connect: function connect() {
    var _this = this;

    if (!this._disconnected) {
      _logger.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting");

      return Promise.resolve();
    }

    this._disconnected = false;

    _logger.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");

    var req = this.indexedDB.open(this._dbName, VERSION);

    req.onupgradeneeded = function (ev) {
      var db = ev.target.result;
      var oldVersion = ev.oldVersion;

      _logger.logger.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(oldVersion));

      if (oldVersion < 1) {
        // The database did not previously exist.
        _this._isNewlyCreated = true;
        createDatabase(db);
      }

      if (oldVersion < 2) {
        upgradeSchemaV2(db);
      }

      if (oldVersion < 3) {
        upgradeSchemaV3(db);
      } // Expand as needed.

    };

    req.onblocked = function () {
      _logger.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere");
    };

    _logger.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection...");

    return reqAsEventPromise(req).then(function (ev) {
      _logger.logger.log("LocalIndexedDBStoreBackend.connect: connected");

      _this.db = ev.target.result; // add a poorly-named listener for when deleteDatabase is called
      // so we can close our db connections.

      _this.db.onversionchange = function () {
        _this.db.close();
      };

      return _this._init();
    });
  },

  /** @return {bool} whether or not the database was newly created in this session. */
  isNewlyCreated: function isNewlyCreated() {
    return Promise.resolve(this._isNewlyCreated);
  },

  /**
   * Having connected, load initial data from the database and prepare for use
   * @return {Promise} Resolves on success
   */
  _init: function _init() {
    var _this2 = this;

    return Promise.all([this._loadAccountData(), this._loadSyncData()]).then(function (_ref) {
      var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
          accountData = _ref2[0],
          syncData = _ref2[1];

      _logger.logger.log("LocalIndexedDBStoreBackend: loaded initial data");

      _this2._syncAccumulator.accumulate({
        next_batch: syncData.nextBatch,
        rooms: syncData.roomsData,
        groups: syncData.groupsData,
        account_data: {
          events: accountData
        }
      }, true);
    });
  },

  /**
   * Returns the out-of-band membership events for this room that
   * were previously loaded.
   * @param {string} roomId
   * @returns {Promise<event[]>} the events, potentially an empty array if OOB loading didn't yield any new members
   * @returns {null} in case the members for this room haven't been stored yet
   */
  getOutOfBandMembers: function getOutOfBandMembers(roomId) {
    var _this3 = this;

    return new Promise(function (resolve, reject) {
      var tx = _this3.db.transaction(["oob_membership_events"], "readonly");

      var store = tx.objectStore("oob_membership_events");
      var roomIndex = store.index("room");
      var range = IDBKeyRange.only(roomId);
      var request = roomIndex.openCursor(range);
      var membershipEvents = []; // did we encounter the oob_written marker object
      // amongst the results? That means OOB member
      // loading already happened for this room
      // but there were no members to persist as they
      // were all known already

      var oobWritten = false;

      request.onsuccess = function (event) {
        var cursor = event.target.result;

        if (!cursor) {
          // Unknown room
          if (!membershipEvents.length && !oobWritten) {
            return resolve(null);
          }

          return resolve(membershipEvents);
        }

        var record = cursor.value;

        if (record.oob_written) {
          oobWritten = true;
        } else {
          membershipEvents.push(record);
        }

        cursor["continue"]();
      };

      request.onerror = function (err) {
        reject(err);
      };
    }).then(function (events) {
      _logger.logger.log("LL: got ".concat(events && events.length) + " membershipEvents from storage for room ".concat(roomId, " ..."));

      return events;
    });
  },

  /**
   * Stores the out-of-band membership events for this room. Note that
   * it still makes sense to store an empty array as the OOB status for the room is
   * marked as fetched, and getOutOfBandMembers will return an empty array instead of null
   * @param {string} roomId
   * @param {event[]} membershipEvents the membership events to store
   */
  setOutOfBandMembers: function () {
    var _setOutOfBandMembers = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(roomId, membershipEvents) {
      var tx, store, markerObject;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _logger.logger.log("LL: backend about to store ".concat(membershipEvents.length) + " members for ".concat(roomId));

              tx = this.db.transaction(["oob_membership_events"], "readwrite");
              store = tx.objectStore("oob_membership_events");
              membershipEvents.forEach(function (e) {
                store.put(e);
              }); // aside from all the events, we also write a marker object to the store
              // to mark the fact that OOB members have been written for this room.
              // It's possible that 0 members need to be written as all where previously know
              // but we still need to know whether to return null or [] from getOutOfBandMembers
              // where null means out of band members haven't been stored yet for this room

              markerObject = {
                room_id: roomId,
                oob_written: true,
                state_key: 0
              };
              store.put(markerObject);
              _context.next = 8;
              return txnAsPromise(tx);

            case 8:
              _logger.logger.log("LL: backend done storing for ".concat(roomId, "!"));

            case 9:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    function setOutOfBandMembers(_x, _x2) {
      return _setOutOfBandMembers.apply(this, arguments);
    }

    return setOutOfBandMembers;
  }(),
  clearOutOfBandMembers: function () {
    var _clearOutOfBandMembers = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(roomId) {
      var readTx, store, roomIndex, roomRange, minStateKeyProm, maxStateKeyProm, _yield$Promise$all, _yield$Promise$all2, minStateKey, maxStateKey, writeTx, writeStore, membersKeyRange;

      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              // the approach to delete all members for a room
              // is to get the min and max state key from the index
              // for that room, and then delete between those
              // keys in the store.
              // this should be way faster than deleting every member
              // individually for a large room.
              readTx = this.db.transaction(["oob_membership_events"], "readonly");
              store = readTx.objectStore("oob_membership_events");
              roomIndex = store.index("room");
              roomRange = IDBKeyRange.only(roomId);
              minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "next")).then(function (cursor) {
                return cursor && cursor.primaryKey[1];
              });
              maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "prev")).then(function (cursor) {
                return cursor && cursor.primaryKey[1];
              });
              _context2.next = 8;
              return Promise.all([minStateKeyProm, maxStateKeyProm]);

            case 8:
              _yield$Promise$all = _context2.sent;
              _yield$Promise$all2 = (0, _slicedToArray2["default"])(_yield$Promise$all, 2);
              minStateKey = _yield$Promise$all2[0];
              maxStateKey = _yield$Promise$all2[1];
              writeTx = this.db.transaction(["oob_membership_events"], "readwrite");
              writeStore = writeTx.objectStore("oob_membership_events");
              membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);

              _logger.logger.log("LL: Deleting all users + marker in storage for " + "room ".concat(roomId, ", with key range:"), [roomId, minStateKey], [roomId, maxStateKey]);

              _context2.next = 18;
              return reqAsPromise(writeStore["delete"](membersKeyRange));

            case 18:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, this);
    }));

    function clearOutOfBandMembers(_x3) {
      return _clearOutOfBandMembers.apply(this, arguments);
    }

    return clearOutOfBandMembers;
  }(),

  /**
   * Clear the entire database. This should be used when logging out of a client
   * to prevent mixing data between accounts.
   * @return {Promise} Resolved when the database is cleared.
   */
  clearDatabase: function clearDatabase() {
    var _this4 = this;

    return new Promise(function (resolve, reject) {
      _logger.logger.log("Removing indexeddb instance: ".concat(_this4._dbName));

      var req = _this4.indexedDB.deleteDatabase(_this4._dbName);

      req.onblocked = function () {
        _logger.logger.log("can't yet delete indexeddb ".concat(_this4._dbName) + " because it is open elsewhere");
      };

      req.onerror = function (ev) {
        // in firefox, with indexedDB disabled, this fails with a
        // DOMError. We treat this as non-fatal, so that we can still
        // use the app.
        _logger.logger.warn("unable to delete js-sdk store indexeddb: ".concat(ev.target.error));

        resolve();
      };

      req.onsuccess = function () {
        _logger.logger.log("Removed indexeddb instance: ".concat(_this4._dbName));

        resolve();
      };
    });
  },

  /**
   * @param {boolean=} copy If false, the data returned is from internal
   * buffers and must not be mutated. Otherwise, a copy is made before
   * returning such that the data can be safely mutated. Default: true.
   *
   * @return {Promise} Resolves with a sync response to restore the
   * client state to where it was at the last save, or null if there
   * is no saved sync data.
   */
  getSavedSync: function getSavedSync(copy) {
    if (copy === undefined) copy = true;

    var data = this._syncAccumulator.getJSON();

    if (!data.nextBatch) return Promise.resolve(null);

    if (copy) {
      // We must deep copy the stored data so that the /sync processing code doesn't
      // corrupt the internal state of the sync accumulator (it adds non-clonable keys)
      return Promise.resolve(utils.deepCopy(data));
    } else {
      return Promise.resolve(data);
    }
  },
  getNextBatchToken: function getNextBatchToken() {
    return Promise.resolve(this._syncAccumulator.getNextBatchToken());
  },
  setSyncData: function setSyncData(syncData) {
    var _this5 = this;

    return Promise.resolve().then(function () {
      _this5._syncAccumulator.accumulate(syncData);
    });
  },
  syncToDatabase: function syncToDatabase(userTuples) {
    var syncData = this._syncAccumulator.getJSON(true);

    return Promise.all([this._persistUserPresenceEvents(userTuples), this._persistAccountData(syncData.accountData), this._persistSyncData(syncData.nextBatch, syncData.roomsData, syncData.groupsData)]);
  },

  /**
   * Persist rooms /sync data along with the next batch token.
   * @param {string} nextBatch The next_batch /sync value.
   * @param {Object} roomsData The 'rooms' /sync data from a SyncAccumulator
   * @param {Object} groupsData The 'groups' /sync data from a SyncAccumulator
   * @return {Promise} Resolves if the data was persisted.
   */
  _persistSyncData: function _persistSyncData(nextBatch, roomsData, groupsData) {
    var _this6 = this;

    _logger.logger.log("Persisting sync data up to", nextBatch);

    return utils.promiseTry(function () {
      var txn = _this6.db.transaction(["sync"], "readwrite");

      var store = txn.objectStore("sync");
      store.put({
        clobber: "-",
        // constant key so will always clobber
        nextBatch: nextBatch,
        roomsData: roomsData,
        groupsData: groupsData
      }); // put == UPSERT

      return txnAsPromise(txn);
    });
  },

  /**
   * Persist a list of account data events. Events with the same 'type' will
   * be replaced.
   * @param {Object[]} accountData An array of raw user-scoped account data events
   * @return {Promise} Resolves if the events were persisted.
   */
  _persistAccountData: function _persistAccountData(accountData) {
    var _this7 = this;

    return utils.promiseTry(function () {
      var txn = _this7.db.transaction(["accountData"], "readwrite");

      var store = txn.objectStore("accountData");

      for (var i = 0; i < accountData.length; i++) {
        store.put(accountData[i]); // put == UPSERT
      }

      return txnAsPromise(txn);
    });
  },

  /**
   * Persist a list of [user id, presence event] they are for.
   * Users with the same 'userId' will be replaced.
   * Presence events should be the event in its raw form (not the Event
   * object)
   * @param {Object[]} tuples An array of [userid, event] tuples
   * @return {Promise} Resolves if the users were persisted.
   */
  _persistUserPresenceEvents: function _persistUserPresenceEvents(tuples) {
    var _this8 = this;

    return utils.promiseTry(function () {
      var txn = _this8.db.transaction(["users"], "readwrite");

      var store = txn.objectStore("users");

      var _iterator = _createForOfIteratorHelper(tuples),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var tuple = _step.value;
          store.put({
            userId: tuple[0],
            event: tuple[1]
          }); // put == UPSERT
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return txnAsPromise(txn);
    });
  },

  /**
   * Load all user presence events from the database. This is not cached.
   * FIXME: It would probably be more sensible to store the events in the
   * sync.
   * @return {Promise<Object[]>} A list of presence events in their raw form.
   */
  getUserPresenceEvents: function getUserPresenceEvents() {
    var _this9 = this;

    return utils.promiseTry(function () {
      var txn = _this9.db.transaction(["users"], "readonly");

      var store = txn.objectStore("users");
      return selectQuery(store, undefined, function (cursor) {
        return [cursor.value.userId, cursor.value.event];
      });
    });
  },

  /**
   * Load all the account data events from the database. This is not cached.
   * @return {Promise<Object[]>} A list of raw global account events.
   */
  _loadAccountData: function _loadAccountData() {
    var _this10 = this;

    _logger.logger.log("LocalIndexedDBStoreBackend: loading account data...");

    return utils.promiseTry(function () {
      var txn = _this10.db.transaction(["accountData"], "readonly");

      var store = txn.objectStore("accountData");
      return selectQuery(store, undefined, function (cursor) {
        return cursor.value;
      }).then(function (result) {
        _logger.logger.log("LocalIndexedDBStoreBackend: loaded account data");

        return result;
      });
    });
  },

  /**
   * Load the sync data from the database.
   * @return {Promise<Object>} An object with "roomsData" and "nextBatch" keys.
   */
  _loadSyncData: function _loadSyncData() {
    var _this11 = this;

    _logger.logger.log("LocalIndexedDBStoreBackend: loading sync data...");

    return utils.promiseTry(function () {
      var txn = _this11.db.transaction(["sync"], "readonly");

      var store = txn.objectStore("sync");
      return selectQuery(store, undefined, function (cursor) {
        return cursor.value;
      }).then(function (results) {
        _logger.logger.log("LocalIndexedDBStoreBackend: loaded sync data");

        if (results.length > 1) {
          _logger.logger.warn("loadSyncData: More than 1 sync row found.");
        }

        return results.length > 0 ? results[0] : {};
      });
    });
  },
  getClientOptions: function getClientOptions() {
    var _this12 = this;

    return Promise.resolve().then(function () {
      var txn = _this12.db.transaction(["client_options"], "readonly");

      var store = txn.objectStore("client_options");
      return selectQuery(store, undefined, function (cursor) {
        if (cursor.value && cursor.value && cursor.value.options) {
          return cursor.value.options;
        }
      }).then(function (results) {
        return results[0];
      });
    });
  },
  storeClientOptions: function () {
    var _storeClientOptions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(options) {
      var txn, store;
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              txn = this.db.transaction(["client_options"], "readwrite");
              store = txn.objectStore("client_options");
              store.put({
                clobber: "-",
                // constant key so will always clobber
                options: options
              }); // put == UPSERT

              _context3.next = 5;
              return txnAsPromise(txn);

            case 5:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, this);
    }));

    function storeClientOptions(_x4) {
      return _storeClientOptions.apply(this, arguments);
    }

    return storeClientOptions;
  }()
};

},{"../indexeddb-helpers":104,"../logger":106,"../sync-accumulator":133,"../utils":137,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],128:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RemoteIndexedDBStoreBackend = RemoteIndexedDBStoreBackend;

var _logger = require("../logger");

var _utils = require("../utils");

/*
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

/**
 * An IndexedDB store backend where the actual backend sits in a web
 * worker.
 *
 * Construct a new Indexed Database store backend. This requires a call to
 * <code>connect()</code> before this store can be used.
 * @constructor
 * @param {string} workerScript URL to the worker script
 * @param {string=} dbName Optional database name. The same name must be used
 * to open the same database.
 * @param {Object} workerApi The web worker compatible interface object
 */
function RemoteIndexedDBStoreBackend(workerScript, dbName, workerApi) {
  this._workerScript = workerScript;
  this._dbName = dbName;
  this._workerApi = workerApi;
  this._worker = null;
  this._nextSeq = 0; // The currently in-flight requests to the actual backend

  this._inFlight = {// seq: promise,
  }; // Once we start connecting, we keep the promise and re-use it
  // if we try to connect again

  this._startPromise = null;
}

RemoteIndexedDBStoreBackend.prototype = {
  /**
   * Attempt to connect to the database. This can fail if the user does not
   * grant permission.
   * @return {Promise} Resolves if successfully connected.
   */
  connect: function connect() {
    var _this = this;

    return this._ensureStarted().then(function () {
      return _this._doCmd('connect');
    });
  },

  /**
   * Clear the entire database. This should be used when logging out of a client
   * to prevent mixing data between accounts.
   * @return {Promise} Resolved when the database is cleared.
   */
  clearDatabase: function clearDatabase() {
    var _this2 = this;

    return this._ensureStarted().then(function () {
      return _this2._doCmd('clearDatabase');
    });
  },

  /** @return {Promise<bool>} whether or not the database was newly created in this session. */
  isNewlyCreated: function isNewlyCreated() {
    return this._doCmd('isNewlyCreated');
  },

  /**
   * @return {Promise} Resolves with a sync response to restore the
   * client state to where it was at the last save, or null if there
   * is no saved sync data.
   */
  getSavedSync: function getSavedSync() {
    return this._doCmd('getSavedSync');
  },
  getNextBatchToken: function getNextBatchToken() {
    return this._doCmd('getNextBatchToken');
  },
  setSyncData: function setSyncData(syncData) {
    return this._doCmd('setSyncData', [syncData]);
  },
  syncToDatabase: function syncToDatabase(users) {
    return this._doCmd('syncToDatabase', [users]);
  },

  /**
   * Returns the out-of-band membership events for this room that
   * were previously loaded.
   * @param {string} roomId
   * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members
   * @returns {null} in case the members for this room haven't been stored yet
   */
  getOutOfBandMembers: function getOutOfBandMembers(roomId) {
    return this._doCmd('getOutOfBandMembers', [roomId]);
  },

  /**
   * Stores the out-of-band membership events for this room. Note that
   * it still makes sense to store an empty array as the OOB status for the room is
   * marked as fetched, and getOutOfBandMembers will return an empty array instead of null
   * @param {string} roomId
   * @param {event[]} membershipEvents the membership events to store
   * @returns {Promise} when all members have been stored
   */
  setOutOfBandMembers: function setOutOfBandMembers(roomId, membershipEvents) {
    return this._doCmd('setOutOfBandMembers', [roomId, membershipEvents]);
  },
  clearOutOfBandMembers: function clearOutOfBandMembers(roomId) {
    return this._doCmd('clearOutOfBandMembers', [roomId]);
  },
  getClientOptions: function getClientOptions() {
    return this._doCmd('getClientOptions');
  },
  storeClientOptions: function storeClientOptions(options) {
    return this._doCmd('storeClientOptions', [options]);
  },

  /**
   * Load all user presence events from the database. This is not cached.
   * @return {Promise<Object[]>} A list of presence events in their raw form.
   */
  getUserPresenceEvents: function getUserPresenceEvents() {
    return this._doCmd('getUserPresenceEvents');
  },
  _ensureStarted: function _ensureStarted() {
    if (this._startPromise === null) {
      this._worker = new this._workerApi(this._workerScript);
      this._worker.onmessage = this._onWorkerMessage.bind(this); // tell the worker the db name.

      this._startPromise = this._doCmd('_setupWorker', [this._dbName]).then(function () {
        _logger.logger.log("IndexedDB worker is ready");
      });
    }

    return this._startPromise;
  },
  _doCmd: function _doCmd(cmd, args) {
    var _this3 = this;

    // wrap in a q so if the postMessage throws,
    // the promise automatically gets rejected
    return Promise.resolve().then(function () {
      var seq = _this3._nextSeq++;
      var def = (0, _utils.defer)();
      _this3._inFlight[seq] = def;

      _this3._worker.postMessage({
        command: cmd,
        seq: seq,
        args: args
      });

      return def.promise;
    });
  },
  _onWorkerMessage: function _onWorkerMessage(ev) {
    var msg = ev.data;

    if (msg.command == 'cmd_success' || msg.command == 'cmd_fail') {
      if (msg.seq === undefined) {
        _logger.logger.error("Got reply from worker with no seq");

        return;
      }

      var def = this._inFlight[msg.seq];

      if (def === undefined) {
        _logger.logger.error("Got reply for unknown seq " + msg.seq);

        return;
      }

      delete this._inFlight[msg.seq];

      if (msg.command == 'cmd_success') {
        def.resolve(msg.result);
      } else {
        var error = new Error(msg.error.message);
        error.name = msg.error.name;
        def.reject(error);
      }
    } else {
      _logger.logger.warn("Unrecognised message from worker: " + msg);
    }
  }
};

},{"../logger":106,"../utils":137}],129:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2017 - 2021 Vector Creations Ltd

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndexedDBStore = void 0;
/* eslint-disable @babel/no-invalid-this */
const events_1 = require("events");
const memory_1 = require("./memory");
const indexeddb_local_backend_js_1 = require("./indexeddb-local-backend.js");
const indexeddb_remote_backend_js_1 = require("./indexeddb-remote-backend.js");
const user_1 = require("../models/user");
const event_1 = require("../models/event");
const logger_1 = require("../logger");
/**
 * This is an internal module. See {@link IndexedDBStore} for the public class.
 * @module store/indexeddb
 */
// If this value is too small we'll be writing very often which will cause
// noticeable stop-the-world pauses. If this value is too big we'll be writing
// so infrequently that the /sync size gets bigger on reload. Writing more
// often does not affect the length of the pause since the entire /sync
// response is persisted each time.
const WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes
class IndexedDBStore extends memory_1.MemoryStore {
    /**
     * Construct a new Indexed Database store, which extends MemoryStore.
     *
     * This store functions like a MemoryStore except it periodically persists
     * the contents of the store to an IndexedDB backend.
     *
     * All data is still kept in-memory but can be loaded from disk by calling
     * <code>startup()</code>. This can make startup times quicker as a complete
     * sync from the server is not required. This does not reduce memory usage as all
     * the data is eagerly fetched when <code>startup()</code> is called.
     * <pre>
     * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };
     * let store = new IndexedDBStore(opts);
     * await store.startup(); // load from indexed db
     * let client = sdk.createClient({
     *     store: store,
     * });
     * client.startClient();
     * client.on("sync", function(state, prevState, data) {
     *     if (state === "PREPARED") {
     *         console.log("Started up, now with go faster stripes!");
     *     }
     * });
     * </pre>
     *
     * @constructor
     * @extends MemoryStore
     * @param {Object} opts Options object.
     * @param {Object} opts.indexedDB The Indexed DB interface e.g.
     * <code>window.indexedDB</code>
     * @param {string=} opts.dbName Optional database name. The same name must be used
     * to open the same database.
     * @param {string=} opts.workerScript Optional URL to a script to invoke a web
     * worker with to run IndexedDB queries on the web worker. The IndexedDbStoreWorker
     * class is provided for this purpose and requires the application to provide a
     * trivial wrapper script around it.
     * @param {Object=} opts.workerApi The webWorker API object. If omitted, the global Worker
     * object will be used if it exists.
     * @prop {IndexedDBStoreBackend} backend The backend instance. Call through to
     * this API if you need to perform specific indexeddb actions like deleting the
     * database.
     */
    constructor(opts) {
        super(opts);
        this.startedUp = false;
        this.syncTs = 0;
        // Records the last-modified-time of each user at the last point we saved
        // the database, such that we can derive the set if users that have been
        // modified since we last saved.
        this.userModifiedMap = {}; // user_id : timestamp
        this.emitter = new events_1.EventEmitter();
        this.on = this.emitter.on.bind(this.emitter);
        /**
         * @return {Promise} Resolves with a sync response to restore the
         * client state to where it was at the last save, or null if there
         * is no saved sync data.
         */
        this.getSavedSync = this.degradable(() => {
            return this.backend.getSavedSync();
        }, "getSavedSync");
        /** @return {Promise<boolean>} whether or not the database was newly created in this session. */
        this.isNewlyCreated = this.degradable(() => {
            return this.backend.isNewlyCreated();
        }, "isNewlyCreated");
        /**
         * @return {Promise} If there is a saved sync, the nextBatch token
         * for this sync, otherwise null.
         */
        this.getSavedSyncToken = this.degradable(() => {
            return this.backend.getNextBatchToken();
        }, "getSavedSyncToken");
        /**
         * Delete all data from this store.
         * @return {Promise} Resolves if the data was deleted from the database.
         */
        this.deleteAllData = this.degradable(() => {
            super.deleteAllData();
            return this.backend.clearDatabase().then(() => {
                logger_1.logger.log("Deleted indexeddb data.");
            }, (err) => {
                logger_1.logger.error(`Failed to delete indexeddb data: ${err}`);
                throw err;
            });
        });
        this.reallySave = this.degradable(() => {
            this.syncTs = Date.now(); // set now to guard against multi-writes
            // work out changed users (this doesn't handle deletions but you
            // can't 'delete' users as they are just presence events).
            const userTuples = [];
            for (const u of this.getUsers()) {
                if (this.userModifiedMap[u.userId] === u.getLastModifiedTime())
                    continue;
                if (!u.events.presence)
                    continue;
                userTuples.push([u.userId, u.events.presence.event]);
                // note that we've saved this version of the user
                this.userModifiedMap[u.userId] = u.getLastModifiedTime();
            }
            return this.backend.syncToDatabase(userTuples);
        });
        this.setSyncData = this.degradable((syncData) => {
            return this.backend.setSyncData(syncData);
        }, "setSyncData");
        /**
         * Returns the out-of-band membership events for this room that
         * were previously loaded.
         * @param {string} roomId
         * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members
         * @returns {null} in case the members for this room haven't been stored yet
         */
        this.getOutOfBandMembers = this.degradable((roomId) => {
            return this.backend.getOutOfBandMembers(roomId);
        }, "getOutOfBandMembers");
        /**
         * Stores the out-of-band membership events for this room. Note that
         * it still makes sense to store an empty array as the OOB status for the room is
         * marked as fetched, and getOutOfBandMembers will return an empty array instead of null
         * @param {string} roomId
         * @param {event[]} membershipEvents the membership events to store
         * @returns {Promise} when all members have been stored
         */
        this.setOutOfBandMembers = this.degradable((roomId, membershipEvents) => {
            super.setOutOfBandMembers(roomId, membershipEvents);
            return this.backend.setOutOfBandMembers(roomId, membershipEvents);
        }, "setOutOfBandMembers");
        this.clearOutOfBandMembers = this.degradable((roomId) => {
            super.clearOutOfBandMembers(roomId);
            return this.backend.clearOutOfBandMembers(roomId);
        }, "clearOutOfBandMembers");
        this.getClientOptions = this.degradable(() => {
            return this.backend.getClientOptions();
        }, "getClientOptions");
        this.storeClientOptions = this.degradable((options) => {
            super.storeClientOptions(options);
            return this.backend.storeClientOptions(options);
        }, "storeClientOptions");
        if (!opts.indexedDB) {
            throw new Error('Missing required option: indexedDB');
        }
        if (opts.workerScript) {
            // try & find a webworker-compatible API
            let workerApi = opts.workerApi;
            if (!workerApi) {
                // default to the global Worker object (which is where it in a browser)
                workerApi = global.Worker;
            }
            this.backend = new indexeddb_remote_backend_js_1.RemoteIndexedDBStoreBackend(opts.workerScript, opts.dbName, workerApi);
        }
        else {
            this.backend = new indexeddb_local_backend_js_1.LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);
        }
    }
    static exists(indexedDB, dbName) {
        return indexeddb_local_backend_js_1.LocalIndexedDBStoreBackend.exists(indexedDB, dbName);
    }
    /**
     * @return {Promise} Resolved when loaded from indexed db.
     */
    startup() {
        if (this.startedUp) {
            logger_1.logger.log(`IndexedDBStore.startup: already started`);
            return Promise.resolve();
        }
        logger_1.logger.log(`IndexedDBStore.startup: connecting to backend`);
        return this.backend.connect().then(() => {
            logger_1.logger.log(`IndexedDBStore.startup: loading presence events`);
            return this.backend.getUserPresenceEvents();
        }).then((userPresenceEvents) => {
            logger_1.logger.log(`IndexedDBStore.startup: processing presence events`);
            userPresenceEvents.forEach(([userId, rawEvent]) => {
                const u = new user_1.User(userId);
                if (rawEvent) {
                    u.setPresenceEvent(new event_1.MatrixEvent(rawEvent));
                }
                this.userModifiedMap[u.userId] = u.getLastModifiedTime();
                this.storeUser(u);
            });
        });
    }
    /**
     * Whether this store would like to save its data
     * Note that obviously whether the store wants to save or
     * not could change between calling this function and calling
     * save().
     *
     * @return {boolean} True if calling save() will actually save
     *     (at the time this function is called).
     */
    wantsSave() {
        const now = Date.now();
        return now - this.syncTs > WRITE_DELAY_MS;
    }
    /**
     * Possibly write data to the database.
     *
     * @param {boolean} force True to force a save to happen
     * @return {Promise} Promise resolves after the write completes
     *     (or immediately if no write is performed)
     */
    save(force = false) {
        if (force || this.wantsSave()) {
            return this.reallySave();
        }
        return Promise.resolve();
    }
    /**
     * All member functions of `IndexedDBStore` that access the backend use this wrapper to
     * watch for failures after initial store startup, including `QuotaExceededError` as
     * free disk space changes, etc.
     *
     * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`
     * in place so that the current operation and all future ones are in-memory only.
     *
     * @param {Function} func The degradable work to do.
     * @param {String} fallback The method name for fallback.
     * @returns {Function} A wrapped member function.
     */
    degradable(func, fallback) {
        const fallbackFn = super[fallback];
        return (...args) => __awaiter(this, void 0, void 0, function* () {
            try {
                return func.call(this, ...args);
            }
            catch (e) {
                logger_1.logger.error("IndexedDBStore failure, degrading to MemoryStore", e);
                this.emitter.emit("degraded", e);
                try {
                    // We try to delete IndexedDB after degrading since this store is only a
                    // cache (the app will still function correctly without the data).
                    // It's possible that deleting repair IndexedDB for the next app load,
                    // potentially by making a little more space available.
                    logger_1.logger.log("IndexedDBStore trying to delete degraded data");
                    yield this.backend.clearDatabase();
                    logger_1.logger.log("IndexedDBStore delete after degrading succeeded");
                }
                catch (e) {
                    logger_1.logger.warn("IndexedDBStore delete after degrading failed", e);
                }
                // Degrade the store from being an instance of `IndexedDBStore` to instead be
                // an instance of `MemoryStore` so that future API calls use the memory path
                // directly and skip IndexedDB entirely. This should be safe as
                // `IndexedDBStore` already extends from `MemoryStore`, so we are making the
                // store become its parent type in a way. The mutator methods of
                // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are
                // not overridden at all).
                if (fallbackFn) {
                    return fallbackFn(...args);
                }
            }
        });
    }
}
exports.IndexedDBStore = IndexedDBStore;

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"../logger":106,"../models/event":113,"../models/user":121,"./indexeddb-local-backend.js":127,"./indexeddb-remote-backend.js":128,"./memory":130,"events":36}],130:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryStore = void 0;
const user_1 = require("../models/user");
function isValidFilterId(filterId) {
    const isValidStr = typeof filterId === "string" &&
        !!filterId &&
        filterId !== "undefined" && // exclude these as we've serialized undefined in localStorage before
        filterId !== "null";
    return isValidStr || typeof filterId === "number";
}
/**
 * Construct a new in-memory data store for the Matrix Client.
 * @constructor
 * @param {Object=} opts Config options
 * @param {LocalStorage} opts.localStorage The local storage instance to persist
 * some forms of data such as tokens. Rooms will NOT be stored.
 */
class MemoryStore {
    constructor(opts = {}) {
        this.rooms = {}; // roomId: Room
        this.groups = {}; // groupId: Group
        this.users = {}; // userId: User
        this.syncToken = null;
        // userId: {
        //    filterId: Filter
        // }
        this.filters = {};
        this.accountData = {}; // type : content
        this.oobMembers = {}; // roomId: [member events]
        this.clientOptions = {};
        /**
         * Called when a room member in a room being tracked by this store has been
         * updated.
         * @param {MatrixEvent} event
         * @param {RoomState} state
         * @param {RoomMember} member
         */
        this.onRoomMember = (event, state, member) => {
            if (member.membership === "invite") {
                // We do NOT add invited members because people love to typo user IDs
                // which would then show up in these lists (!)
                return;
            }
            const user = this.users[member.userId] || new user_1.User(member.userId);
            if (member.name) {
                user.setDisplayName(member.name);
                if (member.events.member) {
                    user.setRawDisplayName(member.events.member.getDirectionalContent().displayname);
                }
            }
            if (member.events.member && member.events.member.getContent().avatar_url) {
                user.setAvatarUrl(member.events.member.getContent().avatar_url);
            }
            this.users[user.userId] = user;
        };
        this.localStorage = opts.localStorage;
    }
    /**
     * Retrieve the token to stream from.
     * @return {string} The token or null.
     */
    getSyncToken() {
        return this.syncToken;
    }
    /** @return {Promise<boolean>} whether or not the database was newly created in this session. */
    isNewlyCreated() {
        return Promise.resolve(true);
    }
    /**
     * Set the token to stream from.
     * @param {string} token The token to stream from.
     */
    setSyncToken(token) {
        this.syncToken = token;
    }
    /**
     * Store the given room.
     * @param {Group} group The group to be stored
     */
    storeGroup(group) {
        this.groups[group.groupId] = group;
    }
    /**
     * Retrieve a group by its group ID.
     * @param {string} groupId The group ID.
     * @return {Group} The group or null.
     */
    getGroup(groupId) {
        return this.groups[groupId] || null;
    }
    /**
     * Retrieve all known groups.
     * @return {Group[]} A list of groups, which may be empty.
     */
    getGroups() {
        return Object.values(this.groups);
    }
    /**
     * Store the given room.
     * @param {Room} room The room to be stored. All properties must be stored.
     */
    storeRoom(room) {
        this.rooms[room.roomId] = room;
        // add listeners for room member changes so we can keep the room member
        // map up-to-date.
        room.currentState.on("RoomState.members", this.onRoomMember);
        // add existing members
        room.currentState.getMembers().forEach((m) => {
            this.onRoomMember(null, room.currentState, m);
        });
    }
    /**
     * Retrieve a room by its' room ID.
     * @param {string} roomId The room ID.
     * @return {Room} The room or null.
     */
    getRoom(roomId) {
        return this.rooms[roomId] || null;
    }
    /**
     * Retrieve all known rooms.
     * @return {Room[]} A list of rooms, which may be empty.
     */
    getRooms() {
        return Object.values(this.rooms);
    }
    /**
     * Permanently delete a room.
     * @param {string} roomId
     */
    removeRoom(roomId) {
        if (this.rooms[roomId]) {
            this.rooms[roomId].removeListener("RoomState.members", this.onRoomMember);
        }
        delete this.rooms[roomId];
    }
    /**
     * Retrieve a summary of all the rooms.
     * @return {RoomSummary[]} A summary of each room.
     */
    getRoomSummaries() {
        return Object.values(this.rooms).map(function (room) {
            return room.summary;
        });
    }
    /**
     * Store a User.
     * @param {User} user The user to store.
     */
    storeUser(user) {
        this.users[user.userId] = user;
    }
    /**
     * Retrieve a User by its' user ID.
     * @param {string} userId The user ID.
     * @return {User} The user or null.
     */
    getUser(userId) {
        return this.users[userId] || null;
    }
    /**
     * Retrieve all known users.
     * @return {User[]} A list of users, which may be empty.
     */
    getUsers() {
        return Object.values(this.users);
    }
    /**
     * Retrieve scrollback for this room.
     * @param {Room} room The matrix room
     * @param {integer} limit The max number of old events to retrieve.
     * @return {Array<Object>} An array of objects which will be at most 'limit'
     * length and at least 0. The objects are the raw event JSON.
     */
    scrollback(room, limit) {
        return [];
    }
    /**
     * Store events for a room. The events have already been added to the timeline
     * @param {Room} room The room to store events for.
     * @param {Array<MatrixEvent>} events The events to store.
     * @param {string} token The token associated with these events.
     * @param {boolean} toStart True if these are paginated results.
     */
    storeEvents(room, events, token, toStart) {
        // no-op because they've already been added to the room instance.
    }
    /**
     * Store a filter.
     * @param {Filter} filter
     */
    storeFilter(filter) {
        if (!filter) {
            return;
        }
        if (!this.filters[filter.userId]) {
            this.filters[filter.userId] = {};
        }
        this.filters[filter.userId][filter.filterId] = filter;
    }
    /**
     * Retrieve a filter.
     * @param {string} userId
     * @param {string} filterId
     * @return {?Filter} A filter or null.
     */
    getFilter(userId, filterId) {
        if (!this.filters[userId] || !this.filters[userId][filterId]) {
            return null;
        }
        return this.filters[userId][filterId];
    }
    /**
     * Retrieve a filter ID with the given name.
     * @param {string} filterName The filter name.
     * @return {?string} The filter ID or null.
     */
    getFilterIdByName(filterName) {
        if (!this.localStorage) {
            return null;
        }
        const key = "mxjssdk_memory_filter_" + filterName;
        // XXX Storage.getItem doesn't throw ...
        // or are we using something different
        // than window.localStorage in some cases
        // that does throw?
        // that would be very naughty
        try {
            const value = this.localStorage.getItem(key);
            if (isValidFilterId(value)) {
                return value;
            }
        }
        catch (e) { }
        return null;
    }
    /**
     * Set a filter name to ID mapping.
     * @param {string} filterName
     * @param {string} filterId
     */
    setFilterIdByName(filterName, filterId) {
        if (!this.localStorage) {
            return;
        }
        const key = "mxjssdk_memory_filter_" + filterName;
        try {
            if (isValidFilterId(filterId)) {
                this.localStorage.setItem(key, filterId);
            }
            else {
                this.localStorage.removeItem(key);
            }
        }
        catch (e) { }
    }
    /**
     * Store user-scoped account data events.
     * N.B. that account data only allows a single event per type, so multiple
     * events with the same type will replace each other.
     * @param {Array<MatrixEvent>} events The events to store.
     */
    storeAccountDataEvents(events) {
        events.forEach((event) => {
            this.accountData[event.getType()] = event;
        });
    }
    /**
     * Get account data event by event type
     * @param {string} eventType The event type being queried
     * @return {?MatrixEvent} the user account_data event of given type, if any
     */
    getAccountData(eventType) {
        return this.accountData[eventType];
    }
    /**
     * setSyncData does nothing as there is no backing data store.
     *
     * @param {Object} syncData The sync data
     * @return {Promise} An immediately resolved promise.
     */
    setSyncData(syncData) {
        return Promise.resolve();
    }
    /**
     * We never want to save becase we have nothing to save to.
     *
     * @return {boolean} If the store wants to save
     */
    wantsSave() {
        return false;
    }
    /**
     * Save does nothing as there is no backing data store.
     * @param {bool} force True to force a save (but the memory
     *     store still can't save anything)
     */
    save(force) { }
    /**
     * Startup does nothing as this store doesn't require starting up.
     * @return {Promise} An immediately resolved promise.
     */
    startup() {
        return Promise.resolve();
    }
    /**
     * @return {Promise} Resolves with a sync response to restore the
     * client state to where it was at the last save, or null if there
     * is no saved sync data.
     */
    getSavedSync() {
        return Promise.resolve(null);
    }
    /**
     * @return {Promise} If there is a saved sync, the nextBatch token
     * for this sync, otherwise null.
     */
    getSavedSyncToken() {
        return Promise.resolve(null);
    }
    /**
     * Delete all data from this store.
     * @return {Promise} An immediately resolved promise.
     */
    deleteAllData() {
        this.rooms = {
        // roomId: Room
        };
        this.users = {
        // userId: User
        };
        this.syncToken = null;
        this.filters = {
        // userId: {
        //    filterId: Filter
        // }
        };
        this.accountData = {
        // type : content
        };
        return Promise.resolve();
    }
    /**
     * Returns the out-of-band membership events for this room that
     * were previously loaded.
     * @param {string} roomId
     * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members
     * @returns {null} in case the members for this room haven't been stored yet
     */
    getOutOfBandMembers(roomId) {
        return Promise.resolve(this.oobMembers[roomId] || null);
    }
    /**
     * Stores the out-of-band membership events for this room. Note that
     * it still makes sense to store an empty array as the OOB status for the room is
     * marked as fetched, and getOutOfBandMembers will return an empty array instead of null
     * @param {string} roomId
     * @param {event[]} membershipEvents the membership events to store
     * @returns {Promise} when all members have been stored
     */
    setOutOfBandMembers(roomId, membershipEvents) {
        this.oobMembers[roomId] = membershipEvents;
        return Promise.resolve();
    }
    clearOutOfBandMembers(roomId) {
        this.oobMembers = {};
        return Promise.resolve();
    }
    getClientOptions() {
        return Promise.resolve(this.clientOptions);
    }
    storeClientOptions(options) {
        this.clientOptions = Object.assign({}, options);
        return Promise.resolve();
    }
}
exports.MemoryStore = MemoryStore;

},{"../models/user":121}],131:[function(require,module,exports){
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.WebStorageSessionStore = WebStorageSessionStore;

var utils = _interopRequireWildcard(require("../../utils"));

var _logger = require("../../logger");

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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; } } }; }

function _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); }

function _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; }

var DEBUG = false; // set true to enable console logging.

var E2E_PREFIX = "session.e2e.";
/**
 * Construct a web storage session store, capable of storing account keys,
 * session keys and access tokens.
 * @constructor
 * @param {WebStorage} webStore A web storage implementation, e.g.
 * 'window.localStorage' or 'window.sessionStorage' or a custom implementation.
 * @throws if the supplied 'store' does not meet the Storage interface of the
 * WebStorage API.
 */

function WebStorageSessionStore(webStore) {
  this.store = webStore;

  if (!utils.isFunction(webStore.getItem) || !utils.isFunction(webStore.setItem) || !utils.isFunction(webStore.removeItem) || !utils.isFunction(webStore.key) || typeof webStore.length !== 'number') {
    throw new Error("Supplied webStore does not meet the WebStorage API interface");
  }
}

WebStorageSessionStore.prototype = {
  /**
   * Remove the stored end to end account for the logged-in user.
   */
  removeEndToEndAccount: function removeEndToEndAccount() {
    this.store.removeItem(KEY_END_TO_END_ACCOUNT);
  },

  /**
   * Load the end to end account for the logged-in user.
   * Note that the end-to-end account is now stored in the
   * crypto store rather than here: this remains here so
   * old sessions can be migrated out of the session store.
   * @return {?string} Base64 encoded account.
   */
  getEndToEndAccount: function getEndToEndAccount() {
    return this.store.getItem(KEY_END_TO_END_ACCOUNT);
  },

  /**
   * Retrieves the known devices for all users.
   * @return {object} A map from user ID to map of device ID to keys for the device.
   */
  getAllEndToEndDevices: function getAllEndToEndDevices() {
    var prefix = keyEndToEndDevicesForUser('');
    var devices = {};

    for (var i = 0; i < this.store.length; ++i) {
      var key = this.store.key(i);
      var userId = key.substr(prefix.length);
      if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key);
    }

    return devices;
  },
  getEndToEndDeviceTrackingStatus: function getEndToEndDeviceTrackingStatus() {
    return getJsonItem(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);
  },

  /**
   * Get the sync token corresponding to the device list.
   *
   * @return {String?} token
   */
  getEndToEndDeviceSyncToken: function getEndToEndDeviceSyncToken() {
    return getJsonItem(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);
  },

  /**
   * Removes all end to end device data from the store
   */
  removeEndToEndDeviceData: function removeEndToEndDeviceData() {
    removeByPrefix(this.store, keyEndToEndDevicesForUser(''));
    removeByPrefix(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);
    removeByPrefix(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);
  },

  /**
   * Retrieve the end-to-end sessions between the logged-in user and another
   * device.
   * @param {string} deviceKey The public key of the other device.
   * @return {object} A map from sessionId to Base64 end-to-end session.
   */
  getEndToEndSessions: function getEndToEndSessions(deviceKey) {
    return getJsonItem(this.store, keyEndToEndSessions(deviceKey));
  },

  /**
   * Retrieve all end-to-end sessions between the logged-in user and other
   * devices.
   * @return {object} A map of {deviceKey -> {sessionId -> session pickle}}
   */
  getAllEndToEndSessions: function getAllEndToEndSessions() {
    var deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions(''));
    var results = {};

    var _iterator = _createForOfIteratorHelper(deviceKeys),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var k = _step.value;
        var unprefixedKey = k.substr(keyEndToEndSessions('').length);
        results[unprefixedKey] = getJsonItem(this.store, k);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return results;
  },

  /**
   * Remove all end-to-end sessions from the store
   * This is used after migrating sessions awat from the sessions store.
   */
  removeAllEndToEndSessions: function removeAllEndToEndSessions() {
    removeByPrefix(this.store, keyEndToEndSessions(''));
  },

  /**
   * Retrieve a list of all known inbound group sessions
   *
   * @return {{senderKey: string, sessionId: string}}
   */
  getAllEndToEndInboundGroupSessionKeys: function getAllEndToEndInboundGroupSessionKeys() {
    var prefix = E2E_PREFIX + 'inboundgroupsessions/';
    var result = [];

    for (var i = 0; i < this.store.length; i++) {
      var key = this.store.key(i);

      if (!key.startsWith(prefix)) {
        continue;
      } // we can't use split, as the components we are trying to split out
      // might themselves contain '/' characters. We rely on the
      // senderKey being a (32-byte) curve25519 key, base64-encoded
      // (hence 43 characters long).


      result.push({
        senderKey: key.substr(prefix.length, 43),
        sessionId: key.substr(prefix.length + 44)
      });
    }

    return result;
  },
  getEndToEndInboundGroupSession: function getEndToEndInboundGroupSession(senderKey, sessionId) {
    var key = keyEndToEndInboundGroupSession(senderKey, sessionId);
    return this.store.getItem(key);
  },
  removeAllEndToEndInboundGroupSessions: function removeAllEndToEndInboundGroupSessions() {
    removeByPrefix(this.store, E2E_PREFIX + 'inboundgroupsessions/');
  },

  /**
   * Get the end-to-end state for all rooms
   * @return {object} roomId -> object with the end-to-end info for the room.
   */
  getAllEndToEndRooms: function getAllEndToEndRooms() {
    var roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom(''));
    var results = {};

    var _iterator2 = _createForOfIteratorHelper(roomKeys),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var k = _step2.value;
        var unprefixedKey = k.substr(keyEndToEndRoom('').length);
        results[unprefixedKey] = getJsonItem(this.store, k);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    return results;
  },
  removeAllEndToEndRooms: function removeAllEndToEndRooms() {
    removeByPrefix(this.store, keyEndToEndRoom(''));
  },
  setLocalTrustedBackupPubKey: function setLocalTrustedBackupPubKey(pubkey) {
    this.store.setItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY, pubkey);
  },
  // XXX: This store is deprecated really, but added this as a temporary
  // thing until cross-signing lands.
  getLocalTrustedBackupPubKey: function getLocalTrustedBackupPubKey() {
    return this.store.getItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY);
  }
};
var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
var KEY_END_TO_END_DEVICE_SYNC_TOKEN = E2E_PREFIX + "device_sync_token";
var KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS = E2E_PREFIX + "device_tracking";
var KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY = E2E_PREFIX + "trusted_backup_pubkey";

function keyEndToEndDevicesForUser(userId) {
  return E2E_PREFIX + "devices/" + userId;
}

function keyEndToEndSessions(deviceKey) {
  return E2E_PREFIX + "sessions/" + deviceKey;
}

function keyEndToEndInboundGroupSession(senderKey, sessionId) {
  return E2E_PREFIX + "inboundgroupsessions/" + senderKey + "/" + sessionId;
}

function keyEndToEndRoom(roomId) {
  return E2E_PREFIX + "rooms/" + roomId;
}

function getJsonItem(store, key) {
  try {
    // if the key is absent, store.getItem() returns null, and
    // JSON.parse(null) === null, so this returns null.
    return JSON.parse(store.getItem(key));
  } catch (e) {
    debuglog("Failed to get key %s: %s", key, e);
    debuglog(e.stack);
  }

  return null;
}

function getKeysWithPrefix(store, prefix) {
  var results = [];

  for (var i = 0; i < store.length; ++i) {
    var key = store.key(i);
    if (key.startsWith(prefix)) results.push(key);
  }

  return results;
}

function removeByPrefix(store, prefix) {
  var toRemove = [];

  for (var i = 0; i < store.length; ++i) {
    var key = store.key(i);
    if (key.startsWith(prefix)) toRemove.push(key);
  }

  for (var _i = 0, _toRemove = toRemove; _i < _toRemove.length; _i++) {
    var _key = _toRemove[_i];
    store.removeItem(_key);
  }
}

function debuglog() {
  if (DEBUG) {
    _logger.logger.log.apply(_logger.logger, arguments);
  }
}

},{"../../logger":106,"../../utils":137,"@babel/runtime/helpers/interopRequireWildcard":13}],132:[function(require,module,exports){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.StubStore = void 0;
/**
 * Construct a stub store. This does no-ops on most store methods.
 * @constructor
 */
class StubStore {
    constructor() {
        this.fromToken = null;
    }
    /** @return {Promise<bool>} whether or not the database was newly created in this session. */
    isNewlyCreated() {
        return Promise.resolve(true);
    }
    /**
     * Get the sync token.
     * @return {string}
     */
    getSyncToken() {
        return this.fromToken;
    }
    /**
     * Set the sync token.
     * @param {string} token
     */
    setSyncToken(token) {
        this.fromToken = token;
    }
    /**
     * No-op.
     * @param {Group} group
     */
    storeGroup(group) { }
    /**
     * No-op.
     * @param {string} groupId
     * @return {null}
     */
    getGroup(groupId) {
        return null;
    }
    /**
     * No-op.
     * @return {Array} An empty array.
     */
    getGroups() {
        return [];
    }
    /**
     * No-op.
     * @param {Room} room
     */
    storeRoom(room) { }
    /**
     * No-op.
     * @param {string} roomId
     * @return {null}
     */
    getRoom(roomId) {
        return null;
    }
    /**
     * No-op.
     * @return {Array} An empty array.
     */
    getRooms() {
        return [];
    }
    /**
     * Permanently delete a room.
     * @param {string} roomId
     */
    removeRoom(roomId) {
        return;
    }
    /**
     * No-op.
     * @return {Array} An empty array.
     */
    getRoomSummaries() {
        return [];
    }
    /**
     * No-op.
     * @param {User} user
     */
    storeUser(user) { }
    /**
     * No-op.
     * @param {string} userId
     * @return {null}
     */
    getUser(userId) {
        return null;
    }
    /**
     * No-op.
     * @return {User[]}
     */
    getUsers() {
        return [];
    }
    /**
     * No-op.
     * @param {Room} room
     * @param {integer} limit
     * @return {Array}
     */
    scrollback(room, limit) {
        return [];
    }
    /**
     * Store events for a room.
     * @param {Room} room The room to store events for.
     * @param {Array<MatrixEvent>} events The events to store.
     * @param {string} token The token associated with these events.
     * @param {boolean} toStart True if these are paginated results.
     */
    storeEvents(room, events, token, toStart) { }
    /**
     * Store a filter.
     * @param {Filter} filter
     */
    storeFilter(filter) { }
    /**
     * Retrieve a filter.
     * @param {string} userId
     * @param {string} filterId
     * @return {?Filter} A filter or null.
     */
    getFilter(userId, filterId) {
        return null;
    }
    /**
     * Retrieve a filter ID with the given name.
     * @param {string} filterName The filter name.
     * @return {?string} The filter ID or null.
     */
    getFilterIdByName(filterName) {
        return null;
    }
    /**
     * Set a filter name to ID mapping.
     * @param {string} filterName
     * @param {string} filterId
     */
    setFilterIdByName(filterName, filterId) { }
    /**
     * Store user-scoped account data events
     * @param {Array<MatrixEvent>} events The events to store.
     */
    storeAccountDataEvents(events) { }
    /**
     * Get account data event by event type
     * @param {string} eventType The event type being queried
     */
    getAccountData(eventType) {
        return undefined;
    }
    /**
     * setSyncData does nothing as there is no backing data store.
     *
     * @param {Object} syncData The sync data
     * @return {Promise} An immediately resolved promise.
     */
    setSyncData(syncData) {
        return Promise.resolve();
    }
    /**
     * We never want to save because we have nothing to save to.
     *
     * @return {boolean} If the store wants to save
     */
    wantsSave() {
        return false;
    }
    /**
     * Save does nothing as there is no backing data store.
     */
    save() { }
    /**
     * Startup does nothing.
     * @return {Promise} An immediately resolved promise.
     */
    startup() {
        return Promise.resolve();
    }
    /**
     * @return {Promise} Resolves with a sync response to restore the
     * client state to where it was at the last save, or null if there
     * is no saved sync data.
     */
    getSavedSync() {
        return Promise.resolve(null);
    }
    /**
     * @return {Promise} If there is a saved sync, the nextBatch token
     * for this sync, otherwise null.
     */
    getSavedSyncToken() {
        return Promise.resolve(null);
    }
    /**
     * Delete all data from this store. Does nothing since this store
     * doesn't store anything.
     * @return {Promise} An immediately resolved promise.
     */
    deleteAllData() {
        return Promise.resolve();
    }
    getOutOfBandMembers() {
        return Promise.resolve(null);
    }
    setOutOfBandMembers(roomId, membershipEvents) {
        return Promise.resolve();
    }
    clearOutOfBandMembers() {
        return Promise.resolve();
    }
    getClientOptions() {
        return Promise.resolve({});
    }
    storeClientOptions(options) {
        return Promise.resolve();
    }
}
exports.StubStore = StubStore;

},{}],133:[function(require,module,exports){
"use strict";
/*
Copyright 2017 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncAccumulator = exports.Category = void 0;
/**
 * This is an internal module. See {@link SyncAccumulator} for the public class.
 * @module sync-accumulator
 */
const logger_1 = require("./logger");
const utils_1 = require("./utils");
/* eslint-enable camelcase */
var Category;
(function (Category) {
    Category["Invite"] = "invite";
    Category["Leave"] = "leave";
    Category["Join"] = "join";
})(Category = exports.Category || (exports.Category = {}));
/**
 * The purpose of this class is to accumulate /sync responses such that a
 * complete "initial" JSON response can be returned which accurately represents
 * the sum total of the /sync responses accumulated to date. It only handles
 * room data: that is, everything under the "rooms" top-level key.
 *
 * This class is used when persisting room data so a complete /sync response can
 * be loaded from disk and incremental syncs can be performed on the server,
 * rather than asking the server to do an initial sync on startup.
 */
class SyncAccumulator {
    /**
     * @param {Object} opts
     * @param {Number=} opts.maxTimelineEntries The ideal maximum number of
     * timeline entries to keep in the sync response. This is best-effort, as
     * clients do not always have a back-pagination token for each event, so
     * it's possible there may be slightly *less* than this value. There will
     * never be more. This cannot be 0 or else it makes it impossible to scroll
     * back in a room. Default: 50.
     */
    constructor(opts = {}) {
        this.opts = opts;
        this.accountData = {}; // $event_type: Object
        this.inviteRooms = {}; // $roomId: { ... sync 'invite' json data ... }
        this.joinRooms = {};
        // the /sync token which corresponds to the last time rooms were
        // accumulated. We remember this so that any caller can obtain a
        // coherent /sync response and know at what point they should be
        // streaming from without losing events.
        this.nextBatch = null;
        // { ('invite'|'join'|'leave'): $groupId: { ... sync 'group' data } }
        this.groups = {
            invite: {},
            join: {},
            leave: {},
        };
        this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;
    }
    accumulate(syncResponse, fromDatabase = false) {
        this.accumulateRooms(syncResponse, fromDatabase);
        this.accumulateGroups(syncResponse);
        this.accumulateAccountData(syncResponse);
        this.nextBatch = syncResponse.next_batch;
    }
    accumulateAccountData(syncResponse) {
        if (!syncResponse.account_data || !syncResponse.account_data.events) {
            return;
        }
        // Clobbers based on event type.
        syncResponse.account_data.events.forEach((e) => {
            this.accountData[e.type] = e;
        });
    }
    /**
     * Accumulate incremental /sync room data.
     * @param {Object} syncResponse the complete /sync JSON
     * @param {boolean} fromDatabase True if the sync response is one saved to the database
     */
    accumulateRooms(syncResponse, fromDatabase = false) {
        if (!syncResponse.rooms) {
            return;
        }
        if (syncResponse.rooms.invite) {
            Object.keys(syncResponse.rooms.invite).forEach((roomId) => {
                this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);
            });
        }
        if (syncResponse.rooms.join) {
            Object.keys(syncResponse.rooms.join).forEach((roomId) => {
                this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);
            });
        }
        if (syncResponse.rooms.leave) {
            Object.keys(syncResponse.rooms.leave).forEach((roomId) => {
                this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);
            });
        }
    }
    accumulateRoom(roomId, category, data, fromDatabase = false) {
        // Valid /sync state transitions
        //       +--------+ <======+            1: Accept an invite
        //   +== | INVITE |        | (5)        2: Leave a room
        //   |   +--------+ =====+ |            3: Join a public room previously
        //   |(1)            (4) | |               left (handle as if new room)
        //   V         (2)       V |            4: Reject an invite
        // +------+ ========> +--------+         5: Invite to a room previously
        // | JOIN |    (3)    | LEAVE* |            left (handle as if new room)
        // +------+ <======== +--------+
        //
        // * equivalent to "no state"
        switch (category) {
            case Category.Invite: // (5)
                this.accumulateInviteState(roomId, data);
                break;
            case Category.Join:
                if (this.inviteRooms[roomId]) { // (1)
                    // was previously invite, now join. We expect /sync to give
                    // the entire state and timeline on 'join', so delete previous
                    // invite state
                    delete this.inviteRooms[roomId];
                }
                // (3)
                this.accumulateJoinState(roomId, data, fromDatabase);
                break;
            case Category.Leave:
                if (this.inviteRooms[roomId]) { // (4)
                    delete this.inviteRooms[roomId];
                }
                else { // (2)
                    delete this.joinRooms[roomId];
                }
                break;
            default:
                logger_1.logger.error("Unknown cateogory: ", category);
        }
    }
    accumulateInviteState(roomId, data) {
        if (!data.invite_state || !data.invite_state.events) { // no new data
            return;
        }
        if (!this.inviteRooms[roomId]) {
            this.inviteRooms[roomId] = {
                invite_state: data.invite_state,
            };
            return;
        }
        // accumulate extra keys for invite->invite transitions
        // clobber based on event type / state key
        // We expect invite_state to be small, so just loop over the events
        const currentData = this.inviteRooms[roomId];
        data.invite_state.events.forEach((e) => {
            let hasAdded = false;
            for (let i = 0; i < currentData.invite_state.events.length; i++) {
                const current = currentData.invite_state.events[i];
                if (current.type === e.type && current.state_key == e.state_key) {
                    currentData.invite_state.events[i] = e; // update
                    hasAdded = true;
                }
            }
            if (!hasAdded) {
                currentData.invite_state.events.push(e);
            }
        });
    }
    // Accumulate timeline and state events in a room.
    accumulateJoinState(roomId, data, fromDatabase = false) {
        // We expect this function to be called a lot (every /sync) so we want
        // this to be fast. /sync stores events in an array but we often want
        // to clobber based on type/state_key. Rather than convert arrays to
        // maps all the time, just keep private maps which contain
        // the actual current accumulated sync state, and array-ify it when
        // getJSON() is called.
        // State resolution:
        // The 'state' key is the delta from the previous sync (or start of time
        // if no token was supplied), to the START of the timeline. To obtain
        // the current state, we need to "roll forward" state by reading the
        // timeline. We want to store the current state so we can drop events
        // out the end of the timeline based on opts.maxTimelineEntries.
        //
        //      'state'     'timeline'     current state
        // |-------x<======================>x
        //          T   I   M   E
        //
        // When getJSON() is called, we 'roll back' the current state by the
        // number of entries in the timeline to work out what 'state' should be.
        // Back-pagination:
        // On an initial /sync, the server provides a back-pagination token for
        // the start of the timeline. When /sync deltas come down, they also
        // include back-pagination tokens for the start of the timeline. This
        // means not all events in the timeline have back-pagination tokens, as
        // it is only the ones at the START of the timeline which have them.
        // In order for us to have a valid timeline (and back-pagination token
        // to match), we need to make sure that when we remove old timeline
        // events, that we roll forward to an event which has a back-pagination
        // token. This means we can't keep a strict sliding-window based on
        // opts.maxTimelineEntries, and we may have a few less. We should never
        // have more though, provided that the /sync limit is less than or equal
        // to opts.maxTimelineEntries.
        if (!this.joinRooms[roomId]) {
            // Create truly empty objects so event types of 'hasOwnProperty' and co
            // don't cause this code to break.
            this.joinRooms[roomId] = {
                _currentState: Object.create(null),
                _timeline: [],
                _accountData: Object.create(null),
                _unreadNotifications: {},
                _summary: {},
                _readReceipts: {},
            };
        }
        const currentData = this.joinRooms[roomId];
        if (data.account_data && data.account_data.events) {
            // clobber based on type
            data.account_data.events.forEach((e) => {
                currentData._accountData[e.type] = e;
            });
        }
        // these probably clobber, spec is unclear.
        if (data.unread_notifications) {
            currentData._unreadNotifications = data.unread_notifications;
        }
        if (data.summary) {
            const HEROES_KEY = "m.heroes";
            const INVITED_COUNT_KEY = "m.invited_member_count";
            const JOINED_COUNT_KEY = "m.joined_member_count";
            const acc = currentData._summary;
            const sum = data.summary;
            acc[HEROES_KEY] = sum[HEROES_KEY] || acc[HEROES_KEY];
            acc[JOINED_COUNT_KEY] = sum[JOINED_COUNT_KEY] || acc[JOINED_COUNT_KEY];
            acc[INVITED_COUNT_KEY] = sum[INVITED_COUNT_KEY] || acc[INVITED_COUNT_KEY];
        }
        if (data.ephemeral && data.ephemeral.events) {
            data.ephemeral.events.forEach((e) => {
                // We purposefully do not persist m.typing events.
                // Technically you could refresh a browser before the timer on a
                // typing event is up, so it'll look like you aren't typing when
                // you really still are. However, the alternative is worse. If
                // we do persist typing events, it will look like people are
                // typing forever until someone really does start typing (which
                // will prompt Synapse to send down an actual m.typing event to
                // clobber the one we persisted).
                if (e.type !== "m.receipt" || !e.content) {
                    // This means we'll drop unknown ephemeral events but that
                    // seems okay.
                    return;
                }
                // Handle m.receipt events. They clobber based on:
                //   (user_id, receipt_type)
                // but they are keyed in the event as:
                //   content:{ $event_id: { $receipt_type: { $user_id: {json} }}}
                // so store them in the former so we can accumulate receipt deltas
                // quickly and efficiently (we expect a lot of them). Fold the
                // receipt type into the key name since we only have 1 at the
                // moment (m.read) and nested JSON objects are slower and more
                // of a hassle to work with. We'll inflate this back out when
                // getJSON() is called.
                Object.keys(e.content).forEach((eventId) => {
                    if (!e.content[eventId]["m.read"]) {
                        return;
                    }
                    Object.keys(e.content[eventId]["m.read"]).forEach((userId) => {
                        // clobber on user ID
                        currentData._readReceipts[userId] = {
                            data: e.content[eventId]["m.read"][userId],
                            eventId: eventId,
                        };
                    });
                });
            });
        }
        // if we got a limited sync, we need to remove all timeline entries or else
        // we will have gaps in the timeline.
        if (data.timeline && data.timeline.limited) {
            currentData._timeline = [];
        }
        // Work out the current state. The deltas need to be applied in the order:
        // - existing state which didn't come down /sync.
        // - State events under the 'state' key.
        // - State events in the 'timeline'.
        if (data.state && data.state.events) {
            data.state.events.forEach((e) => {
                setState(currentData._currentState, e);
            });
        }
        if (data.timeline && data.timeline.events) {
            data.timeline.events.forEach((e, index) => {
                // this nops if 'e' isn't a state event
                setState(currentData._currentState, e);
                // append the event to the timeline. The back-pagination token
                // corresponds to the first event in the timeline
                let transformedEvent;
                if (!fromDatabase) {
                    transformedEvent = Object.assign({}, e);
                    if (transformedEvent.unsigned !== undefined) {
                        transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);
                    }
                    const age = e.unsigned ? e.unsigned.age : e.age;
                    if (age !== undefined)
                        transformedEvent._localTs = Date.now() - age;
                }
                else {
                    transformedEvent = e;
                }
                currentData._timeline.push({
                    event: transformedEvent,
                    token: index === 0 ? data.timeline.prev_batch : null,
                });
            });
        }
        // attempt to prune the timeline by jumping between events which have
        // pagination tokens.
        if (currentData._timeline.length > this.opts.maxTimelineEntries) {
            const startIndex = (currentData._timeline.length - this.opts.maxTimelineEntries);
            for (let i = startIndex; i < currentData._timeline.length; i++) {
                if (currentData._timeline[i].token) {
                    // keep all events after this, including this one
                    currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);
                    break;
                }
            }
        }
    }
    /**
     * Accumulate incremental /sync group data.
     * @param {Object} syncResponse the complete /sync JSON
     */
    accumulateGroups(syncResponse) {
        if (!syncResponse.groups) {
            return;
        }
        if (syncResponse.groups.invite) {
            Object.keys(syncResponse.groups.invite).forEach((groupId) => {
                this.accumulateGroup(groupId, Category.Invite, syncResponse.groups.invite[groupId]);
            });
        }
        if (syncResponse.groups.join) {
            Object.keys(syncResponse.groups.join).forEach((groupId) => {
                this.accumulateGroup(groupId, Category.Join, syncResponse.groups.join[groupId]);
            });
        }
        if (syncResponse.groups.leave) {
            Object.keys(syncResponse.groups.leave).forEach((groupId) => {
                this.accumulateGroup(groupId, Category.Leave, syncResponse.groups.leave[groupId]);
            });
        }
    }
    accumulateGroup(groupId, category, data) {
        for (const cat of [Category.Invite, Category.Leave, Category.Join]) {
            delete this.groups[cat][groupId];
        }
        this.groups[category][groupId] = data;
    }
    /**
     * Return everything under the 'rooms' key from a /sync response which
     * represents all room data that should be stored. This should be paired
     * with the sync token which represents the most recent /sync response
     * provided to accumulate().
     * @param {boolean} forDatabase True to generate a sync to be saved to storage
     * @return {Object} An object with a "nextBatch", "roomsData" and "accountData"
     * keys.
     * The "nextBatch" key is a string which represents at what point in the
     * /sync stream the accumulator reached. This token should be used when
     * restarting a /sync stream at startup. Failure to do so can lead to missing
     * events. The "roomsData" key is an Object which represents the entire
     * /sync response from the 'rooms' key onwards. The "accountData" key is
     * a list of raw events which represent global account data.
     */
    getJSON(forDatabase = false) {
        const data = {
            join: {},
            invite: {},
            // always empty. This is set by /sync when a room was previously
            // in 'invite' or 'join'. On fresh startup, the client won't know
            // about any previous room being in 'invite' or 'join' so we can
            // just omit mentioning it at all, even if it has previously come
            // down /sync.
            // The notable exception is when a client is kicked or banned:
            // we may want to hold onto that room so the client can clearly see
            // why their room has disappeared. We don't persist it though because
            // it is unclear *when* we can safely remove the room from the DB.
            // Instead, we assume that if you're loading from the DB, you've
            // refreshed the page, which means you've seen the kick/ban already.
            leave: {},
        };
        Object.keys(this.inviteRooms).forEach((roomId) => {
            data.invite[roomId] = this.inviteRooms[roomId];
        });
        Object.keys(this.joinRooms).forEach((roomId) => {
            const roomData = this.joinRooms[roomId];
            const roomJson = {
                ephemeral: { events: [] },
                account_data: { events: [] },
                state: { events: [] },
                timeline: {
                    events: [],
                    prev_batch: null,
                },
                unread_notifications: roomData._unreadNotifications,
                summary: roomData._summary,
            };
            // Add account data
            Object.keys(roomData._accountData).forEach((evType) => {
                roomJson.account_data.events.push(roomData._accountData[evType]);
            });
            // Add receipt data
            const receiptEvent = {
                type: "m.receipt",
                room_id: roomId,
                content: {
                // $event_id: { "m.read": { $user_id: $json } }
                },
            };
            Object.keys(roomData._readReceipts).forEach((userId) => {
                const receiptData = roomData._readReceipts[userId];
                if (!receiptEvent.content[receiptData.eventId]) {
                    receiptEvent.content[receiptData.eventId] = {
                        "m.read": {},
                    };
                }
                receiptEvent.content[receiptData.eventId]["m.read"][userId] = (receiptData.data);
            });
            // add only if we have some receipt data
            if (Object.keys(receiptEvent.content).length > 0) {
                roomJson.ephemeral.events.push(receiptEvent);
            }
            // Add timeline data
            roomData._timeline.forEach((msgData) => {
                if (!roomJson.timeline.prev_batch) {
                    // the first event we add to the timeline MUST match up to
                    // the prev_batch token.
                    if (!msgData.token) {
                        return; // this shouldn't happen as we prune constantly.
                    }
                    roomJson.timeline.prev_batch = msgData.token;
                }
                let transformedEvent;
                if (!forDatabase && msgData.event["_localTs"]) {
                    // This means we have to copy each event so we can fix it up to
                    // set a correct 'age' parameter whilst keeping the local timestamp
                    // on our stored event. If this turns out to be a bottleneck, it could
                    // be optimised either by doing this in the main process after the data
                    // has been structured-cloned to go between the worker & main process,
                    // or special-casing data from saved syncs to read the local timestamp
                    // directly rather than turning it into age to then immediately be
                    // transformed back again into a local timestamp.
                    transformedEvent = Object.assign({}, msgData.event);
                    if (transformedEvent.unsigned !== undefined) {
                        transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);
                    }
                    delete transformedEvent._localTs;
                    transformedEvent.unsigned = transformedEvent.unsigned || {};
                    transformedEvent.unsigned.age = Date.now() - msgData.event["_localTs"];
                }
                else {
                    transformedEvent = msgData.event;
                }
                roomJson.timeline.events.push(transformedEvent);
            });
            // Add state data: roll back current state to the start of timeline,
            // by "reverse clobbering" from the end of the timeline to the start.
            // Convert maps back into arrays.
            const rollBackState = Object.create(null);
            for (let i = roomJson.timeline.events.length - 1; i >= 0; i--) {
                const timelineEvent = roomJson.timeline.events[i];
                if (timelineEvent.state_key === null ||
                    timelineEvent.state_key === undefined) {
                    continue; // not a state event
                }
                // since we're going back in time, we need to use the previous
                // state value else we'll break causality. We don't have the
                // complete previous state event, so we need to create one.
                const prevStateEvent = utils_1.deepCopy(timelineEvent);
                if (prevStateEvent.unsigned) {
                    if (prevStateEvent.unsigned.prev_content) {
                        prevStateEvent.content = prevStateEvent.unsigned.prev_content;
                    }
                    if (prevStateEvent.unsigned.prev_sender) {
                        prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;
                    }
                }
                setState(rollBackState, prevStateEvent);
            }
            Object.keys(roomData._currentState).forEach((evType) => {
                Object.keys(roomData._currentState[evType]).forEach((stateKey) => {
                    let ev = roomData._currentState[evType][stateKey];
                    if (rollBackState[evType] && rollBackState[evType][stateKey]) {
                        // use the reverse clobbered event instead.
                        ev = rollBackState[evType][stateKey];
                    }
                    roomJson.state.events.push(ev);
                });
            });
            data.join[roomId] = roomJson;
        });
        // Add account data
        const accData = [];
        Object.keys(this.accountData).forEach((evType) => {
            accData.push(this.accountData[evType]);
        });
        return {
            nextBatch: this.nextBatch,
            roomsData: data,
            groupsData: this.groups,
            accountData: accData,
        };
    }
    getNextBatchToken() {
        return this.nextBatch;
    }
}
exports.SyncAccumulator = SyncAccumulator;
function setState(eventMap, event) {
    if (event.state_key === null || event.state_key === undefined || !event.type) {
        return;
    }
    if (!eventMap[event.type]) {
        eventMap[event.type] = Object.create(null);
    }
    eventMap[event.type][event.state_key] = event;
}

},{"./logger":106,"./utils":137}],134:[function(require,module,exports){
"use strict";
/*
Copyright 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncState = void 0;
// TODO: Merge this with sync.js once converted
var SyncState;
(function (SyncState) {
    SyncState["Error"] = "ERROR";
    SyncState["Prepared"] = "PREPARED";
    SyncState["Stopped"] = "STOPPED";
    SyncState["Syncing"] = "SYNCING";
    SyncState["Catchup"] = "CATCHUP";
    SyncState["Reconnecting"] = "RECONNECTING";
})(SyncState = exports.SyncState || (exports.SyncState = {}));

},{}],135:[function(require,module,exports){
(function (global){(function (){
"use strict";
/*
Copyright 2015 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncApi = void 0;
/*
 * TODO:
 * This class mainly serves to take all the syncing logic out of client.js and
 * into a separate file. It's all very fluid, and this class gut wrenches a lot
 * of MatrixClient props (e.g. http). Given we want to support WebSockets as
 * an alternative syncing API, we may want to have a proper syncing interface
 * for HTTP and WS at some point.
 */
const user_1 = require("./models/user");
const room_1 = require("./models/room");
const group_1 = require("./models/group");
const utils = __importStar(require("./utils"));
const filter_1 = require("./filter");
const event_timeline_1 = require("./models/event-timeline");
const pushprocessor_1 = require("./pushprocessor");
const logger_1 = require("./logger");
const errors_1 = require("./errors");
const client_1 = require("./client");
const sync_api_1 = require("./sync.api");
const sync_accumulator_1 = require("./sync-accumulator");
const DEBUG = true;
// /sync requests allow you to set a timeout= but the request may continue
// beyond that and wedge forever, so we need to track how long we are willing
// to keep open the connection. This constant is *ADDED* to the timeout= value
// to determine the max time we're willing to wait.
const BUFFER_PERIOD_MS = 80 * 1000;
// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed
// to RECONNECTING. This is needed to inform the client of server issues when the
// keepAlive is successful but the server /sync fails.
const FAILED_SYNC_ERROR_THRESHOLD = 3;
function getFilterName(userId, suffix) {
    // scope this on the user ID because people may login on many accounts
    // and they all need to be stored!
    return "FILTER_SYNC_" + userId + (suffix ? "_" + suffix : "");
}
function debuglog(...params) {
    if (!DEBUG) {
        return;
    }
    logger_1.logger.log(...params);
}
/**
 * <b>Internal class - unstable.</b>
 * Construct an entity which is able to sync with a homeserver.
 * @constructor
 * @param {MatrixClient} client The matrix client instance to use.
 * @param {Object} opts Config options
 * @param {module:crypto=} opts.crypto Crypto manager
 * @param {Function=} opts.canResetEntireTimeline A function which is called
 * with a room ID and returns a boolean. It should return 'true' if the SDK can
 * SAFELY remove events from this room. It may not be safe to remove events if
 * there are other references to the timelines for this room.
 * Default: returns false.
 * @param {Boolean=} opts.disablePresence True to perform syncing without automatically
 * updating presence.
 */
class SyncApi {
    constructor(client, opts = {}) {
        var _a;
        this.client = client;
        this.opts = opts;
        this._peekRoom = null;
        this.currentSyncRequest = null;
        this.syncState = null;
        this.syncStateData = null; // additional data (eg. error object for failed sync)
        this.catchingUp = false;
        this.running = false;
        this.keepAliveTimer = null;
        this.connectionReturnedDefer = null;
        this.notifEvents = []; // accumulator of sync events in the current sync response
        this.failedSyncCount = 0; // Number of consecutive failed /sync requests
        this.storeIsInvalid = false; // flag set if the store needs to be cleared before we can start
        /**
         * Event handler for the 'online' event
         * This event is generally unreliable and precise behaviour
         * varies between browsers, so we poll for connectivity too,
         * but this might help us reconnect a little faster.
         */
        this.onOnline = () => {
            debuglog("Browser thinks we are back online");
            this.startKeepAlives(0);
        };
        this.opts.initialSyncLimit = (_a = this.opts.initialSyncLimit) !== null && _a !== void 0 ? _a : 8;
        this.opts.resolveInvitesToProfiles = this.opts.resolveInvitesToProfiles || false;
        this.opts.pollTimeout = this.opts.pollTimeout || (30 * 1000);
        this.opts.pendingEventOrdering = this.opts.pendingEventOrdering || client_1.PendingEventOrdering.Chronological;
        if (!opts.canResetEntireTimeline) {
            opts.canResetEntireTimeline = (roomId) => {
                return false;
            };
        }
        if (client.getNotifTimelineSet()) {
            client.reEmitter.reEmit(client.getNotifTimelineSet(), ["Room.timeline", "Room.timelineReset"]);
        }
    }
    /**
     * @param {string} roomId
     * @return {Room}
     */
    createRoom(roomId) {
        const client = this.client;
        const { timelineSupport, unstableClientRelationAggregation, } = client;
        const room = new room_1.Room(roomId, client, client.getUserId(), {
            lazyLoadMembers: this.opts.lazyLoadMembers,
            pendingEventOrdering: this.opts.pendingEventOrdering,
            timelineSupport,
            unstableClientRelationAggregation,
        });
        client.reEmitter.reEmit(room, ["Room.name", "Room.timeline",
            "Room.redaction",
            "Room.redactionCancelled",
            "Room.receipt", "Room.tags",
            "Room.timelineReset",
            "Room.localEchoUpdated",
            "Room.accountData",
            "Room.myMembership",
            "Room.replaceEvent",
        ]);
        this.registerStateListeners(room);
        return room;
    }
    /**
     * @param {string} groupId
     * @return {Group}
     */
    createGroup(groupId) {
        const client = this.client;
        const group = new group_1.Group(groupId);
        client.reEmitter.reEmit(group, ["Group.profile", "Group.myMembership"]);
        client.store.storeGroup(group);
        return group;
    }
    /**
     * @param {Room} room
     * @private
     */
    registerStateListeners(room) {
        const client = this.client;
        // we need to also re-emit room state and room member events, so hook it up
        // to the client now. We need to add a listener for RoomState.members in
        // order to hook them correctly. (TODO: find a better way?)
        client.reEmitter.reEmit(room.currentState, [
            "RoomState.events", "RoomState.members", "RoomState.newMember",
        ]);
        room.currentState.on("RoomState.newMember", function (event, state, member) {
            member.user = client.getUser(member.userId);
            client.reEmitter.reEmit(member, [
                "RoomMember.name", "RoomMember.typing", "RoomMember.powerLevel",
                "RoomMember.membership",
            ]);
        });
    }
    /**
     * @param {Room} room
     * @private
     */
    deregisterStateListeners(room) {
        // could do with a better way of achieving this.
        room.currentState.removeAllListeners("RoomState.events");
        room.currentState.removeAllListeners("RoomState.members");
        room.currentState.removeAllListeners("RoomState.newMember");
    }
    /**
     * Sync rooms the user has left.
     * @return {Promise} Resolved when they've been added to the store.
     */
    syncLeftRooms() {
        const client = this.client;
        // grab a filter with limit=1 and include_leave=true
        const filter = new filter_1.Filter(this.client.credentials.userId);
        filter.setTimelineLimit(1);
        filter.setIncludeLeaveRooms(true);
        const localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
        const qps = {
            timeout: 0,
        };
        return client.getOrCreateFilter(getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter).then(function (filterId) {
            qps.filter = filterId;
            return client.http.authedRequest(undefined, "GET", "/sync", qps, undefined, localTimeoutMs);
        }).then((data) => {
            let leaveRooms = [];
            if (data.rooms && data.rooms.leave) {
                leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);
            }
            const rooms = [];
            leaveRooms.forEach((leaveObj) => {
                const room = leaveObj.room;
                rooms.push(room);
                if (!leaveObj.isBrandNewRoom) {
                    // the intention behind syncLeftRooms is to add in rooms which were
                    // *omitted* from the initial /sync. Rooms the user were joined to
                    // but then left whilst the app is running will appear in this list
                    // and we do not want to bother with them since they will have the
                    // current state already (and may get dupe messages if we add
                    // yet more timeline events!), so skip them.
                    // NB: When we persist rooms to localStorage this will be more
                    //     complicated...
                    return;
                }
                leaveObj.timeline = leaveObj.timeline || {};
                const timelineEvents = this.mapSyncEventsFormat(leaveObj.timeline, room);
                const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);
                // set the back-pagination token. Do this *before* adding any
                // events so that clients can start back-paginating.
                room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, event_timeline_1.EventTimeline.BACKWARDS);
                this.processRoomEvents(room, stateEvents, timelineEvents);
                room.recalculate();
                client.store.storeRoom(room);
                client.emit("Room", room);
                this.processEventsForNotifs(room, timelineEvents);
            });
            return rooms;
        });
    }
    /**
     * Peek into a room. This will result in the room in question being synced so it
     * is accessible via getRooms(). Live updates for the room will be provided.
     * @param {string} roomId The room ID to peek into.
     * @return {Promise} A promise which resolves once the room has been added to the
     * store.
     */
    peek(roomId) {
        if (this._peekRoom && this._peekRoom.roomId === roomId) {
            return Promise.resolve(this._peekRoom);
        }
        const client = this.client;
        this._peekRoom = this.createRoom(roomId);
        return this.client.roomInitialSync(roomId, 20).then((response) => {
            // make sure things are init'd
            response.messages = response.messages || {};
            response.messages.chunk = response.messages.chunk || [];
            response.state = response.state || [];
            // FIXME: Mostly duplicated from processRoomEvents but not entirely
            // because "state" in this API is at the BEGINNING of the chunk
            const oldStateEvents = utils.deepCopy(response.state)
                .map(client.getEventMapper());
            const stateEvents = response.state.map(client.getEventMapper());
            const messages = response.messages.chunk.map(client.getEventMapper());
            // XXX: copypasted from /sync until we kill off this
            // minging v1 API stuff)
            // handle presence events (User objects)
            if (response.presence && Array.isArray(response.presence)) {
                response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) {
                    let user = client.store.getUser(presenceEvent.getContent().user_id);
                    if (user) {
                        user.setPresenceEvent(presenceEvent);
                    }
                    else {
                        user = createNewUser(client, presenceEvent.getContent().user_id);
                        user.setPresenceEvent(presenceEvent);
                        client.store.storeUser(user);
                    }
                    client.emit("event", presenceEvent);
                });
            }
            // set the pagination token before adding the events in case people
            // fire off pagination requests in response to the Room.timeline
            // events.
            if (response.messages.start) {
                this._peekRoom.oldState.paginationToken = response.messages.start;
            }
            // set the state of the room to as it was after the timeline executes
            this._peekRoom.oldState.setStateEvents(oldStateEvents);
            this._peekRoom.currentState.setStateEvents(stateEvents);
            this.resolveInvites(this._peekRoom);
            this._peekRoom.recalculate();
            // roll backwards to diverge old state. addEventsToTimeline
            // will overwrite the pagination token, so make sure it overwrites
            // it with the right thing.
            this._peekRoom.addEventsToTimeline(messages.reverse(), true, this._peekRoom.getLiveTimeline(), response.messages.start);
            client.store.storeRoom(this._peekRoom);
            client.emit("Room", this._peekRoom);
            this.peekPoll(this._peekRoom);
            return this._peekRoom;
        });
    }
    /**
     * Stop polling for updates in the peeked room. NOPs if there is no room being
     * peeked.
     */
    stopPeeking() {
        this._peekRoom = null;
    }
    /**
     * Do a peek room poll.
     * @param {Room} peekRoom
     * @param {string?} token from= token
     */
    peekPoll(peekRoom, token) {
        if (this._peekRoom !== peekRoom) {
            debuglog("Stopped peeking in room %s", peekRoom.roomId);
            return;
        }
        // FIXME: gut wrenching; hard-coded timeout values
        this.client.http.authedRequest(undefined, "GET", "/events", {
            room_id: peekRoom.roomId,
            timeout: 30 * 1000,
            from: token,
        }, undefined, 50 * 1000).then((res) => {
            if (this._peekRoom !== peekRoom) {
                debuglog("Stopped peeking in room %s", peekRoom.roomId);
                return;
            }
            // We have a problem that we get presence both from /events and /sync
            // however, /sync only returns presence for users in rooms
            // you're actually joined to.
            // in order to be sure to get presence for all of the users in the
            // peeked room, we handle presence explicitly here. This may result
            // in duplicate presence events firing for some users, which is a
            // performance drain, but such is life.
            // XXX: copypasted from /sync until we can kill this minging v1 stuff.
            res.chunk.filter(function (e) {
                return e.type === "m.presence";
            }).map(this.client.getEventMapper()).forEach((presenceEvent) => {
                let user = this.client.store.getUser(presenceEvent.getContent().user_id);
                if (user) {
                    user.setPresenceEvent(presenceEvent);
                }
                else {
                    user = createNewUser(this.client, presenceEvent.getContent().user_id);
                    user.setPresenceEvent(presenceEvent);
                    this.client.store.storeUser(user);
                }
                this.client.emit("event", presenceEvent);
            });
            // strip out events which aren't for the given room_id (e.g presence)
            // and also ephemeral events (which we're assuming is anything without
            // and event ID because the /events API doesn't separate them).
            const events = res.chunk.filter(function (e) {
                return e.room_id === peekRoom.roomId && e.event_id;
            }).map(this.client.getEventMapper());
            peekRoom.addLiveEvents(events);
            this.peekPoll(peekRoom, res.end);
        }, (err) => {
            logger_1.logger.error("[%s] Peek poll failed: %s", peekRoom.roomId, err);
            setTimeout(() => {
                this.peekPoll(peekRoom, token);
            }, 30 * 1000);
        });
    }
    /**
     * Returns the current state of this sync object
     * @see module:client~MatrixClient#event:"sync"
     * @return {?String}
     */
    getSyncState() {
        return this.syncState;
    }
    /**
     * Returns the additional data object associated with
     * the current sync state, or null if there is no
     * such data.
     * Sync errors, if available, are put in the 'error' key of
     * this object.
     * @return {?Object}
     */
    getSyncStateData() {
        return this.syncStateData;
    }
    recoverFromSyncStartupError(savedSyncPromise, err) {
        return __awaiter(this, void 0, void 0, function* () {
            // Wait for the saved sync to complete - we send the pushrules and filter requests
            // before the saved sync has finished so they can run in parallel, but only process
            // the results after the saved sync is done. Equivalently, we wait for it to finish
            // before reporting failures from these functions.
            yield savedSyncPromise;
            const keepaliveProm = this.startKeepAlives();
            this.updateSyncState(sync_api_1.SyncState.Error, { error: err });
            yield keepaliveProm;
        });
    }
    /**
     * Is the lazy loading option different than in previous session?
     * @param {boolean} lazyLoadMembers current options for lazy loading
     * @return {boolean} whether or not the option has changed compared to the previous session */
    wasLazyLoadingToggled(lazyLoadMembers = false) {
        return __awaiter(this, void 0, void 0, function* () {
            // assume it was turned off before
            // if we don't know any better
            let lazyLoadMembersBefore = false;
            const isStoreNewlyCreated = yield this.client.store.isNewlyCreated();
            if (!isStoreNewlyCreated) {
                const prevClientOptions = yield this.client.store.getClientOptions();
                if (prevClientOptions) {
                    lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers;
                }
                return lazyLoadMembersBefore !== lazyLoadMembers;
            }
            return false;
        });
    }
    shouldAbortSync(error) {
        if (error.errcode === "M_UNKNOWN_TOKEN") {
            // The logout already happened, we just need to stop.
            logger_1.logger.warn("Token no longer valid - assuming logout");
            this.stop();
            return true;
        }
        return false;
    }
    /**
     * Main entry point
     */
    sync() {
        const client = this.client;
        this.running = true;
        if (global.window && global.window.addEventListener) {
            global.window.addEventListener("online", this.onOnline, false);
        }
        let savedSyncPromise = Promise.resolve();
        let savedSyncToken = null;
        // We need to do one-off checks before we can begin the /sync loop.
        // These are:
        //   1) We need to get push rules so we can check if events should bing as we get
        //      them from /sync.
        //   2) We need to get/create a filter which we can use for /sync.
        //   3) We need to check the lazy loading option matches what was used in the
        //       stored sync. If it doesn't, we can't use the stored sync.
        const getPushRules = () => __awaiter(this, void 0, void 0, function* () {
            try {
                debuglog("Getting push rules...");
                const result = yield client.getPushRules();
                debuglog("Got push rules");
                client.pushRules = result;
            }
            catch (err) {
                logger_1.logger.error("Getting push rules failed", err);
                if (this.shouldAbortSync(err))
                    return;
                // wait for saved sync to complete before doing anything else,
                // otherwise the sync state will end up being incorrect
                debuglog("Waiting for saved sync before retrying push rules...");
                yield this.recoverFromSyncStartupError(savedSyncPromise, err);
                getPushRules();
                return;
            }
            checkLazyLoadStatus(); // advance to the next stage
        });
        const buildDefaultFilter = () => {
            const filter = new filter_1.Filter(client.credentials.userId);
            filter.setTimelineLimit(this.opts.initialSyncLimit);
            return filter;
        };
        const checkLazyLoadStatus = () => __awaiter(this, void 0, void 0, function* () {
            debuglog("Checking lazy load status...");
            if (this.opts.lazyLoadMembers && client.isGuest()) {
                this.opts.lazyLoadMembers = false;
            }
            if (this.opts.lazyLoadMembers) {
                debuglog("Checking server lazy load support...");
                const supported = yield client.doesServerSupportLazyLoading();
                if (supported) {
                    debuglog("Enabling lazy load on sync filter...");
                    if (!this.opts.filter) {
                        this.opts.filter = buildDefaultFilter();
                    }
                    this.opts.filter.setLazyLoadMembers(true);
                }
                else {
                    debuglog("LL: lazy loading requested but not supported " +
                        "by server, so disabling");
                    this.opts.lazyLoadMembers = false;
                }
            }
            // need to vape the store when enabling LL and wasn't enabled before
            debuglog("Checking whether lazy loading has changed in store...");
            const shouldClear = yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers);
            if (shouldClear) {
                this.storeIsInvalid = true;
                const reason = errors_1.InvalidStoreError.TOGGLED_LAZY_LOADING;
                const error = new errors_1.InvalidStoreError(reason, !!this.opts.lazyLoadMembers);
                this.updateSyncState(sync_api_1.SyncState.Error, { error });
                // bail out of the sync loop now: the app needs to respond to this error.
                // we leave the state as 'ERROR' which isn't great since this normally means
                // we're retrying. The client must be stopped before clearing the stores anyway
                // so the app should stop the client, clear the store and start it again.
                logger_1.logger.warn("InvalidStoreError: store is not usable: stopping sync.");
                return;
            }
            if (this.opts.lazyLoadMembers && this.opts.crypto) {
                this.opts.crypto.enableLazyLoading();
            }
            try {
                debuglog("Storing client options...");
                yield this.client.storeClientOptions();
                debuglog("Stored client options");
            }
            catch (err) {
                logger_1.logger.error("Storing client options failed", err);
                throw err;
            }
            getFilter(); // Now get the filter and start syncing
        });
        const getFilter = () => __awaiter(this, void 0, void 0, function* () {
            debuglog("Getting filter...");
            let filter;
            if (this.opts.filter) {
                filter = this.opts.filter;
            }
            else {
                filter = buildDefaultFilter();
            }
            let filterId;
            try {
                filterId = yield client.getOrCreateFilter(getFilterName(client.credentials.userId), filter);
            }
            catch (err) {
                logger_1.logger.error("Getting filter failed", err);
                if (this.shouldAbortSync(err))
                    return;
                // wait for saved sync to complete before doing anything else,
                // otherwise the sync state will end up being incorrect
                debuglog("Waiting for saved sync before retrying filter...");
                yield this.recoverFromSyncStartupError(savedSyncPromise, err);
                getFilter();
                return;
            }
            // reset the notifications timeline to prepare it to paginate from
            // the current point in time.
            // The right solution would be to tie /sync pagination tokens into
            // /notifications API somehow.
            client.resetNotifTimelineSet();
            if (this.currentSyncRequest === null) {
                // Send this first sync request here so we can then wait for the saved
                // sync data to finish processing before we process the results of this one.
                debuglog("Sending first sync request...");
                this.currentSyncRequest = this.doSyncRequest({ filterId }, savedSyncToken);
            }
            // Now wait for the saved sync to finish...
            debuglog("Waiting for saved sync before starting sync processing...");
            yield savedSyncPromise;
            this._sync({ filterId });
        });
        if (client.isGuest()) {
            // no push rules for guests, no access to POST filter for guests.
            this._sync({});
        }
        else {
            // Pull the saved sync token out first, before the worker starts sending
            // all the sync data which could take a while. This will let us send our
            // first incremental sync request before we've processed our saved data.
            debuglog("Getting saved sync token...");
            savedSyncPromise = client.store.getSavedSyncToken().then((tok) => {
                debuglog("Got saved sync token");
                savedSyncToken = tok;
                debuglog("Getting saved sync...");
                return client.store.getSavedSync();
            }).then((savedSync) => {
                debuglog(`Got reply from saved sync, exists? ${!!savedSync}`);
                if (savedSync) {
                    return this.syncFromCache(savedSync);
                }
            }).catch(err => {
                logger_1.logger.error("Getting saved sync failed", err);
            });
            // Now start the first incremental sync request: this can also
            // take a while so if we set it going now, we can wait for it
            // to finish while we process our saved sync data.
            getPushRules();
        }
    }
    /**
     * Stops the sync object from syncing.
     */
    stop() {
        debuglog("SyncApi.stop");
        if (global.window) {
            global.window.removeEventListener("online", this.onOnline, false);
        }
        this.running = false;
        if (this.currentSyncRequest) {
            this.currentSyncRequest.abort();
        }
        if (this.keepAliveTimer) {
            clearTimeout(this.keepAliveTimer);
            this.keepAliveTimer = null;
        }
    }
    /**
     * Retry a backed off syncing request immediately. This should only be used when
     * the user <b>explicitly</b> attempts to retry their lost connection.
     * @return {boolean} True if this resulted in a request being retried.
     */
    retryImmediately() {
        if (!this.connectionReturnedDefer) {
            return false;
        }
        this.startKeepAlives(0);
        return true;
    }
    /**
     * Process a single set of cached sync data.
     * @param {Object} savedSync a saved sync that was persisted by a store. This
     * should have been acquired via client.store.getSavedSync().
     */
    syncFromCache(savedSync) {
        return __awaiter(this, void 0, void 0, function* () {
            debuglog("sync(): not doing HTTP hit, instead returning stored /sync data");
            const nextSyncToken = savedSync.nextBatch;
            // Set sync token for future incremental syncing
            this.client.store.setSyncToken(nextSyncToken);
            // No previous sync, set old token to null
            const syncEventData = {
                oldSyncToken: null,
                nextSyncToken,
                catchingUp: false,
                fromCache: true,
            };
            const data = {
                next_batch: nextSyncToken,
                rooms: savedSync.roomsData,
                groups: savedSync.groupsData,
                account_data: {
                    events: savedSync.accountData,
                },
            };
            try {
                yield this.processSyncResponse(syncEventData, data);
            }
            catch (e) {
                logger_1.logger.error("Error processing cached sync", e.stack || e);
            }
            // Don't emit a prepared if we've bailed because the store is invalid:
            // in this case the client will not be usable until stopped & restarted
            // so this would be useless and misleading.
            if (!this.storeIsInvalid) {
                this.updateSyncState(sync_api_1.SyncState.Prepared, syncEventData);
            }
        });
    }
    /**
     * Invoke me to do /sync calls
     * @param {Object} syncOptions
     * @param {string} syncOptions.filterId
     * @param {boolean} syncOptions.hasSyncedBefore
     */
    _sync(syncOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const client = this.client;
            if (!this.running) {
                debuglog("Sync no longer running: exiting.");
                if (this.connectionReturnedDefer) {
                    this.connectionReturnedDefer.reject();
                    this.connectionReturnedDefer = null;
                }
                this.updateSyncState(sync_api_1.SyncState.Stopped);
                return;
            }
            const syncToken = client.store.getSyncToken();
            let data;
            try {
                //debuglog('Starting sync since=' + syncToken);
                if (this.currentSyncRequest === null) {
                    this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken);
                }
                data = yield this.currentSyncRequest;
            }
            catch (e) {
                this.onSyncError(e, syncOptions);
                return;
            }
            finally {
                this.currentSyncRequest = null;
            }
            //debuglog('Completed sync, next_batch=' + data.next_batch);
            // set the sync token NOW *before* processing the events. We do this so
            // if something barfs on an event we can skip it rather than constantly
            // polling with the same token.
            client.store.setSyncToken(data.next_batch);
            // Reset after a successful sync
            this.failedSyncCount = 0;
            yield client.store.setSyncData(data);
            const syncEventData = {
                oldSyncToken: syncToken,
                nextSyncToken: data.next_batch,
                catchingUp: this.catchingUp,
            };
            if (this.opts.crypto) {
                // tell the crypto module we're about to process a sync
                // response
                yield this.opts.crypto.onSyncWillProcess(syncEventData);
            }
            try {
                yield this.processSyncResponse(syncEventData, data);
            }
            catch (e) {
                // log the exception with stack if we have it, else fall back
                // to the plain description
                logger_1.logger.error("Caught /sync error", e.stack || e);
                // Emit the exception for client handling
                this.client.emit("sync.unexpectedError", e);
            }
            // update this as it may have changed
            syncEventData.catchingUp = this.catchingUp;
            // emit synced events
            if (!syncOptions.hasSyncedBefore) {
                this.updateSyncState(sync_api_1.SyncState.Prepared, syncEventData);
                syncOptions.hasSyncedBefore = true;
            }
            // tell the crypto module to do its processing. It may block (to do a
            // /keys/changes request).
            if (this.opts.crypto) {
                yield this.opts.crypto.onSyncCompleted(syncEventData);
            }
            // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates
            this.updateSyncState(sync_api_1.SyncState.Syncing, syncEventData);
            if (client.store.wantsSave()) {
                // We always save the device list (if it's dirty) before saving the sync data:
                // this means we know the saved device list data is at least as fresh as the
                // stored sync data which means we don't have to worry that we may have missed
                // device changes. We can also skip the delay since we're not calling this very
                // frequently (and we don't really want to delay the sync for it).
                if (this.opts.crypto) {
                    yield this.opts.crypto.saveDeviceList(0);
                }
                // tell databases that everything is now in a consistent state and can be saved.
                client.store.save();
            }
            // Begin next sync
            this._sync(syncOptions);
        });
    }
    doSyncRequest(syncOptions, syncToken) {
        const qps = this.getSyncParams(syncOptions, syncToken);
        return this.client.http.authedRequest(undefined, "GET", "/sync", qps, undefined, qps.timeout + BUFFER_PERIOD_MS);
    }
    getSyncParams(syncOptions, syncToken) {
        let pollTimeout = this.opts.pollTimeout;
        if (this.getSyncState() !== 'SYNCING' || this.catchingUp) {
            // unless we are happily syncing already, we want the server to return
            // as quickly as possible, even if there are no events queued. This
            // serves two purposes:
            //
            // * When the connection dies, we want to know asap when it comes back,
            //   so that we can hide the error from the user. (We don't want to
            //   have to wait for an event or a timeout).
            //
            // * We want to know if the server has any to_device messages queued up
            //   for us. We do that by calling it with a zero timeout until it
            //   doesn't give us any more to_device messages.
            this.catchingUp = true;
            pollTimeout = 0;
        }
        let filterId = syncOptions.filterId;
        if (this.client.isGuest() && !filterId) {
            filterId = this.getGuestFilter();
        }
        const qps = {
            filter: filterId,
            timeout: pollTimeout,
        };
        if (this.opts.disablePresence) {
            qps.set_presence = "offline";
        }
        if (syncToken) {
            qps.since = syncToken;
        }
        else {
            // use a cachebuster for initialsyncs, to make sure that
            // we don't get a stale sync
            // (https://github.com/vector-im/vector-web/issues/1354)
            qps._cacheBuster = Date.now();
        }
        if (this.getSyncState() == 'ERROR' || this.getSyncState() == 'RECONNECTING') {
            // we think the connection is dead. If it comes back up, we won't know
            // about it till /sync returns. If the timeout= is high, this could
            // be a long time. Set it to 0 when doing retries so we don't have to wait
            // for an event or a timeout before emiting the SYNCING event.
            qps.timeout = 0;
        }
        return qps;
    }
    onSyncError(err, syncOptions) {
        if (!this.running) {
            debuglog("Sync no longer running: exiting");
            if (this.connectionReturnedDefer) {
                this.connectionReturnedDefer.reject();
                this.connectionReturnedDefer = null;
            }
            this.updateSyncState(sync_api_1.SyncState.Stopped);
            return;
        }
        logger_1.logger.error("/sync error %s", err);
        logger_1.logger.error(err);
        if (this.shouldAbortSync(err)) {
            return;
        }
        this.failedSyncCount++;
        logger_1.logger.log('Number of consecutive failed sync requests:', this.failedSyncCount);
        debuglog("Starting keep-alive");
        // Note that we do *not* mark the sync connection as
        // lost yet: we only do this if a keepalive poke
        // fails, since long lived HTTP connections will
        // go away sometimes and we shouldn't treat this as
        // erroneous. We set the state to 'reconnecting'
        // instead, so that clients can observe this state
        // if they wish.
        this.startKeepAlives().then((connDidFail) => {
            // Only emit CATCHUP if we detected a connectivity error: if we didn't,
            // it's quite likely the sync will fail again for the same reason and we
            // want to stay in ERROR rather than keep flip-flopping between ERROR
            // and CATCHUP.
            if (connDidFail && this.getSyncState() === sync_api_1.SyncState.Error) {
                this.updateSyncState(sync_api_1.SyncState.Catchup, {
                    oldSyncToken: null,
                    nextSyncToken: null,
                    catchingUp: true,
                });
            }
            this._sync(syncOptions);
        });
        this.currentSyncRequest = null;
        // Transition from RECONNECTING to ERROR after a given number of failed syncs
        this.updateSyncState(this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ?
            sync_api_1.SyncState.Error : sync_api_1.SyncState.Reconnecting, { error: err });
    }
    /**
     * Process data returned from a sync response and propagate it
     * into the model objects
     *
     * @param {Object} syncEventData Object containing sync tokens associated with this sync
     * @param {Object} data The response from /sync
     */
    processSyncResponse(syncEventData, data) {
        return __awaiter(this, void 0, void 0, function* () {
            const client = this.client;
            // data looks like:
            // {
            //    next_batch: $token,
            //    presence: { events: [] },
            //    account_data: { events: [] },
            //    device_lists: { changed: ["@user:server", ... ]},
            //    to_device: { events: [] },
            //    device_one_time_keys_count: { signed_curve25519: 42 },
            //    rooms: {
            //      invite: {
            //        $roomid: {
            //          invite_state: { events: [] }
            //        }
            //      },
            //      join: {
            //        $roomid: {
            //          state: { events: [] },
            //          timeline: { events: [], prev_batch: $token, limited: true },
            //          ephemeral: { events: [] },
            //          summary: {
            //             m.heroes: [ $user_id ],
            //             m.joined_member_count: $count,
            //             m.invited_member_count: $count
            //          },
            //          account_data: { events: [] },
            //          unread_notifications: {
            //              highlight_count: 0,
            //              notification_count: 0,
            //          }
            //        }
            //      },
            //      leave: {
            //        $roomid: {
            //          state: { events: [] },
            //          timeline: { events: [], prev_batch: $token }
            //        }
            //      }
            //    },
            //    groups: {
            //        invite: {
            //            $groupId: {
            //                inviter: $inviter,
            //                profile: {
            //                    avatar_url: $avatarUrl,
            //                    name: $groupName,
            //                },
            //            },
            //        },
            //        join: {},
            //        leave: {},
            //    },
            // }
            // TODO-arch:
            // - Each event we pass through needs to be emitted via 'event', can we
            //   do this in one place?
            // - The isBrandNewRoom boilerplate is boilerplatey.
            // handle presence events (User objects)
            if (data.presence && Array.isArray(data.presence.events)) {
                data.presence.events.map(client.getEventMapper()).forEach(function (presenceEvent) {
                    let user = client.store.getUser(presenceEvent.getSender());
                    if (user) {
                        user.setPresenceEvent(presenceEvent);
                    }
                    else {
                        user = createNewUser(client, presenceEvent.getSender());
                        user.setPresenceEvent(presenceEvent);
                        client.store.storeUser(user);
                    }
                    client.emit("event", presenceEvent);
                });
            }
            // handle non-room account_data
            if (data.account_data && Array.isArray(data.account_data.events)) {
                const events = data.account_data.events.map(client.getEventMapper());
                const prevEventsMap = events.reduce((m, c) => {
                    m[c.getId()] = client.store.getAccountData(c.getType());
                    return m;
                }, {});
                client.store.storeAccountDataEvents(events);
                events.forEach(function (accountDataEvent) {
                    // Honour push rules that come down the sync stream but also
                    // honour push rules that were previously cached. Base rules
                    // will be updated when we receive push rules via getPushRules
                    // (see sync) before syncing over the network.
                    if (accountDataEvent.getType() === 'm.push_rules') {
                        const rules = accountDataEvent.getContent();
                        client.pushRules = pushprocessor_1.PushProcessor.rewriteDefaultRules(rules);
                    }
                    const prevEvent = prevEventsMap[accountDataEvent.getId()];
                    client.emit("accountData", accountDataEvent, prevEvent);
                    return accountDataEvent;
                });
            }
            // handle to-device events
            if (data.to_device && Array.isArray(data.to_device.events) &&
                data.to_device.events.length > 0) {
                const cancelledKeyVerificationTxns = [];
                data.to_device.events
                    .map(client.getEventMapper())
                    .map((toDeviceEvent) => {
                    // We want to flag m.key.verification.start events as cancelled
                    // if there's an accompanying m.key.verification.cancel event, so
                    // we pull out the transaction IDs from the cancellation events
                    // so we can flag the verification events as cancelled in the loop
                    // below.
                    if (toDeviceEvent.getType() === "m.key.verification.cancel") {
                        const txnId = toDeviceEvent.getContent()['transaction_id'];
                        if (txnId) {
                            cancelledKeyVerificationTxns.push(txnId);
                        }
                    }
                    // as mentioned above, .map is a cheap inline forEach, so return
                    // the unmodified event.
                    return toDeviceEvent;
                })
                    .forEach(function (toDeviceEvent) {
                    const content = toDeviceEvent.getContent();
                    if (toDeviceEvent.getType() == "m.room.message" &&
                        content.msgtype == "m.bad.encrypted") {
                        // the mapper already logged a warning.
                        logger_1.logger.log('Ignoring undecryptable to-device event from ' +
                            toDeviceEvent.getSender());
                        return;
                    }
                    if (toDeviceEvent.getType() === "m.key.verification.start"
                        || toDeviceEvent.getType() === "m.key.verification.request") {
                        const txnId = content['transaction_id'];
                        if (cancelledKeyVerificationTxns.includes(txnId)) {
                            toDeviceEvent.flagCancelled();
                        }
                    }
                    client.emit("toDeviceEvent", toDeviceEvent);
                });
            }
            else {
                // no more to-device events: we can stop polling with a short timeout.
                this.catchingUp = false;
            }
            if (data.groups) {
                if (data.groups.invite) {
                    this.processGroupSyncEntry(data.groups.invite, sync_accumulator_1.Category.Invite);
                }
                if (data.groups.join) {
                    this.processGroupSyncEntry(data.groups.join, sync_accumulator_1.Category.Join);
                }
                if (data.groups.leave) {
                    this.processGroupSyncEntry(data.groups.leave, sync_accumulator_1.Category.Leave);
                }
            }
            // the returned json structure is a bit crap, so make it into a
            // nicer form (array) after applying sanity to make sure we don't fail
            // on missing keys (on the off chance)
            let inviteRooms = [];
            let joinRooms = [];
            let leaveRooms = [];
            if (data.rooms) {
                if (data.rooms.invite) {
                    inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite);
                }
                if (data.rooms.join) {
                    joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join);
                }
                if (data.rooms.leave) {
                    leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);
                }
            }
            this.notifEvents = [];
            // Handle invites
            inviteRooms.forEach((inviteObj) => {
                const room = inviteObj.room;
                const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room);
                this.processRoomEvents(room, stateEvents);
                if (inviteObj.isBrandNewRoom) {
                    room.recalculate();
                    client.store.storeRoom(room);
                    client.emit("Room", room);
                }
                stateEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                room.updateMyMembership("invite");
            });
            // Handle joins
            yield utils.promiseMapSeries(joinRooms, (joinObj) => __awaiter(this, void 0, void 0, function* () {
                const room = joinObj.room;
                const stateEvents = this.mapSyncEventsFormat(joinObj.state, room);
                // Prevent events from being decrypted ahead of time
                // this helps large account to speed up faster
                // room::decryptCriticalEvent is in charge of decrypting all the events
                // required for a client to function properly
                const timelineEvents = this.mapSyncEventsFormat(joinObj.timeline, room, false);
                const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral);
                const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data);
                const encrypted = client.isRoomEncrypted(room.roomId);
                // we do this first so it's correct when any of the events fire
                if (joinObj.unread_notifications) {
                    room.setUnreadNotificationCount(room_1.NotificationCountType.Total, joinObj.unread_notifications.notification_count);
                    // We track unread notifications ourselves in encrypted rooms, so don't
                    // bother setting it here. We trust our calculations better than the
                    // server's for this case, and therefore will assume that our non-zero
                    // count is accurate.
                    if (!encrypted
                        || (encrypted && room.getUnreadNotificationCount(room_1.NotificationCountType.Highlight) <= 0)) {
                        room.setUnreadNotificationCount(room_1.NotificationCountType.Highlight, joinObj.unread_notifications.highlight_count);
                    }
                }
                joinObj.timeline = joinObj.timeline || {};
                if (joinObj.isBrandNewRoom) {
                    // set the back-pagination token. Do this *before* adding any
                    // events so that clients can start back-paginating.
                    room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, event_timeline_1.EventTimeline.BACKWARDS);
                }
                else if (joinObj.timeline.limited) {
                    let limited = true;
                    // we've got a limited sync, so we *probably* have a gap in the
                    // timeline, so should reset. But we might have been peeking or
                    // paginating and already have some of the events, in which
                    // case we just want to append any subsequent events to the end
                    // of the existing timeline.
                    //
                    // This is particularly important in the case that we already have
                    // *all* of the events in the timeline - in that case, if we reset
                    // the timeline, we'll end up with an entirely empty timeline,
                    // which we'll try to paginate but not get any new events (which
                    // will stop us linking the empty timeline into the chain).
                    //
                    for (let i = timelineEvents.length - 1; i >= 0; i--) {
                        const eventId = timelineEvents[i].getId();
                        if (room.getTimelineForEvent(eventId)) {
                            debuglog("Already have event " + eventId + " in limited " +
                                "sync - not resetting");
                            limited = false;
                            // we might still be missing some of the events before i;
                            // we don't want to be adding them to the end of the
                            // timeline because that would put them out of order.
                            timelineEvents.splice(0, i);
                            // XXX: there's a problem here if the skipped part of the
                            // timeline modifies the state set in stateEvents, because
                            // we'll end up using the state from stateEvents rather
                            // than the later state from timelineEvents. We probably
                            // need to wind stateEvents forward over the events we're
                            // skipping.
                            break;
                        }
                    }
                    if (limited) {
                        this.deregisterStateListeners(room);
                        room.resetLiveTimeline(joinObj.timeline.prev_batch, this.opts.canResetEntireTimeline(room.roomId) ?
                            null : syncEventData.oldSyncToken);
                        // We have to assume any gap in any timeline is
                        // reason to stop incrementally tracking notifications and
                        // reset the timeline.
                        client.resetNotifTimelineSet();
                        this.registerStateListeners(room);
                    }
                }
                this.processRoomEvents(room, stateEvents, timelineEvents, syncEventData.fromCache);
                // set summary after processing events,
                // because it will trigger a name calculation
                // which needs the room state to be up to date
                if (joinObj.summary) {
                    room.setSummary(joinObj.summary);
                }
                // we deliberately don't add ephemeral events to the timeline
                room.addEphemeralEvents(ephemeralEvents);
                // we deliberately don't add accountData to the timeline
                room.addAccountData(accountDataEvents);
                room.recalculate();
                if (joinObj.isBrandNewRoom) {
                    client.store.storeRoom(room);
                    client.emit("Room", room);
                }
                this.processEventsForNotifs(room, timelineEvents);
                const processRoomEvent = (e) => __awaiter(this, void 0, void 0, function* () {
                    client.emit("event", e);
                    if (e.isState() && e.getType() == "m.room.encryption" && this.opts.crypto) {
                        yield this.opts.crypto.onCryptoEvent(e);
                    }
                    if (e.isState() && e.getType() === "im.vector.user_status") {
                        let user = client.store.getUser(e.getStateKey());
                        if (user) {
                            user.unstable_updateStatusMessage(e);
                        }
                        else {
                            user = createNewUser(client, e.getStateKey());
                            user.unstable_updateStatusMessage(e);
                            client.store.storeUser(user);
                        }
                    }
                });
                yield utils.promiseMapSeries(stateEvents, processRoomEvent);
                yield utils.promiseMapSeries(timelineEvents, processRoomEvent);
                ephemeralEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                accountDataEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                room.updateMyMembership("join");
                // Decrypt only the last message in all rooms to make sure we can generate a preview
                // And decrypt all events after the recorded read receipt to ensure an accurate
                // notification count
                room.decryptCriticalEvents();
            }));
            // Handle leaves (e.g. kicked rooms)
            leaveRooms.forEach((leaveObj) => {
                const room = leaveObj.room;
                const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);
                const timelineEvents = this.mapSyncEventsFormat(leaveObj.timeline, room);
                const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data);
                this.processRoomEvents(room, stateEvents, timelineEvents);
                room.addAccountData(accountDataEvents);
                room.recalculate();
                if (leaveObj.isBrandNewRoom) {
                    client.store.storeRoom(room);
                    client.emit("Room", room);
                }
                this.processEventsForNotifs(room, timelineEvents);
                stateEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                timelineEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                accountDataEvents.forEach(function (e) {
                    client.emit("event", e);
                });
                room.updateMyMembership("leave");
            });
            // update the notification timeline, if appropriate.
            // we only do this for live events, as otherwise we can't order them sanely
            // in the timeline relative to ones paginated in by /notifications.
            // XXX: we could fix this by making EventTimeline support chronological
            // ordering... but it doesn't, right now.
            if (syncEventData.oldSyncToken && this.notifEvents.length) {
                this.notifEvents.sort(function (a, b) {
                    return a.getTs() - b.getTs();
                });
                this.notifEvents.forEach(function (event) {
                    client.getNotifTimelineSet().addLiveEvent(event);
                });
            }
            // Handle device list updates
            if (data.device_lists) {
                if (this.opts.crypto) {
                    yield this.opts.crypto.handleDeviceListChanges(syncEventData, data.device_lists);
                }
                else {
                    // FIXME if we *don't* have a crypto module, we still need to
                    // invalidate the device lists. But that would require a
                    // substantial bit of rework :/.
                }
            }
            // Handle one_time_keys_count
            if (this.opts.crypto && data.device_one_time_keys_count) {
                const currentCount = data.device_one_time_keys_count.signed_curve25519 || 0;
                this.opts.crypto.updateOneTimeKeyCount(currentCount);
            }
            if (this.opts.crypto && data["org.matrix.msc2732.device_unused_fallback_key_types"]) {
                // The presence of device_unused_fallback_key_types indicates that the
                // server supports fallback keys. If there's no unused
                // signed_curve25519 fallback key we need a new one.
                const unusedFallbackKeys = data["org.matrix.msc2732.device_unused_fallback_key_types"];
                this.opts.crypto.setNeedsNewFallback(unusedFallbackKeys instanceof Array &&
                    !unusedFallbackKeys.includes("signed_curve25519"));
            }
        });
    }
    /**
     * Starts polling the connectivity check endpoint
     * @param {number} delay How long to delay until the first poll.
     *        defaults to a short, randomised interval (to prevent
     *        tightlooping if /versions succeeds but /sync etc. fail).
     * @return {promise} which resolves once the connection returns
     */
    startKeepAlives(delay) {
        if (delay === undefined) {
            delay = 2000 + Math.floor(Math.random() * 5000);
        }
        if (this.keepAliveTimer !== null) {
            clearTimeout(this.keepAliveTimer);
        }
        if (delay > 0) {
            this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);
        }
        else {
            this.pokeKeepAlive();
        }
        if (!this.connectionReturnedDefer) {
            this.connectionReturnedDefer = utils.defer();
        }
        return this.connectionReturnedDefer.promise;
    }
    /**
     * Make a dummy call to /_matrix/client/versions, to see if the HS is
     * reachable.
     *
     * On failure, schedules a call back to itself. On success, resolves
     * this.connectionReturnedDefer.
     *
     * @param {boolean} connDidFail True if a connectivity failure has been detected. Optional.
     */
    pokeKeepAlive(connDidFail = false) {
        const success = () => {
            clearTimeout(this.keepAliveTimer);
            if (this.connectionReturnedDefer) {
                this.connectionReturnedDefer.resolve(connDidFail);
                this.connectionReturnedDefer = null;
            }
        };
        this.client.http.request(undefined, // callback
        "GET", "/_matrix/client/versions", undefined, // queryParams
        undefined, // data
        {
            prefix: '',
            localTimeoutMs: 15 * 1000,
        }).then(() => {
            success();
        }, (err) => {
            if (err.httpStatus == 400 || err.httpStatus == 404) {
                // treat this as a success because the server probably just doesn't
                // support /versions: point is, we're getting a response.
                // We wait a short time though, just in case somehow the server
                // is in a mode where it 400s /versions responses and sync etc.
                // responses fail, this will mean we don't hammer in a loop.
                this.keepAliveTimer = setTimeout(success, 2000);
            }
            else {
                connDidFail = true;
                this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this, connDidFail), 5000 + Math.floor(Math.random() * 5000));
                // A keepalive has failed, so we emit the
                // error state (whether or not this is the
                // first failure).
                // Note we do this after setting the timer:
                // this lets the unit tests advance the mock
                // clock when they get the error.
                this.updateSyncState(sync_api_1.SyncState.Error, { error: err });
            }
        });
    }
    /**
     * @param {Object} groupsSection Groups section object, eg. response.groups.invite
     * @param {string} sectionName Which section this is ('invite', 'join' or 'leave')
     */
    processGroupSyncEntry(groupsSection, sectionName) {
        // Processes entries from 'groups' section of the sync stream
        for (const groupId of Object.keys(groupsSection)) {
            const groupInfo = groupsSection[groupId];
            let group = this.client.store.getGroup(groupId);
            const isBrandNew = group === null;
            if (group === null) {
                group = this.createGroup(groupId);
            }
            if (groupInfo.profile) {
                group.setProfile(groupInfo.profile.name, groupInfo.profile.avatar_url);
            }
            if (groupInfo.inviter) {
                group.setInviter({ userId: groupInfo.inviter });
            }
            group.setMyMembership(sectionName);
            if (isBrandNew) {
                // Now we've filled in all the fields, emit the Group event
                this.client.emit("Group", group);
            }
        }
    }
    /**
     * @param {Object} obj
     * @return {Object[]}
     */
    mapSyncResponseToRoomArray(obj) {
        // Maps { roomid: {stuff}, roomid: {stuff} }
        // to
        // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]
        const client = this.client;
        return Object.keys(obj).map((roomId) => {
            const arrObj = obj[roomId];
            let room = client.store.getRoom(roomId);
            let isBrandNewRoom = false;
            if (!room) {
                room = this.createRoom(roomId);
                isBrandNewRoom = true;
            }
            arrObj.room = room;
            arrObj.isBrandNewRoom = isBrandNewRoom;
            return arrObj;
        });
    }
    /**
     * @param {Object} obj
     * @param {Room} room
     * @param {boolean} decrypt
     * @return {MatrixEvent[]}
     */
    mapSyncEventsFormat(obj, room, decrypt = true) {
        if (!obj || !Array.isArray(obj.events)) {
            return [];
        }
        const mapper = this.client.getEventMapper({ decrypt });
        return obj.events.map(function (e) {
            if (room) {
                e["room_id"] = room.roomId;
            }
            return mapper(e);
        });
    }
    /**
     * @param {Room} room
     */
    resolveInvites(room) {
        if (!room || !this.opts.resolveInvitesToProfiles) {
            return;
        }
        const client = this.client;
        // For each invited room member we want to give them a displayname/avatar url
        // if they have one (the m.room.member invites don't contain this).
        room.getMembersWithMembership("invite").forEach(function (member) {
            if (member._requestedProfileInfo)
                return;
            member._requestedProfileInfo = true;
            // try to get a cached copy first.
            const user = client.getUser(member.userId);
            let promise;
            if (user) {
                promise = Promise.resolve({
                    avatar_url: user.avatarUrl,
                    displayname: user.displayName,
                });
            }
            else {
                promise = client.getProfileInfo(member.userId);
            }
            promise.then(function (info) {
                // slightly naughty by doctoring the invite event but this means all
                // the code paths remain the same between invite/join display name stuff
                // which is a worthy trade-off for some minor pollution.
                const inviteEvent = member.events.member;
                if (inviteEvent.getContent().membership !== "invite") {
                    // between resolving and now they have since joined, so don't clobber
                    return;
                }
                inviteEvent.getContent().avatar_url = info.avatar_url;
                inviteEvent.getContent().displayname = info.displayname;
                // fire listeners
                member.setMembershipEvent(inviteEvent, room.currentState);
            }, function (err) {
                // OH WELL.
            });
        });
    }
    /**
     * @param {Room} room
     * @param {MatrixEvent[]} stateEventList A list of state events. This is the state
     * at the *START* of the timeline list if it is supplied.
     * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index
     * @param {boolean} fromCache whether the sync response came from cache
     * is earlier in time. Higher index is later.
     */
    processRoomEvents(room, stateEventList, timelineEventList, fromCache = false) {
        // If there are no events in the timeline yet, initialise it with
        // the given state events
        const liveTimeline = room.getLiveTimeline();
        const timelineWasEmpty = liveTimeline.getEvents().length == 0;
        if (timelineWasEmpty) {
            // Passing these events into initialiseState will freeze them, so we need
            // to compute and cache the push actions for them now, otherwise sync dies
            // with an attempt to assign to read only property.
            // XXX: This is pretty horrible and is assuming all sorts of behaviour from
            // these functions that it shouldn't be. We should probably either store the
            // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise
            // find some solution where MatrixEvents are immutable but allow for a cache
            // field.
            for (const ev of stateEventList) {
                this.client.getPushActionsForEvent(ev);
            }
            liveTimeline.initialiseState(stateEventList);
        }
        this.resolveInvites(room);
        // recalculate the room name at this point as adding events to the timeline
        // may make notifications appear which should have the right name.
        // XXX: This looks suspect: we'll end up recalculating the room once here
        // and then again after adding events (processSyncResponse calls it after
        // calling us) even if no state events were added. It also means that if
        // one of the room events in timelineEventList is something that needs
        // a recalculation (like m.room.name) we won't recalculate until we've
        // finished adding all the events, which will cause the notification to have
        // the old room name rather than the new one.
        room.recalculate();
        // If the timeline wasn't empty, we process the state events here: they're
        // defined as updates to the state before the start of the timeline, so this
        // starts to roll the state forward.
        // XXX: That's what we *should* do, but this can happen if we were previously
        // peeking in a room, in which case we obviously do *not* want to add the
        // state events here onto the end of the timeline. Historically, the js-sdk
        // has just set these new state events on the old and new state. This seems
        // very wrong because there could be events in the timeline that diverge the
        // state, in which case this is going to leave things out of sync. However,
        // for now I think it;s best to behave the same as the code has done previously.
        if (!timelineWasEmpty) {
            // XXX: As above, don't do this...
            //room.addLiveEvents(stateEventList || []);
            // Do this instead...
            room.oldState.setStateEvents(stateEventList || []);
            room.currentState.setStateEvents(stateEventList || []);
        }
        // execute the timeline events. This will continue to diverge the current state
        // if the timeline has any state events in it.
        // This also needs to be done before running push rules on the events as they need
        // to be decorated with sender etc.
        room.addLiveEvents(timelineEventList || [], null, fromCache);
    }
    /**
     * Takes a list of timelineEvents and adds and adds to notifEvents
     * as appropriate.
     * This must be called after the room the events belong to has been stored.
     *
     * @param {Room} room
     * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index
     * is earlier in time. Higher index is later.
     */
    processEventsForNotifs(room, timelineEventList) {
        // gather our notifications into this.notifEvents
        if (this.client.getNotifTimelineSet()) {
            for (let i = 0; i < timelineEventList.length; i++) {
                const pushActions = this.client.getPushActionsForEvent(timelineEventList[i]);
                if (pushActions && pushActions.notify &&
                    pushActions.tweaks && pushActions.tweaks.highlight) {
                    this.notifEvents.push(timelineEventList[i]);
                }
            }
        }
    }
    /**
     * @return {string}
     */
    getGuestFilter() {
        // Dev note: This used to be conditional to return a filter of 20 events maximum, but
        // the condition never went to the other branch. This is now hardcoded.
        return "{}";
    }
    /**
     * Sets the sync state and emits an event to say so
     * @param {String} newState The new state string
     * @param {Object} data Object of additional data to emit in the event
     */
    updateSyncState(newState, data) {
        const old = this.syncState;
        this.syncState = newState;
        this.syncStateData = data;
        this.client.emit("sync", this.syncState, old, data);
    }
}
exports.SyncApi = SyncApi;
function createNewUser(client, userId) {
    const user = new user_1.User(userId);
    client.reEmitter.reEmit(user, [
        "User.avatarUrl", "User.displayName", "User.presence",
        "User.currentlyActive", "User.lastPresenceTs",
    ]);
    return user;
}

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./client":64,"./errors":99,"./filter":102,"./logger":106,"./models/event-timeline":112,"./models/group":114,"./models/room":119,"./models/user":121,"./pushprocessor":122,"./sync-accumulator":133,"./sync.api":134,"./utils":137}],136:[function(require,module,exports){
"use strict";
/*
Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimelineIndex = exports.TimelineWindow = void 0;
/** @module timeline-window */
const event_timeline_1 = require("./models/event-timeline");
const logger_1 = require("./logger");
/**
 * @private
 */
const DEBUG = false;
/**
 * @private
 */
const debuglog = DEBUG ? logger_1.logger.log.bind(logger_1.logger) : function () { };
/**
 * the number of times we ask the server for more events before giving up
 *
 * @private
 */
const DEFAULT_PAGINATE_LOOP_LIMIT = 5;
class TimelineWindow {
    /**
     * Construct a TimelineWindow.
     *
     * <p>This abstracts the separate timelines in a Matrix {@link
        * module:models/room|Room} into a single iterable thing. It keeps track of
     * the start and endpoints of the window, which can be advanced with the help
     * of pagination requests.
     *
     * <p>Before the window is useful, it must be initialised by calling {@link
        * module:timeline-window~TimelineWindow#load|load}.
     *
     * <p>Note that the window will not automatically extend itself when new events
     * are received from /sync; you should arrange to call {@link
        * module:timeline-window~TimelineWindow#paginate|paginate} on {@link
        * module:client~MatrixClient.event:"Room.timeline"|Room.timeline} events.
     *
     * @param {MatrixClient} client   MatrixClient to be used for context/pagination
     *   requests.
     *
     * @param {EventTimelineSet} timelineSet  The timelineSet to track
     *
     * @param {Object} [opts] Configuration options for this window
     *
     * @param {number} [opts.windowLimit = 1000] maximum number of events to keep
     *    in the window. If more events are retrieved via pagination requests,
     *    excess events will be dropped from the other end of the window.
     *
     * @constructor
     */
    constructor(client, timelineSet, opts = {}) {
        this.client = client;
        this.timelineSet = timelineSet;
        // these will be TimelineIndex objects; they delineate the 'start' and
        // 'end' of the window.
        //
        // start.index is inclusive; end.index is exclusive.
        this.start = null;
        this.end = null;
        this.eventCount = 0;
        this.windowLimit = opts.windowLimit || 1000;
    }
    /**
     * Initialise the window to point at a given event, or the live timeline
     *
     * @param {string} [initialEventId]   If given, the window will contain the
     *    given event
     * @param {number} [initialWindowSize = 20]   Size of the initial window
     *
     * @return {Promise}
     */
    load(initialEventId, initialWindowSize = 20) {
        // given an EventTimeline, find the event we were looking for, and initialise our
        // fields so that the event in question is in the middle of the window.
        const initFields = (timeline) => {
            let eventIndex;
            const events = timeline.getEvents();
            if (!initialEventId) {
                // we were looking for the live timeline: initialise to the end
                eventIndex = events.length;
            }
            else {
                for (let i = 0; i < events.length; i++) {
                    if (events[i].getId() == initialEventId) {
                        eventIndex = i;
                        break;
                    }
                }
                if (eventIndex === undefined) {
                    throw new Error("getEventTimeline result didn't include requested event");
                }
            }
            const endIndex = Math.min(events.length, eventIndex + Math.ceil(initialWindowSize / 2));
            const startIndex = Math.max(0, endIndex - initialWindowSize);
            this.start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());
            this.end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());
            this.eventCount = endIndex - startIndex;
        };
        // We avoid delaying the resolution of the promise by a reactor tick if
        // we already have the data we need, which is important to keep room-switching
        // feeling snappy.
        //
        if (initialEventId) {
            const timeline = this.timelineSet.getTimelineForEvent(initialEventId);
            if (timeline) {
                // hot-path optimization to save a reactor tick by replicating the sync check getTimelineForEvent does.
                initFields(timeline);
                return Promise.resolve(timeline);
            }
            const prom = this.client.getEventTimeline(this.timelineSet, initialEventId);
            return prom.then(initFields);
        }
        else {
            const tl = this.timelineSet.getLiveTimeline();
            initFields(tl);
            return Promise.resolve();
        }
    }
    /**
     * Get the TimelineIndex of the window in the given direction.
     *
     * @param {string} direction   EventTimeline.BACKWARDS to get the TimelineIndex
     * at the start of the window; EventTimeline.FORWARDS to get the TimelineIndex at
     * the end.
     *
     * @return {TimelineIndex} The requested timeline index if one exists, null
     * otherwise.
     */
    getTimelineIndex(direction) {
        if (direction == event_timeline_1.EventTimeline.BACKWARDS) {
            return this.start;
        }
        else if (direction == event_timeline_1.EventTimeline.FORWARDS) {
            return this.end;
        }
        else {
            throw new Error("Invalid direction '" + direction + "'");
        }
    }
    /**
     * Try to extend the window using events that are already in the underlying
     * TimelineIndex.
     *
     * @param {string} direction   EventTimeline.BACKWARDS to try extending it
     *   backwards; EventTimeline.FORWARDS to try extending it forwards.
     * @param {number} size   number of events to try to extend by.
     *
     * @return {boolean} true if the window was extended, false otherwise.
     */
    extend(direction, size) {
        const tl = this.getTimelineIndex(direction);
        if (!tl) {
            debuglog("TimelineWindow: no timeline yet");
            return false;
        }
        const count = (direction == event_timeline_1.EventTimeline.BACKWARDS) ?
            tl.retreat(size) : tl.advance(size);
        if (count) {
            this.eventCount += count;
            debuglog("TimelineWindow: increased cap by " + count +
                " (now " + this.eventCount + ")");
            // remove some events from the other end, if necessary
            const excess = this.eventCount - this.windowLimit;
            if (excess > 0) {
                this.unpaginate(excess, direction != event_timeline_1.EventTimeline.BACKWARDS);
            }
            return true;
        }
        return false;
    }
    /**
     * Check if this window can be extended
     *
     * <p>This returns true if we either have more events, or if we have a
     * pagination token which means we can paginate in that direction. It does not
     * necessarily mean that there are more events available in that direction at
     * this time.
     *
     * @param {string} direction   EventTimeline.BACKWARDS to check if we can
     *   paginate backwards; EventTimeline.FORWARDS to check if we can go forwards
     *
     * @return {boolean} true if we can paginate in the given direction
     */
    canPaginate(direction) {
        const tl = this.getTimelineIndex(direction);
        if (!tl) {
            debuglog("TimelineWindow: no timeline yet");
            return false;
        }
        if (direction == event_timeline_1.EventTimeline.BACKWARDS) {
            if (tl.index > tl.minIndex()) {
                return true;
            }
        }
        else {
            if (tl.index < tl.maxIndex()) {
                return true;
            }
        }
        return Boolean(tl.timeline.getNeighbouringTimeline(direction) ||
            tl.timeline.getPaginationToken(direction));
    }
    /**
     * Attempt to extend the window
     *
     * @param {string} direction   EventTimeline.BACKWARDS to extend the window
     *    backwards (towards older events); EventTimeline.FORWARDS to go forwards.
     *
     * @param {number} size   number of events to try to extend by. If fewer than this
     *    number are immediately available, then we return immediately rather than
     *    making an API call.
     *
     * @param {boolean} [makeRequest = true] whether we should make API calls to
     *    fetch further events if we don't have any at all. (This has no effect if
     *    the room already knows about additional events in the relevant direction,
     *    even if there are fewer than 'size' of them, as we will just return those
     *    we already know about.)
     *
     * @param {number} [requestLimit = 5] limit for the number of API requests we
     *    should make.
     *
     * @return {Promise} Resolves to a boolean which is true if more events
     *    were successfully retrieved.
     */
    paginate(direction, size, makeRequest = true, requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT) {
        // Either wind back the message cap (if there are enough events in the
        // timeline to do so), or fire off a pagination request.
        const tl = this.getTimelineIndex(direction);
        if (!tl) {
            debuglog("TimelineWindow: no timeline yet");
            return Promise.resolve(false);
        }
        if (tl.pendingPaginate) {
            return tl.pendingPaginate;
        }
        // try moving the cap
        if (this.extend(direction, size)) {
            return Promise.resolve(true);
        }
        if (!makeRequest || requestLimit === 0) {
            // todo: should we return something different to indicate that there
            // might be more events out there, but we haven't found them yet?
            return Promise.resolve(false);
        }
        // try making a pagination request
        const token = tl.timeline.getPaginationToken(direction);
        if (!token) {
            debuglog("TimelineWindow: no token");
            return Promise.resolve(false);
        }
        debuglog("TimelineWindow: starting request");
        const prom = this.client.paginateEventTimeline(tl.timeline, {
            backwards: direction == event_timeline_1.EventTimeline.BACKWARDS,
            limit: size,
        }).finally(function () {
            tl.pendingPaginate = null;
        }).then((r) => {
            debuglog("TimelineWindow: request completed with result " + r);
            if (!r) {
                // end of timeline
                return false;
            }
            // recurse to advance the index into the results.
            //
            // If we don't get any new events, we want to make sure we keep asking
            // the server for events for as long as we have a valid pagination
            // token. In particular, we want to know if we've actually hit the
            // start of the timeline, or if we just happened to know about all of
            // the events thanks to https://matrix.org/jira/browse/SYN-645.
            //
            // On the other hand, we necessarily want to wait forever for the
            // server to make its mind up about whether there are other events,
            // because it gives a bad user experience
            // (https://github.com/vector-im/vector-web/issues/1204).
            return this.paginate(direction, size, true, requestLimit - 1);
        });
        tl.pendingPaginate = prom;
        return prom;
    }
    /**
     * Remove `delta` events from the start or end of the timeline.
     *
     * @param {number}  delta           number of events to remove from the timeline
     * @param {boolean} startOfTimeline if events should be removed from the start
     *     of the timeline.
     */
    unpaginate(delta, startOfTimeline) {
        const tl = startOfTimeline ? this.start : this.end;
        // sanity-check the delta
        if (delta > this.eventCount || delta < 0) {
            throw new Error("Attemting to unpaginate " + delta + " events, but " +
                "only have " + this.eventCount + " in the timeline");
        }
        while (delta > 0) {
            const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);
            if (count <= 0) {
                // sadness. This shouldn't be possible.
                throw new Error("Unable to unpaginate any further, but still have " +
                    this.eventCount + " events");
            }
            delta -= count;
            this.eventCount -= count;
            debuglog("TimelineWindow.unpaginate: dropped " + count +
                " (now " + this.eventCount + ")");
        }
    }
    /**
     * Get a list of the events currently in the window
     *
     * @return {MatrixEvent[]} the events in the window
     */
    getEvents() {
        if (!this.start) {
            // not yet loaded
            return [];
        }
        const result = [];
        // iterate through each timeline between this.start and this.end
        // (inclusive).
        let timeline = this.start.timeline;
        // eslint-disable-next-line no-constant-condition
        while (true) {
            const events = timeline.getEvents();
            // For the first timeline in the chain, we want to start at
            // this.start.index. For the last timeline in the chain, we want to
            // stop before this.end.index. Otherwise, we want to copy all of the
            // events in the timeline.
            //
            // (Note that both this.start.index and this.end.index are relative
            // to their respective timelines' BaseIndex).
            //
            let startIndex = 0;
            let endIndex = events.length;
            if (timeline === this.start.timeline) {
                startIndex = this.start.index + timeline.getBaseIndex();
            }
            if (timeline === this.end.timeline) {
                endIndex = this.end.index + timeline.getBaseIndex();
            }
            for (let i = startIndex; i < endIndex; i++) {
                result.push(events[i]);
            }
            // if we're not done, iterate to the next timeline.
            if (timeline === this.end.timeline) {
                break;
            }
            else {
                timeline = timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS);
            }
        }
        return result;
    }
}
exports.TimelineWindow = TimelineWindow;
/**
 * a thing which contains a timeline reference, and an index into it.
 *
 * @constructor
 * @param {EventTimeline} timeline
 * @param {number} index
 * @private
 */
class TimelineIndex {
    // index: the indexes are relative to BaseIndex, so could well be negative.
    constructor(timeline, index) {
        this.timeline = timeline;
        this.index = index;
    }
    /**
     * @return {number} the minimum possible value for the index in the current
     *    timeline
     */
    minIndex() {
        return this.timeline.getBaseIndex() * -1;
    }
    /**
     * @return {number} the maximum possible value for the index in the current
     *    timeline (exclusive - ie, it actually returns one more than the index
     *    of the last element).
     */
    maxIndex() {
        return this.timeline.getEvents().length - this.timeline.getBaseIndex();
    }
    /**
     * Try move the index forward, or into the neighbouring timeline
     *
     * @param {number} delta  number of events to advance by
     * @return {number} number of events successfully advanced by
     */
    advance(delta) {
        if (!delta) {
            return 0;
        }
        // first try moving the index in the current timeline. See if there is room
        // to do so.
        let cappedDelta;
        if (delta < 0) {
            // we want to wind the index backwards.
            //
            // (this.minIndex() - this.index) is a negative number whose magnitude
            // is the amount of room we have to wind back the index in the current
            // timeline. We cap delta to this quantity.
            cappedDelta = Math.max(delta, this.minIndex() - this.index);
            if (cappedDelta < 0) {
                this.index += cappedDelta;
                return cappedDelta;
            }
        }
        else {
            // we want to wind the index forwards.
            //
            // (this.maxIndex() - this.index) is a (positive) number whose magnitude
            // is the amount of room we have to wind forward the index in the current
            // timeline. We cap delta to this quantity.
            cappedDelta = Math.min(delta, this.maxIndex() - this.index);
            if (cappedDelta > 0) {
                this.index += cappedDelta;
                return cappedDelta;
            }
        }
        // the index is already at the start/end of the current timeline.
        //
        // next see if there is a neighbouring timeline to switch to.
        const neighbour = this.timeline.getNeighbouringTimeline(delta < 0 ? event_timeline_1.EventTimeline.BACKWARDS : event_timeline_1.EventTimeline.FORWARDS);
        if (neighbour) {
            this.timeline = neighbour;
            if (delta < 0) {
                this.index = this.maxIndex();
            }
            else {
                this.index = this.minIndex();
            }
            debuglog("paginate: switched to new neighbour");
            // recurse, using the next timeline
            return this.advance(delta);
        }
        return 0;
    }
    /**
     * Try move the index backwards, or into the neighbouring timeline
     *
     * @param {number} delta  number of events to retreat by
     * @return {number} number of events successfully retreated by
     */
    retreat(delta) {
        return this.advance(delta * -1) * -1;
    }
}
exports.TimelineIndex = TimelineIndex;

},{"./logger":106,"./models/event-timeline":112}],137:[function(require,module,exports){
"use strict";
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.lexicographicCompare = exports.prevString = exports.nextString = exports.averageBetweenStrings = exports.stringToBase = exports.baseToString = exports.alphabetPad = exports.DEFAULT_ALPHABET = exports.getCrypto = exports.setCrypto = exports.simpleRetryOperation = exports.chunkPromises = exports.promiseTry = exports.promiseMapSeries = exports.defer = exports.isNullOrUndefined = exports.sleep = exports.ensureNoTrailingSlash = exports.globToRegexp = exports.escapeRegExp = exports.normalize = exports.removeHiddenChars = exports.isNumber = exports.polyfillSuper = exports.inherits = exports.extend = exports.deepSortedObjectEntries = exports.deepCompare = exports.deepCopy = exports.checkObjectHasNoAdditionalKeys = exports.checkObjectHasKeys = exports.isFunction = exports.removeElement = exports.encodeUri = exports.encodeParams = void 0;
/**
 * This is an internal module.
 * @module utils
 */
const unhomoglyph_1 = __importDefault(require("unhomoglyph"));
const p_retry_1 = __importDefault(require("p-retry"));
/**
 * Encode a dictionary of query parameters.
 * @param {Object} params A dict of key/values to encode e.g.
 * {"foo": "bar", "baz": "taz"}
 * @return {string} The encoded string e.g. foo=bar&baz=taz
 */
function encodeParams(params) {
    let qs = "";
    for (const key in params) {
        if (!params.hasOwnProperty(key)) {
            continue;
        }
        qs += "&" + encodeURIComponent(key) + "=" +
            encodeURIComponent(params[key]);
    }
    return qs.substring(1);
}
exports.encodeParams = encodeParams;
/**
 * Encodes a URI according to a set of template variables. Variables will be
 * passed through encodeURIComponent.
 * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.
 * @param {Object} variables The key/value pairs to replace the template
 * variables with. E.g. { "$bar": "baz" }.
 * @return {string} The result of replacing all template variables e.g. '/foo/baz'.
 */
function encodeUri(pathTemplate, variables) {
    for (const key in variables) {
        if (!variables.hasOwnProperty(key)) {
            continue;
        }
        pathTemplate = pathTemplate.replace(key, encodeURIComponent(variables[key]));
    }
    return pathTemplate;
}
exports.encodeUri = encodeUri;
/**
 * The removeElement() method removes the first element in the array that
 * satisfies (returns true) the provided testing function.
 * @param {Array} array The array.
 * @param {Function} fn Function to execute on each value in the array, with the
 * function signature <code>fn(element, index, array)</code>. Return true to
 * remove this element and break.
 * @param {boolean} reverse True to search in reverse order.
 * @return {boolean} True if an element was removed.
 */
function removeElement(array, fn, reverse) {
    let i;
    let removed;
    if (reverse) {
        for (i = array.length - 1; i >= 0; i--) {
            if (fn(array[i], i, array)) {
                removed = array[i];
                array.splice(i, 1);
                return removed;
            }
        }
    }
    else {
        for (i = 0; i < array.length; i++) {
            if (fn(array[i], i, array)) {
                removed = array[i];
                array.splice(i, 1);
                return removed;
            }
        }
    }
    return false;
}
exports.removeElement = removeElement;
/**
 * Checks if the given thing is a function.
 * @param {*} value The thing to check.
 * @return {boolean} True if it is a function.
 */
function isFunction(value) {
    return Object.prototype.toString.call(value) === "[object Function]";
}
exports.isFunction = isFunction;
/**
 * Checks that the given object has the specified keys.
 * @param {Object} obj The object to check.
 * @param {string[]} keys The list of keys that 'obj' must have.
 * @throws If the object is missing keys.
 */
// note using 'keys' here would shadow the 'keys' function defined above
function checkObjectHasKeys(obj, keys_) {
    for (let i = 0; i < keys_.length; i++) {
        if (!obj.hasOwnProperty(keys_[i])) {
            throw new Error("Missing required key: " + keys_[i]);
        }
    }
}
exports.checkObjectHasKeys = checkObjectHasKeys;
/**
 * Checks that the given object has no extra keys other than the specified ones.
 * @param {Object} obj The object to check.
 * @param {string[]} allowedKeys The list of allowed key names.
 * @throws If there are extra keys.
 */
function checkObjectHasNoAdditionalKeys(obj, allowedKeys) {
    for (const key in obj) {
        if (!obj.hasOwnProperty(key)) {
            continue;
        }
        if (allowedKeys.indexOf(key) === -1) {
            throw new Error("Unknown key: " + key);
        }
    }
}
exports.checkObjectHasNoAdditionalKeys = checkObjectHasNoAdditionalKeys;
/**
 * Deep copy the given object. The object MUST NOT have circular references and
 * MUST NOT have functions.
 * @param {Object} obj The object to deep copy.
 * @return {Object} A copy of the object without any references to the original.
 */
function deepCopy(obj) {
    return JSON.parse(JSON.stringify(obj));
}
exports.deepCopy = deepCopy;
/**
 * Compare two objects for equality. The objects MUST NOT have circular references.
 *
 * @param {Object} x The first object to compare.
 * @param {Object} y The second object to compare.
 *
 * @return {boolean} true if the two objects are equal
 */
function deepCompare(x, y) {
    // Inspired by
    // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249
    // Compare primitives and functions.
    // Also check if both arguments link to the same object.
    if (x === y) {
        return true;
    }
    if (typeof x !== typeof y) {
        return false;
    }
    // special-case NaN (since NaN !== NaN)
    if (typeof x === 'number' && isNaN(x) && isNaN(y)) {
        return true;
    }
    // special-case null (since typeof null == 'object', but null.constructor
    // throws)
    if (x === null || y === null) {
        return x === y;
    }
    // everything else is either an unequal primitive, or an object
    if (!(x instanceof Object)) {
        return false;
    }
    // check they are the same type of object
    if (x.constructor !== y.constructor || x.prototype !== y.prototype) {
        return false;
    }
    // special-casing for some special types of object
    if (x instanceof RegExp || x instanceof Date) {
        return x.toString() === y.toString();
    }
    // the object algorithm works for Array, but it's sub-optimal.
    if (x instanceof Array) {
        if (x.length !== y.length) {
            return false;
        }
        for (let i = 0; i < x.length; i++) {
            if (!deepCompare(x[i], y[i])) {
                return false;
            }
        }
    }
    else {
        // disable jshint "The body of a for in should be wrapped in an if
        // statement"
        /* jshint -W089 */
        // check that all of y's direct keys are in x
        let p;
        for (p in y) {
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            }
        }
        // finally, compare each of x's keys with y
        for (p in y) { // eslint-disable-line guard-for-in
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            }
            if (!deepCompare(x[p], y[p])) {
                return false;
            }
        }
    }
    /* jshint +W089 */
    return true;
}
exports.deepCompare = deepCompare;
// Dev note: This returns a tuple, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703
/**
 * Creates an array of object properties/values (entries) then
 * sorts the result by key, recursively. The input object must
 * ensure it does not have loops. If the input is not an object
 * then it will be returned as-is.
 * @param {*} obj The object to get entries of
 * @returns {Array} The entries, sorted by key.
 */
function deepSortedObjectEntries(obj) {
    if (typeof (obj) !== "object")
        return obj;
    // Apparently these are object types...
    if (obj === null || obj === undefined || Array.isArray(obj))
        return obj;
    const pairs = [];
    for (const [k, v] of Object.entries(obj)) {
        pairs.push([k, deepSortedObjectEntries(v)]);
    }
    // lexicographicCompare is faster than localeCompare, so let's use that.
    pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));
    return pairs;
}
exports.deepSortedObjectEntries = deepSortedObjectEntries;
/**
 * Copy properties from one object to another.
 *
 * All enumerable properties, included inherited ones, are copied.
 *
 * This is approximately equivalent to ES6's Object.assign, except
 * that the latter doesn't copy inherited properties.
 *
 * @param {Object} target  The object that will receive new properties
 * @param {...Object} source  Objects from which to copy properties
 *
 * @return {Object} target
 */
function extend(...restParams) {
    const target = restParams[0] || {};
    for (let i = 1; i < restParams.length; i++) {
        const source = restParams[i];
        if (!source)
            continue;
        for (const propName in source) { // eslint-disable-line guard-for-in
            target[propName] = source[propName];
        }
    }
    return target;
}
exports.extend = extend;
/**
 * Inherit the prototype methods from one constructor into another. This is a
 * port of the Node.js implementation with an Object.create polyfill.
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
function inherits(ctor, superCtor) {
    // Add util.inherits from Node.js
    // Source:
    // https://github.com/joyent/node/blob/master/lib/util.js
    // Copyright Joyent, Inc. and other Node contributors.
    //
    // Permission is hereby granted, free of charge, to any person obtaining a
    // copy of this software and associated documentation files (the
    // "Software"), to deal in the Software without restriction, including
    // without limitation the rights to use, copy, modify, merge, publish,
    // distribute, sublicense, and/or sell copies of the Software, and to permit
    // persons to whom the Software is furnished to do so, subject to the
    // following conditions:
    //
    // The above copyright notice and this permission notice shall be included
    // in all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
    // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    // USE OR OTHER DEALINGS IN THE SOFTWARE.
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true,
        },
    });
}
exports.inherits = inherits;
/**
 * Polyfills inheritance for prototypes by allowing different kinds of
 * super types. Typically prototypes would use `SuperType.call(this, params)`
 * though this doesn't always work in some environments - this function
 * falls back to using `Object.assign()` to clone a constructed copy
 * of the super type onto `thisArg`.
 * @param {any} thisArg The child instance. Modified in place.
 * @param {any} SuperType The type to act as a super instance
 * @param {any} params Arguments to supply to the super type's constructor
 */
function polyfillSuper(thisArg, SuperType, ...params) {
    try {
        SuperType.call(thisArg, ...params);
    }
    catch (e) {
        // fall back to Object.assign to just clone the thing
        const fakeSuper = new SuperType(...params);
        Object.assign(thisArg, fakeSuper);
    }
}
exports.polyfillSuper = polyfillSuper;
/**
 * Returns whether the given value is a finite number without type-coercion
 *
 * @param {*} value the value to test
 * @return {boolean} whether or not value is a finite number without type-coercion
 */
function isNumber(value) {
    return typeof value === 'number' && isFinite(value);
}
exports.isNumber = isNumber;
/**
 * Removes zero width chars, diacritics and whitespace from the string
 * Also applies an unhomoglyph on the string, to prevent similar looking chars
 * @param {string} str the string to remove hidden characters from
 * @return {string} a string with the hidden characters removed
 */
function removeHiddenChars(str) {
    if (typeof str === "string") {
        return unhomoglyph_1.default(str.normalize('NFD').replace(removeHiddenCharsRegex, ''));
    }
    return "";
}
exports.removeHiddenChars = removeHiddenChars;
function normalize(str) {
    // Note: we have to match the filter with the removeHiddenChars() because the
    // function strips spaces and other characters (M becomes RN for example, in lowercase).
    return removeHiddenChars(str.toLowerCase())
        // Strip all punctuation
        .replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g, "")
        // We also doubly convert to lowercase to work around oddities of the library.
        .toLowerCase();
}
exports.normalize = normalize;
// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.
// Includes:
// various width spaces U+2000 - U+200D
// LTR and RTL marks U+200E and U+200F
// LTR/RTL and other directional formatting marks U+202A - U+202F
// Combining characters U+0300 - U+036F
// Zero width no-break space (BOM) U+FEFF
// eslint-disable-next-line no-misleading-character-class
const removeHiddenCharsRegex = /[\u2000-\u200F\u202A-\u202F\u0300-\u036f\uFEFF\s]/g;
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
exports.escapeRegExp = escapeRegExp;
function globToRegexp(glob, extended) {
    extended = typeof (extended) === 'boolean' ? extended : true;
    // From
    // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132
    // Because micromatch is about 130KB with dependencies,
    // and minimatch is not much better.
    let pat = escapeRegExp(glob);
    pat = pat.replace(/\\\*/g, '.*');
    pat = pat.replace(/\?/g, '.');
    if (extended) {
        pat = pat.replace(/\\\[(!|)(.*)\\]/g, function (match, p1, p2, offset, string) {
            const first = p1 && '^' || '';
            const second = p2.replace(/\\-/, '-');
            return '[' + first + second + ']';
        });
    }
    return pat;
}
exports.globToRegexp = globToRegexp;
function ensureNoTrailingSlash(url) {
    if (url && url.endsWith("/")) {
        return url.substr(0, url.length - 1);
    }
    else {
        return url;
    }
}
exports.ensureNoTrailingSlash = ensureNoTrailingSlash;
// Returns a promise which resolves with a given value after the given number of ms
function sleep(ms, value) {
    return new Promise((resolve => {
        setTimeout(resolve, ms, value);
    }));
}
exports.sleep = sleep;
function isNullOrUndefined(val) {
    return val === null || val === undefined;
}
exports.isNullOrUndefined = isNullOrUndefined;
// Returns a Deferred
function defer() {
    let resolve;
    let reject;
    const promise = new Promise((_resolve, _reject) => {
        resolve = _resolve;
        reject = _reject;
    });
    return { resolve, reject, promise };
}
exports.defer = defer;
function promiseMapSeries(promises, fn) {
    return __awaiter(this, void 0, void 0, function* () {
        for (const o of promises) {
            yield fn(yield o);
        }
    });
}
exports.promiseMapSeries = promiseMapSeries;
function promiseTry(fn) {
    return new Promise((resolve) => resolve(fn()));
}
exports.promiseTry = promiseTry;
// Creates and awaits all promises, running no more than `chunkSize` at the same time
function chunkPromises(fns, chunkSize) {
    return __awaiter(this, void 0, void 0, function* () {
        const results = [];
        for (let i = 0; i < fns.length; i += chunkSize) {
            results.push(...(yield Promise.all(fns.slice(i, i + chunkSize).map(fn => fn()))));
        }
        return results;
    });
}
exports.chunkPromises = chunkPromises;
/**
 * Retries the function until it succeeds or is interrupted. The given function must return
 * a promise which throws/rejects on error, otherwise the retry will assume the request
 * succeeded. The promise chain returned will contain the successful promise. The given function
 * should always return a new promise.
 * @param {Function} promiseFn The function to call to get a fresh promise instance. Takes an
 * attempt count as an argument, for logging/debugging purposes.
 * @returns {Promise<T>} The promise for the retried operation.
 */
function simpleRetryOperation(promiseFn) {
    return p_retry_1.default((attempt) => {
        return promiseFn(attempt);
    }, {
        forever: true,
        factor: 2,
        minTimeout: 3000,
        maxTimeout: 15000,
    });
}
exports.simpleRetryOperation = simpleRetryOperation;
// We need to be able to access the Node.js crypto library from within the
// Matrix SDK without needing to `require("crypto")`, which will fail in
// browsers.  So `index.ts` will call `setCrypto` to store it, and when we need
// it, we can call `getCrypto`.
let crypto;
function setCrypto(c) {
    crypto = c;
}
exports.setCrypto = setCrypto;
function getCrypto() {
    return crypto;
}
exports.getCrypto = getCrypto;
// String averaging inspired by https://stackoverflow.com/a/2510816
// Dev note: We make the alphabet a string because it's easier to write syntactically
// than arrays. Thankfully, strings implement the useful parts of the Array interface
// anyhow.
/**
 * The default alphabet used by string averaging in this SDK. This matches
 * all usefully printable ASCII characters (0x20-0x7E, inclusive).
 */
exports.DEFAULT_ALPHABET = (() => {
    let str = "";
    for (let c = 0x20; c <= 0x7E; c++) {
        str += String.fromCharCode(c);
    }
    return str;
})();
/**
 * Pads a string using the given alphabet as a base. The returned string will be
 * padded at the end with the first character in the alphabet.
 *
 * This is intended for use with string averaging.
 * @param {string} s The string to pad.
 * @param {number} n The length to pad to.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {string} The padded string.
 */
function alphabetPad(s, n, alphabet = exports.DEFAULT_ALPHABET) {
    return s.padEnd(n, alphabet[0]);
}
exports.alphabetPad = alphabetPad;
/**
 * Converts a baseN number to a string, where N is the alphabet's length.
 *
 * This is intended for use with string averaging.
 * @param {bigint} n The baseN number.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {string} The baseN number encoded as a string from the alphabet.
 */
function baseToString(n, alphabet = exports.DEFAULT_ALPHABET) {
    // Developer note: the stringToBase() function offsets the character set by 1 so that repeated
    // characters (ie: "aaaaaa" in a..z) don't come out as zero. We have to reverse this here as
    // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun
    // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a
    // sane state. This also means we have to do rollover detection: see below.
    var _a;
    const len = BigInt(alphabet.length);
    if (n <= len) {
        return (_a = alphabet[Number(n) - 1]) !== null && _a !== void 0 ? _a : "";
    }
    let d = n / len;
    let r = Number(n % len) - 1;
    // Rollover detection: if the remainder is negative, it means that the string needs
    // to roll over by 1 character downwards (ie: in a..z, the previous to "aaa" would be
    // "zz").
    if (r < 0) {
        d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.
        r = Number(len) - 1;
    }
    return baseToString(d, alphabet) + alphabet[r];
}
exports.baseToString = baseToString;
/**
 * Converts a string to a baseN number, where N is the alphabet's length.
 *
 * This is intended for use with string averaging.
 * @param {string} s The string to convert to a number.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {bigint} The baseN number.
 */
function stringToBase(s, alphabet = exports.DEFAULT_ALPHABET) {
    const len = BigInt(alphabet.length);
    // In our conversion to baseN we do a couple performance optimizations to avoid using
    // excess CPU and such. To create baseN numbers, the input string needs to be reversed
    // so the exponents stack up appropriately, as the last character in the unreversed
    // string has less impact than the first character (in "abc" the A is a lot more important
    // for lexicographic sorts). We also do a trick with the character codes to optimize the
    // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know
    // that the alphabet and (theoretically) the input string are constrained on character sets
    // and thus can do simple subtraction to end up with the same result.
    // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot
    // rely on Math.pow() (for example) to be capable of handling our insane numbers.
    let result = BigInt(0);
    for (let i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {
        const charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);
        // We add 1 to the char index to offset the whole numbering scheme. We unpack this in
        // the baseToString() function.
        result += BigInt(1 + charIndex) * (len ** j);
    }
    return result;
}
exports.stringToBase = stringToBase;
/**
 * Averages two strings, returning the midpoint between them. This is accomplished by
 * converting both to baseN numbers (where N is the alphabet's length) then averaging
 * those before re-encoding as a string.
 * @param {string} a The first string.
 * @param {string} b The second string.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {string} The midpoint between the strings, as a string.
 */
function averageBetweenStrings(a, b, alphabet = exports.DEFAULT_ALPHABET) {
    const padN = Math.max(a.length, b.length);
    const baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);
    const baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);
    const avg = (baseA + baseB) / BigInt(2);
    // Detect integer division conflicts. This happens when two numbers are divided too close so
    // we lose a .5 precision. We need to add a padding character in these cases.
    if (avg === baseA || avg == baseB) {
        return baseToString(avg, alphabet) + alphabet[0];
    }
    return baseToString(avg, alphabet);
}
exports.averageBetweenStrings = averageBetweenStrings;
/**
 * Finds the next string using the alphabet provided. This is done by converting the
 * string to a baseN number, where N is the alphabet's length, then adding 1 before
 * converting back to a string.
 * @param {string} s The string to start at.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {string} The string which follows the input string.
 */
function nextString(s, alphabet = exports.DEFAULT_ALPHABET) {
    return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);
}
exports.nextString = nextString;
/**
 * Finds the previous string using the alphabet provided. This is done by converting the
 * string to a baseN number, where N is the alphabet's length, then subtracting 1 before
 * converting back to a string.
 * @param {string} s The string to start at.
 * @param {string} alphabet The alphabet to use as a single string.
 * @returns {string} The string which precedes the input string.
 */
function prevString(s, alphabet = exports.DEFAULT_ALPHABET) {
    return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);
}
exports.prevString = prevString;
/**
 * Compares strings lexicographically as a sort-safe function.
 * @param {string} a The first (reference) string.
 * @param {string} b The second (compare) string.
 * @returns {number} Negative if the reference string is before the compare string;
 * positive if the reference string is after; and zero if equal.
 */
function lexicographicCompare(a, b) {
    // Dev note: this exists because I'm sad that you can use math operators on strings, so I've
    // hidden the operation in this function.
    return (a < b) ? -1 : ((a === b) ? 0 : 1);
}
exports.lexicographicCompare = lexicographicCompare;

},{"p-retry":39,"unhomoglyph":55}],138:[function(require,module,exports){
(function (process){(function (){
"use strict";
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNewMatrixCall = exports.setVideoInput = exports.setAudioInput = exports.getUserMediaContraints = exports.MatrixCall = exports.CallError = exports.getDesktopCapturerSources = exports.ConstraintsType = exports.CallErrorCode = exports.CallEvent = exports.CallParty = exports.CallDirection = exports.CallType = exports.CallState = void 0;
/**
 * This is an internal module. See {@link createNewMatrixCall} for the public API.
 * @module webrtc/call
 */
const logger_1 = require("../logger");
const events_1 = require("events");
const utils = __importStar(require("../utils"));
const event_1 = require("../@types/event");
const randomstring_1 = require("../randomstring");
const callEventTypes_1 = require("./callEventTypes");
const callFeed_1 = require("./callFeed");
var CallState;
(function (CallState) {
    CallState["Fledgling"] = "fledgling";
    CallState["InviteSent"] = "invite_sent";
    CallState["WaitLocalMedia"] = "wait_local_media";
    CallState["CreateOffer"] = "create_offer";
    CallState["CreateAnswer"] = "create_answer";
    CallState["Connecting"] = "connecting";
    CallState["Connected"] = "connected";
    CallState["Ringing"] = "ringing";
    CallState["Ended"] = "ended";
})(CallState = exports.CallState || (exports.CallState = {}));
var CallType;
(function (CallType) {
    CallType["Voice"] = "voice";
    CallType["Video"] = "video";
})(CallType = exports.CallType || (exports.CallType = {}));
var CallDirection;
(function (CallDirection) {
    CallDirection["Inbound"] = "inbound";
    CallDirection["Outbound"] = "outbound";
})(CallDirection = exports.CallDirection || (exports.CallDirection = {}));
var CallParty;
(function (CallParty) {
    CallParty["Local"] = "local";
    CallParty["Remote"] = "remote";
})(CallParty = exports.CallParty || (exports.CallParty = {}));
var CallEvent;
(function (CallEvent) {
    CallEvent["Hangup"] = "hangup";
    CallEvent["State"] = "state";
    CallEvent["Error"] = "error";
    CallEvent["Replaced"] = "replaced";
    // The value of isLocalOnHold() has changed
    CallEvent["LocalHoldUnhold"] = "local_hold_unhold";
    // The value of isRemoteOnHold() has changed
    CallEvent["RemoteHoldUnhold"] = "remote_hold_unhold";
    // backwards compat alias for LocalHoldUnhold: remove in a major version bump
    CallEvent["HoldUnhold"] = "hold_unhold";
    // Feeds have changed
    CallEvent["FeedsChanged"] = "feeds_changed";
    CallEvent["AssertedIdentityChanged"] = "asserted_identity_changed";
})(CallEvent = exports.CallEvent || (exports.CallEvent = {}));
var CallErrorCode;
(function (CallErrorCode) {
    /** The user chose to end the call */
    CallErrorCode["UserHangup"] = "user_hangup";
    /** An error code when the local client failed to create an offer. */
    CallErrorCode["LocalOfferFailed"] = "local_offer_failed";
    /**
     * An error code when there is no local mic/camera to use. This may be because
     * the hardware isn't plugged in, or the user has explicitly denied access.
     */
    CallErrorCode["NoUserMedia"] = "no_user_media";
    /**
     * Error code used when a call event failed to send
     * because unknown devices were present in the room
     */
    CallErrorCode["UnknownDevices"] = "unknown_devices";
    /**
     * Error code usewd when we fail to send the invite
     * for some reason other than there being unknown devices
     */
    CallErrorCode["SendInvite"] = "send_invite";
    /**
     * An answer could not be created
     */
    CallErrorCode["CreateAnswer"] = "create_answer";
    /**
     * Error code usewd when we fail to send the answer
     * for some reason other than there being unknown devices
     */
    CallErrorCode["SendAnswer"] = "send_answer";
    /**
     * The session description from the other side could not be set
     */
    CallErrorCode["SetRemoteDescription"] = "set_remote_description";
    /**
     * The session description from this side could not be set
     */
    CallErrorCode["SetLocalDescription"] = "set_local_description";
    /**
     * A different device answered the call
     */
    CallErrorCode["AnsweredElsewhere"] = "answered_elsewhere";
    /**
     * No media connection could be established to the other party
     */
    CallErrorCode["IceFailed"] = "ice_failed";
    /**
     * The invite timed out whilst waiting for an answer
     */
    CallErrorCode["InviteTimeout"] = "invite_timeout";
    /**
     * The call was replaced by another call
     */
    CallErrorCode["Replaced"] = "replaced";
    /**
     * Signalling for the call could not be sent (other than the initial invite)
     */
    CallErrorCode["SignallingFailed"] = "signalling_timeout";
    /**
     * The remote party is busy
     */
    CallErrorCode["UserBusy"] = "user_busy";
    /**
     * We transferred the call off to somewhere else
     */
    CallErrorCode["Transfered"] = "transferred";
})(CallErrorCode = exports.CallErrorCode || (exports.CallErrorCode = {}));
var ConstraintsType;
(function (ConstraintsType) {
    ConstraintsType["Audio"] = "audio";
    ConstraintsType["Video"] = "video";
})(ConstraintsType = exports.ConstraintsType || (exports.ConstraintsType = {}));
/**
 * The version field that we set in m.call.* events
 */
const VOIP_PROTO_VERSION = 1;
/** The fallback ICE server to use for STUN or TURN protocols. */
const FALLBACK_ICE_SERVER = 'stun:turn.matrix.org';
/** The length of time a call can be ringing for. */
const CALL_TIMEOUT_MS = 60000;
/** Retrieves sources from desktopCapturer */
function getDesktopCapturerSources() {
    const options = {
        thumbnailSize: {
            height: 176,
            width: 312,
        },
        types: [
            "screen",
            "window",
        ],
    };
    return window.electron.getDesktopCapturerSources(options);
}
exports.getDesktopCapturerSources = getDesktopCapturerSources;
class CallError extends Error {
    constructor(code, msg, err) {
        // Stil ldon't think there's any way to have proper nested errors
        super(msg + ": " + err);
        this.code = code;
    }
}
exports.CallError = CallError;
function genCallID() {
    return Date.now().toString() + randomstring_1.randomString(16);
}
/**
 * Construct a new Matrix Call.
 * @constructor
 * @param {Object} opts Config options.
 * @param {string} opts.roomId The room ID for this call.
 * @param {Object} opts.webRtc The WebRTC globals from the browser.
 * @param {boolean} opts.forceTURN whether relay through TURN should be forced.
 * @param {Object} opts.URL The URL global.
 * @param {Array<Object>} opts.turnServers Optional. A list of TURN servers.
 * @param {MatrixClient} opts.client The Matrix Client instance to send events to.
 */
class MatrixCall extends events_1.EventEmitter {
    constructor(opts) {
        super();
        // If candidates arrive before we've picked an opponent (which, in particular,
        // will happen if the opponent sends candidates eagerly before the user answers
        // the call) we buffer them up here so we can then add the ones from the party we pick
        this.remoteCandidateBuffer = new Map();
        /**
         * Internal
         * @param {Object} stream
         */
        this.gotUserMediaForInvite = (stream) => __awaiter(this, void 0, void 0, function* () {
            if (this.successor) {
                this.successor.gotUserMediaForAnswer(stream);
                return;
            }
            if (this.callHasEnded()) {
                this.stopAllMedia();
                return;
            }
            this.localAVStream = stream;
            logger_1.logger.info("Got local AV stream with id " + this.localAVStream.id);
            this.setState(CallState.CreateOffer);
            logger_1.logger.debug("gotUserMediaForInvite -> " + this.type);
            if (this.screenSharingStream) {
                logger_1.logger.debug("Setting screen sharing stream to the local video element");
                this.pushNewFeed(this.screenSharingStream, this.client.getUserId(), callEventTypes_1.SDPStreamMetadataPurpose.Screenshare);
            }
            else {
                this.pushNewFeed(stream, this.client.getUserId(), callEventTypes_1.SDPStreamMetadataPurpose.Usermedia);
            }
            // why do we enable audio (and only audio) tracks here? -- matthew
            setTracksEnabled(stream.getAudioTracks(), true);
            for (const audioTrack of stream.getAudioTracks()) {
                logger_1.logger.info("Adding audio track with id " + audioTrack.id);
                this.peerConn.addTrack(audioTrack, stream);
            }
            for (const videoTrack of (this.screenSharingStream || stream).getVideoTracks()) {
                logger_1.logger.info("Adding video track with id " + videoTrack.id);
                this.peerConn.addTrack(videoTrack, stream);
            }
            // Now we wait for the negotiationneeded event
        });
        this.gotUserMediaForAnswer = (stream) => __awaiter(this, void 0, void 0, function* () {
            if (this.callHasEnded()) {
                return;
            }
            this.pushNewFeed(stream, this.client.getUserId(), callEventTypes_1.SDPStreamMetadataPurpose.Usermedia);
            this.localAVStream = stream;
            logger_1.logger.info("Got local AV stream with id " + this.localAVStream.id);
            setTracksEnabled(stream.getAudioTracks(), true);
            for (const track of stream.getTracks()) {
                this.peerConn.addTrack(track, stream);
            }
            this.setState(CallState.CreateAnswer);
            let myAnswer;
            try {
                myAnswer = yield this.peerConn.createAnswer();
            }
            catch (err) {
                logger_1.logger.debug("Failed to create answer: ", err);
                this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);
                return;
            }
            try {
                yield this.peerConn.setLocalDescription(myAnswer);
                this.setState(CallState.Connecting);
                // Allow a short time for initial candidates to be gathered
                yield new Promise(resolve => {
                    setTimeout(resolve, 200);
                });
                this.sendAnswer();
            }
            catch (err) {
                logger_1.logger.debug("Error setting local description!", err);
                this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);
                return;
            }
        });
        /**
         * Internal
         * @param {Object} event
         */
        this.gotLocalIceCandidate = (event) => {
            if (event.candidate) {
                logger_1.logger.debug("Call " + this.callId + " got local ICE " + event.candidate.sdpMid + " candidate: " +
                    event.candidate.candidate);
                if (this.callHasEnded())
                    return;
                // As with the offer, note we need to make a copy of this object, not
                // pass the original: that broke in Chrome ~m43.
                if (event.candidate.candidate !== '' || !this.sentEndOfCandidates) {
                    this.queueCandidate(event.candidate);
                    if (event.candidate.candidate === '')
                        this.sentEndOfCandidates = true;
                }
            }
        };
        this.onIceGatheringStateChange = (event) => {
            logger_1.logger.debug("ice gathering state changed to " + this.peerConn.iceGatheringState);
            if (this.peerConn.iceGatheringState === 'complete' && !this.sentEndOfCandidates) {
                // If we didn't get an empty-string candidate to signal the end of candidates,
                // create one ourselves now gathering has finished.
                // We cast because the interface lists all the properties as required but we
                // only want to send 'candidate'
                // XXX: We probably want to send either sdpMid or sdpMLineIndex, as it's not strictly
                // correct to have a candidate that lacks both of these. We'd have to figure out what
                // previous candidates had been sent with and copy them.
                const c = {
                    candidate: '',
                };
                this.queueCandidate(c);
                this.sentEndOfCandidates = true;
            }
        };
        this.gotLocalOffer = (description) => __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug("Created offer: ", description);
            if (this.callHasEnded()) {
                logger_1.logger.debug("Ignoring newly created offer on call ID " + this.callId +
                    " because the call has ended");
                return;
            }
            try {
                yield this.peerConn.setLocalDescription(description);
            }
            catch (err) {
                logger_1.logger.debug("Error setting local description!", err);
                this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);
                return;
            }
            if (this.peerConn.iceGatheringState === 'gathering') {
                // Allow a short time for initial candidates to be gathered
                yield new Promise(resolve => {
                    setTimeout(resolve, 200);
                });
            }
            if (this.callHasEnded())
                return;
            const eventType = this.state === CallState.CreateOffer ? event_1.EventType.CallInvite : event_1.EventType.CallNegotiate;
            const content = {
                lifetime: CALL_TIMEOUT_MS,
            };
            if (eventType === event_1.EventType.CallInvite && this.invitee) {
                content.invitee = this.invitee;
            }
            // clunky because TypeScript can't folow the types through if we use an expression as the key
            if (this.state === CallState.CreateOffer) {
                content.offer = this.peerConn.localDescription;
            }
            else {
                content.description = this.peerConn.localDescription;
            }
            if (this.client.supportsCallTransfer) {
                content.capabilities = {
                    'm.call.transferee': true,
                };
            }
            // Get rid of any candidates waiting to be sent: they'll be included in the local
            // description we just got and will send in the offer.
            logger_1.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`);
            this.candidateSendQueue = [];
            try {
                yield this.sendVoipEvent(eventType, content);
            }
            catch (error) {
                logger_1.logger.error("Failed to send invite", error);
                if (error.event)
                    this.client.cancelPendingEvent(error.event);
                let code = CallErrorCode.SignallingFailed;
                let message = "Signalling failed";
                if (this.state === CallState.CreateOffer) {
                    code = CallErrorCode.SendInvite;
                    message = "Failed to send invite";
                }
                if (error.name == 'UnknownDeviceError') {
                    code = CallErrorCode.UnknownDevices;
                    message = "Unknown devices present in the room";
                }
                this.emit(CallEvent.Error, new CallError(code, message, error));
                this.terminate(CallParty.Local, code, false);
                // no need to carry on & send the candidate queue, but we also
                // don't want to rethrow the error
                return;
            }
            this.sendCandidateQueue();
            if (this.state === CallState.CreateOffer) {
                this.inviteOrAnswerSent = true;
                this.setState(CallState.InviteSent);
                this.inviteTimeout = setTimeout(() => {
                    this.inviteTimeout = null;
                    if (this.state === CallState.InviteSent) {
                        this.hangup(CallErrorCode.InviteTimeout, false);
                    }
                }, CALL_TIMEOUT_MS);
            }
        });
        this.getLocalOfferFailed = (err) => {
            logger_1.logger.error("Failed to get local offer", err);
            this.emit(CallEvent.Error, new CallError(CallErrorCode.LocalOfferFailed, "Failed to get local offer!", err));
            this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);
        };
        this.getUserMediaFailed = (err) => {
            if (this.successor) {
                this.successor.getUserMediaFailed(err);
                return;
            }
            logger_1.logger.warn("Failed to get user media - ending call", err);
            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.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);
        };
        this.onIceConnectionStateChanged = () => {
            if (this.callHasEnded()) {
                return; // because ICE can still complete as we're ending the call
            }
            logger_1.logger.debug("Call ID " + this.callId + ": ICE connection state changed to: " + this.peerConn.iceConnectionState);
            // ideally we'd consider the call to be connected when we get media but
            // chrome doesn't implement any of the 'onstarted' events yet
            if (this.peerConn.iceConnectionState == 'connected') {
                clearTimeout(this.iceDisconnectedTimeout);
                this.setState(CallState.Connected);
            }
            else if (this.peerConn.iceConnectionState == 'failed') {
                this.hangup(CallErrorCode.IceFailed, false);
            }
            else if (this.peerConn.iceConnectionState == 'disconnected') {
                this.iceDisconnectedTimeout = setTimeout(() => {
                    this.hangup(CallErrorCode.IceFailed, false);
                }, 30 * 1000);
            }
        };
        this.onSignallingStateChanged = () => {
            logger_1.logger.debug("call " + this.callId + ": Signalling state changed to: " +
                this.peerConn.signalingState);
        };
        this.onTrack = (ev) => {
            var _a;
            if (ev.streams.length === 0) {
                logger_1.logger.warn(`Streamless ${ev.track.kind} found: ignoring.`);
                return;
            }
            const oldRemoteStream = (_a = this.feeds.find((feed) => !feed.isLocal())) === null || _a === void 0 ? void 0 : _a.stream;
            // If we already have a stream, check this track is from the same one
            // Note that we check by ID and always set the remote stream: Chrome appears
            // to make new stream objects when tranciever directionality is changed and the 'active'
            // status of streams change - Dave
            if (oldRemoteStream && ev.streams[0].id !== oldRemoteStream.id) {
                logger_1.logger.warn(`Ignoring new stream ID ${ev.streams[0].id}: we already have stream ID ${oldRemoteStream.id}`);
                return;
            }
            if (!oldRemoteStream) {
                logger_1.logger.info("Got remote stream with id " + ev.streams[0].id);
            }
            const newRemoteStream = ev.streams[0];
            logger_1.logger.debug(`Track id ${ev.track.id} of kind ${ev.track.kind} added`);
            this.pushNewFeed(newRemoteStream, this.getOpponentMember().userId, callEventTypes_1.SDPStreamMetadataPurpose.Usermedia);
            logger_1.logger.info("playing remote. stream active? " + newRemoteStream.active);
        };
        this.onNegotiationNeeded = () => __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.info("Negotation is needed!");
            if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) {
                logger_1.logger.info("Opponent does not support renegotiation: ignoring negotiationneeded event");
                return;
            }
            this.makingOffer = true;
            try {
                const myOffer = yield this.peerConn.createOffer();
                yield this.gotLocalOffer(myOffer);
            }
            catch (e) {
                this.getLocalOfferFailed(e);
                return;
            }
            finally {
                this.makingOffer = false;
            }
        });
        this.onHangupReceived = (msg) => {
            logger_1.logger.debug("Hangup received for call ID " + this.callId);
            // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen
            // a partner yet but we're treating the hangup as a reject as per VoIP v0)
            if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {
                // default reason is user_hangup
                this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
            }
            else {
                logger_1.logger.info(`Ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`);
            }
        };
        this.onRejectReceived = (msg) => {
            logger_1.logger.debug("Reject received for call ID " + this.callId);
            // No need to check party_id for reject because if we'd received either
            // an answer or reject, we wouldn't be in state InviteSent
            const shouldTerminate = (
            // reject events also end the call if it's ringing: it's another of
            // our devices rejecting the call.
            ([CallState.InviteSent, CallState.Ringing].includes(this.state)) ||
                // also if we're in the init state and it's an inbound call, since
                // this means we just haven't entered the ringing state yet
                this.state === CallState.Fledgling && this.direction === CallDirection.Inbound);
            if (shouldTerminate) {
                this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
            }
            else {
                logger_1.logger.debug(`Call is in state: ${this.state}: ignoring reject`);
            }
        };
        this.onAnsweredElsewhere = (msg) => {
            logger_1.logger.debug("Call ID " + this.callId + " answered elsewhere");
            this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);
        };
        this.roomId = opts.roomId;
        this.invitee = opts.invitee;
        this.client = opts.client;
        this.type = null;
        this.forceTURN = opts.forceTURN;
        this.ourPartyId = this.client.deviceId;
        // Array of Objects with urls, username, credential keys
        this.turnServers = opts.turnServers || [];
        if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {
            this.turnServers.push({
                urls: [FALLBACK_ICE_SERVER],
            });
        }
        for (const server of this.turnServers) {
            utils.checkObjectHasKeys(server, ["urls"]);
        }
        this.callId = genCallID();
        this.state = CallState.Fledgling;
        // A queue for candidates waiting to go out.
        // We try to amalgamate candidates into a single candidate message where
        // possible
        this.candidateSendQueue = [];
        this.candidateSendTries = 0;
        this.sentEndOfCandidates = false;
        this.inviteOrAnswerSent = false;
        this.makingOffer = false;
        this.remoteOnHold = false;
        this.micMuted = false;
        this.vidMuted = false;
        this.feeds = [];
    }
    /**
     * Place a voice call to this room.
     * @throws If you have not specified a listener for 'error' events.
     */
    placeVoiceCall() {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug("placeVoiceCall");
            this.checkForErrorListener();
            this.type = CallType.Voice;
            yield this.placeCall(ConstraintsType.Audio);
        });
    }
    /**
     * Place a video call to this room.
     * @throws If you have not specified a listener for 'error' events.
     */
    placeVideoCall() {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug("placeVideoCall");
            this.checkForErrorListener();
            this.type = CallType.Video;
            yield this.placeCall(ConstraintsType.Video);
        });
    }
    /**
     * Place a screen-sharing call to this room. This includes audio.
     * <b>This method is EXPERIMENTAL and subject to change without warning. It
     * only works in Google Chrome and Firefox >= 44.</b>
     * @throws If you have not specified a listener for 'error' events.
     */
    placeScreenSharingCall(selectDesktopCapturerSource) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug("placeScreenSharingCall");
            this.checkForErrorListener();
            try {
                const screenshareConstraints = yield getScreenshareContraints(selectDesktopCapturerSource);
                if (!screenshareConstraints) {
                    this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);
                    return;
                }
                if ((_a = window.electron) === null || _a === void 0 ? void 0 : _a.getDesktopCapturerSources) {
                    // We are using Electron
                    logger_1.logger.debug("Getting screen stream using getUserMedia()...");
                    this.screenSharingStream = yield navigator.mediaDevices.getUserMedia(screenshareConstraints);
                }
                else {
                    // We are not using Electron
                    logger_1.logger.debug("Getting screen stream using getDisplayMedia()...");
                    this.screenSharingStream = yield navigator.mediaDevices.getDisplayMedia(screenshareConstraints);
                }
                logger_1.logger.debug("Got screen stream, requesting audio stream...");
                this.placeCall(ConstraintsType.Audio);
            }
            catch (err) {
                this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, "Failed to get screen-sharing stream: ", err));
                this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);
            }
            this.type = CallType.Video;
        });
    }
    getOpponentMember() {
        return this.opponentMember;
    }
    opponentCanBeTransferred() {
        return Boolean(this.opponentCaps && this.opponentCaps["m.call.transferee"]);
    }
    getRemoteAssertedIdentity() {
        return this.remoteAssertedIdentity;
    }
    /**
     * Returns an array of all CallFeeds
     * @returns {Array<CallFeed>} CallFeeds
     */
    getFeeds() {
        return this.feeds;
    }
    /**
     * Returns an array of all local CallFeeds
     * @returns {Array<CallFeed>} local CallFeeds
     */
    getLocalFeeds() {
        return this.feeds.filter((feed) => feed.isLocal());
    }
    /**
     * Returns an array of all remote CallFeeds
     * @returns {Array<CallFeed>} remote CallFeeds
     */
    getRemoteFeeds() {
        return this.feeds.filter((feed) => !feed.isLocal());
    }
    /**
     * Returns true if there are no incoming feeds,
     * otherwise returns false
     * @returns {boolean} no incoming feeds
     */
    noIncomingFeeds() {
        return !this.feeds.some((feed) => !feed.isLocal());
    }
    pushNewFeed(stream, userId, purpose) {
        // Try to find a feed with the same stream id as the new stream,
        // if we find it replace the old stream with the new one
        const feed = this.feeds.find((feed) => feed.stream.id === stream.id);
        if (feed) {
            feed.setNewStream(stream);
        }
        else {
            this.feeds.push(new callFeed_1.CallFeed(stream, userId, purpose, this.client, this.roomId));
            this.emit(CallEvent.FeedsChanged, this.feeds);
        }
    }
    deleteAllFeeds() {
        this.feeds = [];
        this.emit(CallEvent.FeedsChanged, this.feeds);
    }
    // The typescript definitions have this type as 'any' :(
    getCurrentCallStats() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.callHasEnded()) {
                return this.callStatsAtEnd;
            }
            return this.collectCallStats();
        });
    }
    collectCallStats() {
        return __awaiter(this, void 0, void 0, function* () {
            // This happens when the call fails before it starts.
            // For example when we fail to get capture sources
            if (!this.peerConn)
                return;
            const statsReport = yield this.peerConn.getStats();
            const stats = [];
            for (const item of statsReport) {
                stats.push(item[1]);
            }
            return stats;
        });
    }
    /**
     * Configure this call from an invite event. Used by MatrixClient.
     * @param {MatrixEvent} event The m.call.invite event
     */
    initWithInvite(event) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const invite = event.getContent();
            this.direction = CallDirection.Inbound;
            // make sure we have valid turn creds. Unless something's gone wrong, it should
            // poll and keep the credentials valid so this should be instant.
            const haveTurnCreds = yield this.client.checkTurnServers();
            if (!haveTurnCreds) {
                logger_1.logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");
            }
            this.peerConn = this.createPeerConnection();
            // we must set the party ID before await-ing on anything: the call event
            // handler will start giving us more call events (eg. candidates) so if
            // we haven't set the party ID, we'll ignore them.
            this.chooseOpponent(event);
            try {
                yield this.peerConn.setRemoteDescription(invite.offer);
                yield this.addBufferedIceCandidates();
            }
            catch (e) {
                logger_1.logger.debug("Failed to set remote description", e);
                this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
                return;
            }
            const remoteStream = (_a = this.feeds.find((feed) => !feed.isLocal())) === null || _a === void 0 ? void 0 : _a.stream;
            // According to previous comments in this file, firefox at some point did not
            // add streams until media started ariving on them. Testing latest firefox
            // (81 at time of writing), this is no longer a problem, so let's do it the correct way.
            if (!remoteStream || remoteStream.getTracks().length === 0) {
                logger_1.logger.error("No remote stream or no tracks after setting remote description!");
                this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
                return;
            }
            this.type = remoteStream.getTracks().some(t => t.kind === 'video') ? CallType.Video : CallType.Voice;
            this.setState(CallState.Ringing);
            if (event.getLocalAge()) {
                setTimeout(() => {
                    if (this.state == CallState.Ringing) {
                        logger_1.logger.debug("Call invite has expired. Hanging up.");
                        this.hangupParty = CallParty.Remote; // effectively
                        this.setState(CallState.Ended);
                        this.stopAllMedia();
                        if (this.peerConn.signalingState != 'closed') {
                            this.peerConn.close();
                        }
                        this.emit(CallEvent.Hangup);
                    }
                }, invite.lifetime - event.getLocalAge());
            }
        });
    }
    /**
     * Configure this call from a hangup or reject event. Used by MatrixClient.
     * @param {MatrixEvent} event The m.call.hangup event
     */
    initWithHangup(event) {
        // perverse as it may seem, sometimes we want to instantiate a call with a
        // hangup message (because when getting the state of the room on load, events
        // come in reverse order and we want to remember that a call has been hung up)
        this.setState(CallState.Ended);
    }
    /**
     * Answer a call.
     */
    answer() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.inviteOrAnswerSent) {
                return;
            }
            logger_1.logger.debug(`Answering call ${this.callId} of type ${this.type}`);
            if (!this.localAVStream && !this.waitForLocalAVStream) {
                this.setState(CallState.WaitLocalMedia);
                this.waitForLocalAVStream = true;
                try {
                    let mediaStream;
                    if (this.type === CallType.Voice) {
                        mediaStream = yield this.client.getLocalAudioStream();
                    }
                    else {
                        mediaStream = yield this.client.getLocalVideoStream();
                    }
                    this.waitForLocalAVStream = false;
                    this.gotUserMediaForAnswer(mediaStream);
                }
                catch (e) {
                    this.getUserMediaFailed(e);
                    return;
                }
            }
            else if (this.localAVStream) {
                this.gotUserMediaForAnswer(this.localAVStream);
            }
            else if (this.waitForLocalAVStream) {
                this.setState(CallState.WaitLocalMedia);
            }
        });
    }
    /**
     * Replace this call with a new call, e.g. for glare resolution. Used by
     * MatrixClient.
     * @param {MatrixCall} newCall The new call.
     */
    replacedBy(newCall) {
        logger_1.logger.debug(this.callId + " being replaced by " + newCall.callId);
        if (this.state === CallState.WaitLocalMedia) {
            logger_1.logger.debug("Telling new call to wait for local media");
            newCall.waitForLocalAVStream = true;
        }
        else if (this.state === CallState.CreateOffer) {
            logger_1.logger.debug("Handing local stream to new call");
            newCall.gotUserMediaForAnswer(this.localAVStream);
            delete (this.localAVStream);
        }
        else if (this.state === CallState.InviteSent) {
            logger_1.logger.debug("Handing local stream to new call");
            newCall.gotUserMediaForAnswer(this.localAVStream);
            delete (this.localAVStream);
        }
        this.successor = newCall;
        this.emit(CallEvent.Replaced, newCall);
        this.hangup(CallErrorCode.Replaced, true);
    }
    /**
     * Hangup a call.
     * @param {string} reason The reason why the call is being hung up.
     * @param {boolean} suppressEvent True to suppress emitting an event.
     */
    hangup(reason, suppressEvent) {
        if (this.callHasEnded())
            return;
        logger_1.logger.debug("Ending call " + this.callId);
        this.terminate(CallParty.Local, reason, !suppressEvent);
        // We don't want to send hangup here if we didn't even get to sending an invite
        if (this.state === CallState.WaitLocalMedia)
            return;
        const content = {};
        // Continue to send no reason for user hangups temporarily, until
        // clients understand the user_hangup reason (voip v1)
        if (reason !== CallErrorCode.UserHangup)
            content['reason'] = reason;
        this.sendVoipEvent(event_1.EventType.CallHangup, content);
    }
    /**
     * Reject a call
     * This used to be done by calling hangup, but is a separate method and protocol
     * event as of MSC2746.
     */
    reject() {
        if (this.state !== CallState.Ringing) {
            throw Error("Call must be in 'ringing' state to reject!");
        }
        if (this.opponentVersion < 1) {
            logger_1.logger.info(`Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`);
            this.hangup(CallErrorCode.UserHangup, true);
            return;
        }
        logger_1.logger.debug("Rejecting call: " + this.callId);
        this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);
        this.sendVoipEvent(event_1.EventType.CallReject, {});
    }
    /**
     * Set whether our outbound video should be muted or not.
     * @param {boolean} muted True to mute the outbound video.
     */
    setLocalVideoMuted(muted) {
        this.vidMuted = muted;
        this.updateMuteStatus();
    }
    /**
     * Check if local video is muted.
     *
     * If there are multiple video tracks, <i>all</i> of the tracks need to be muted
     * for this to return true. This means if there are no video tracks, this will
     * return true.
     * @return {Boolean} True if the local preview video is muted, else false
     * (including if the call is not set up yet).
     */
    isLocalVideoMuted() {
        return this.vidMuted;
    }
    /**
     * Set whether the microphone should be muted or not.
     * @param {boolean} muted True to mute the mic.
     */
    setMicrophoneMuted(muted) {
        this.micMuted = muted;
        this.updateMuteStatus();
    }
    /**
     * Check if the microphone is muted.
     *
     * If there are multiple audio tracks, <i>all</i> of the tracks need to be muted
     * for this to return true. This means if there are no audio tracks, this will
     * return true.
     * @return {Boolean} True if the mic is muted, else false (including if the call
     * is not set up yet).
     */
    isMicrophoneMuted() {
        return this.micMuted;
    }
    /**
     * @returns true if we have put the party on the other side of the call on hold
     * (that is, we are signalling to them that we are not listening)
     */
    isRemoteOnHold() {
        return this.remoteOnHold;
    }
    setRemoteOnHold(onHold) {
        if (this.isRemoteOnHold() === onHold)
            return;
        this.remoteOnHold = onHold;
        for (const tranceiver of this.peerConn.getTransceivers()) {
            // We don't send hold music or anything so we're not actually
            // sending anything, but sendrecv is fairly standard for hold and
            // it makes it a lot easier to figure out who's put who on hold.
            tranceiver.direction = onHold ? 'sendonly' : 'sendrecv';
        }
        this.updateMuteStatus();
        this.emit(CallEvent.RemoteHoldUnhold, this.remoteOnHold);
    }
    /**
     * Indicates whether we are 'on hold' to the remote party (ie. if true,
     * they cannot hear us).
     * @returns true if the other party has put us on hold
     */
    isLocalOnHold() {
        if (this.state !== CallState.Connected)
            return false;
        let callOnHold = true;
        // We consider a call to be on hold only if *all* the tracks are on hold
        // (is this the right thing to do?)
        for (const tranceiver of this.peerConn.getTransceivers()) {
            const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);
            if (!trackOnHold)
                callOnHold = false;
        }
        return callOnHold;
    }
    /**
     * Sends a DTMF digit to the other party
     * @param digit The digit (nb. string - '#' and '*' are dtmf too)
     */
    sendDtmfDigit(digit) {
        for (const sender of this.peerConn.getSenders()) {
            if (sender.track.kind === 'audio' && sender.dtmf) {
                sender.dtmf.insertDTMF(digit);
                return;
            }
        }
        throw new Error("Unable to find a track to send DTMF on");
    }
    updateMuteStatus() {
        if (!this.localAVStream) {
            return;
        }
        const micShouldBeMuted = this.micMuted || this.remoteOnHold;
        setTracksEnabled(this.localAVStream.getAudioTracks(), !micShouldBeMuted);
        const vidShouldBeMuted = this.vidMuted || this.remoteOnHold;
        setTracksEnabled(this.localAVStream.getVideoTracks(), !vidShouldBeMuted);
    }
    sendAnswer() {
        return __awaiter(this, void 0, void 0, function* () {
            const answerContent = {
                answer: {
                    sdp: this.peerConn.localDescription.sdp,
                    // type is now deprecated as of Matrix VoIP v1, but
                    // required to still be sent for backwards compat
                    type: this.peerConn.localDescription.type,
                },
            };
            if (this.client.supportsCallTransfer) {
                answerContent.capabilities = {
                    'm.call.transferee': true,
                };
            }
            // We have just taken the local description from the peerconnection which will
            // contain all the local candidates added so far, so we can discard any candidates
            // we had queued up because they'll be in the answer.
            logger_1.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`);
            this.candidateSendQueue = [];
            try {
                yield this.sendVoipEvent(event_1.EventType.CallAnswer, answerContent);
                // If this isn't the first time we've tried to send the answer,
                // we may have candidates queued up, so send them now.
                this.inviteOrAnswerSent = true;
            }
            catch (error) {
                // We've failed to answer: back to the ringing state
                this.setState(CallState.Ringing);
                this.client.cancelPendingEvent(error.event);
                let code = CallErrorCode.SendAnswer;
                let message = "Failed to send answer";
                if (error.name == 'UnknownDeviceError') {
                    code = CallErrorCode.UnknownDevices;
                    message = "Unknown devices present in the room";
                }
                this.emit(CallEvent.Error, new CallError(code, message, error));
                throw error;
            }
            // error handler re-throws so this won't happen on error, but
            // we don't want the same error handling on the candidate queue
            this.sendCandidateQueue();
        });
    }
    onRemoteIceCandidatesReceived(ev) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.callHasEnded()) {
                //debuglog("Ignoring remote ICE candidate because call has ended");
                return;
            }
            const cands = ev.getContent().candidates;
            if (!cands) {
                logger_1.logger.info("Ignoring candidates event with no candidates!");
                return;
            }
            const fromPartyId = ev.getContent().version === 0 ? null : ev.getContent().party_id || null;
            if (this.opponentPartyId === undefined) {
                // we haven't picked an opponent yet so save the candidates
                logger_1.logger.info(`Bufferring ${cands.length} candidates until we pick an opponent`);
                const bufferedCands = this.remoteCandidateBuffer.get(fromPartyId) || [];
                bufferedCands.push(...cands);
                this.remoteCandidateBuffer.set(fromPartyId, bufferedCands);
                return;
            }
            if (!this.partyIdMatches(ev.getContent())) {
                logger_1.logger.info(`Ignoring candidates from party ID ${ev.getContent().party_id}: ` +
                    `we have chosen party ID ${this.opponentPartyId}`);
                return;
            }
            yield this.addIceCandidates(cands);
        });
    }
    /**
     * Used by MatrixClient.
     * @param {Object} msg
     */
    onAnswerReceived(event) {
        return __awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug(`Got answer for call ID ${this.callId} from party ID ${event.getContent().party_id}`);
            if (this.callHasEnded()) {
                logger_1.logger.debug(`Ignoring answer because call ID ${this.callId} has ended`);
                return;
            }
            if (this.opponentPartyId !== undefined) {
                logger_1.logger.info(`Ignoring answer from party ID ${event.getContent().party_id}: ` +
                    `we already have an answer/reject from ${this.opponentPartyId}`);
                return;
            }
            this.chooseOpponent(event);
            yield this.addBufferedIceCandidates();
            this.setState(CallState.Connecting);
            try {
                yield this.peerConn.setRemoteDescription(event.getContent().answer);
            }
            catch (e) {
                logger_1.logger.debug("Failed to set remote description", e);
                this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
                return;
            }
            // If the answer we selected has a party_id, send a select_answer event
            // We do this after setting the remote description since otherwise we'd block
            // call setup on it
            if (this.opponentPartyId !== null) {
                try {
                    yield this.sendVoipEvent(event_1.EventType.CallSelectAnswer, {
                        selected_party_id: this.opponentPartyId,
                    });
                }
                catch (err) {
                    // This isn't fatal, and will just mean that if another party has raced to answer
                    // the call, they won't know they got rejected, so we carry on & don't retry.
                    logger_1.logger.warn("Failed to send select_answer event", err);
                }
            }
        });
    }
    onSelectAnswerReceived(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.direction !== CallDirection.Inbound) {
                logger_1.logger.warn("Got select_answer for an outbound call: ignoring");
                return;
            }
            const selectedPartyId = event.getContent().selected_party_id;
            if (selectedPartyId === undefined || selectedPartyId === null) {
                logger_1.logger.warn("Got nonsensical select_answer with null/undefined selected_party_id: ignoring");
                return;
            }
            if (selectedPartyId !== this.ourPartyId) {
                logger_1.logger.info(`Got select_answer for party ID ${selectedPartyId}: we are party ID ${this.ourPartyId}.`);
                // The other party has picked somebody else's answer
                this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);
            }
        });
    }
    onNegotiateReceived(event) {
        return __awaiter(this, void 0, void 0, function* () {
            const description = event.getContent().description;
            if (!description || !description.sdp || !description.type) {
                logger_1.logger.info("Ignoring invalid m.call.negotiate event");
                return;
            }
            // Politeness always follows the direction of the call: in a glare situation,
            // we pick either the inbound or outbound call, so one side will always be
            // inbound and one outbound
            const polite = this.direction === CallDirection.Inbound;
            // Here we follow the perfect negotiation logic from
            // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation
            const offerCollision = ((description.type === 'offer') &&
                (this.makingOffer || this.peerConn.signalingState != 'stable'));
            this.ignoreOffer = !polite && offerCollision;
            if (this.ignoreOffer) {
                logger_1.logger.info("Ignoring colliding negotiate event because we're impolite");
                return;
            }
            const prevLocalOnHold = this.isLocalOnHold();
            try {
                yield this.peerConn.setRemoteDescription(description);
                if (description.type === 'offer') {
                    const localDescription = yield this.peerConn.createAnswer();
                    yield this.peerConn.setLocalDescription(localDescription);
                    this.sendVoipEvent(event_1.EventType.CallNegotiate, {
                        description: this.peerConn.localDescription,
                    });
                }
            }
            catch (err) {
                logger_1.logger.warn("Failed to complete negotiation", err);
            }
            const newLocalOnHold = this.isLocalOnHold();
            if (prevLocalOnHold !== newLocalOnHold) {
                this.emit(CallEvent.LocalHoldUnhold, newLocalOnHold);
                // also this one for backwards compat
                this.emit(CallEvent.HoldUnhold, newLocalOnHold);
            }
        });
    }
    onAssertedIdentityReceived(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!event.getContent().asserted_identity)
                return;
            this.remoteAssertedIdentity = {
                id: event.getContent().asserted_identity.id,
                displayName: event.getContent().asserted_identity.display_name,
            };
            this.emit(CallEvent.AssertedIdentityChanged);
        });
    }
    callHasEnded() {
        // This exists as workaround to typescript trying to be clever and erroring
        // when putting if (this.state === CallState.Ended) return; twice in the same
        // function, even though that function is async.
        return this.state === CallState.Ended;
    }
    setState(state) {
        const oldState = this.state;
        this.state = state;
        this.emit(CallEvent.State, state, oldState);
    }
    /**
     * Internal
     * @param {string} eventType
     * @param {Object} content
     * @return {Promise}
     */
    sendVoipEvent(eventType, content) {
        return this.client.sendEvent(this.roomId, eventType, Object.assign({}, content, {
            version: VOIP_PROTO_VERSION,
            call_id: this.callId,
            party_id: this.ourPartyId,
        }));
    }
    queueCandidate(content) {
        // Sends candidates with are sent in a special way because we try to amalgamate
        // them into one message
        this.candidateSendQueue.push(content);
        // Don't send the ICE candidates yet if the call is in the ringing state: this
        // means we tried to pick (ie. started generating candidates) and then failed to
        // send the answer and went back to the ringing state. Queue up the candidates
        // to send if we sucessfully send the answer.
        // Equally don't send if we haven't yet sent the answer because we can send the
        // first batch of candidates along with the answer
        if (this.state === CallState.Ringing || !this.inviteOrAnswerSent)
            return;
        // MSC2746 reccomends these values (can be quite long when calling because the
        // callee will need a while to answer the call)
        const delay = this.direction === CallDirection.Inbound ? 500 : 2000;
        if (this.candidateSendTries === 0) {
            setTimeout(() => {
                this.sendCandidateQueue();
            }, delay);
        }
    }
    /*
     * Transfers this call to another user
     */
    transfer(targetUserId) {
        return __awaiter(this, void 0, void 0, function* () {
            // Fetch the target user's global profile info: their room avatar / displayname
            // could be different in whatever room we shae with them.
            const profileInfo = yield this.client.getProfileInfo(targetUserId);
            const replacementId = genCallID();
            const body = {
                replacement_id: genCallID(),
                target_user: {
                    id: targetUserId,
                    display_name: profileInfo.display_name,
                    avatar_url: profileInfo.avatar_url,
                },
                create_call: replacementId,
            };
            yield this.sendVoipEvent(event_1.EventType.CallReplaces, body);
            yield this.terminate(CallParty.Local, CallErrorCode.Transfered, true);
        });
    }
    /*
     * Transfers this call to the target call, effectively 'joining' the
     * two calls (so the remote parties on each call are connected together).
     */
    transferToCall(transferTargetCall) {
        return __awaiter(this, void 0, void 0, function* () {
            const targetProfileInfo = yield this.client.getProfileInfo(transferTargetCall.getOpponentMember().userId);
            const transfereeProfileInfo = yield this.client.getProfileInfo(this.getOpponentMember().userId);
            const newCallId = genCallID();
            const bodyToTransferTarget = {
                // the replacements on each side have their own ID, and it's distinct from the
                // ID of the new call (but we can use the same function to generate it)
                replacement_id: genCallID(),
                target_user: {
                    id: this.getOpponentMember().userId,
                    display_name: transfereeProfileInfo.display_name,
                    avatar_url: transfereeProfileInfo.avatar_url,
                },
                await_call: newCallId,
            };
            yield transferTargetCall.sendVoipEvent(event_1.EventType.CallReplaces, bodyToTransferTarget);
            const bodyToTransferee = {
                replacement_id: genCallID(),
                target_user: {
                    id: transferTargetCall.getOpponentMember().userId,
                    display_name: targetProfileInfo.display_name,
                    avatar_url: targetProfileInfo.avatar_url,
                },
                create_call: newCallId,
            };
            yield this.sendVoipEvent(event_1.EventType.CallReplaces, bodyToTransferee);
            yield this.terminate(CallParty.Local, CallErrorCode.Replaced, true);
            yield transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transfered, true);
        });
    }
    terminate(hangupParty, hangupReason, shouldEmit) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.callHasEnded())
                return;
            this.callStatsAtEnd = yield this.collectCallStats();
            if (this.inviteTimeout) {
                clearTimeout(this.inviteTimeout);
                this.inviteTimeout = null;
            }
            // Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds()
            // We don't stop media if the call was replaced as we want to re-use streams in the successor
            if (hangupReason !== CallErrorCode.Replaced)
                this.stopAllMedia();
            this.deleteAllFeeds();
            this.hangupParty = hangupParty;
            this.hangupReason = hangupReason;
            this.setState(CallState.Ended);
            if (this.peerConn && this.peerConn.signalingState !== 'closed') {
                this.peerConn.close();
            }
            if (shouldEmit) {
                this.emit(CallEvent.Hangup, this);
            }
        });
    }
    stopAllMedia() {
        logger_1.logger.debug(`stopAllMedia (stream=${this.localAVStream})`);
        for (const feed of this.feeds) {
            if (!feed.isLocal()) {
                for (const track of feed.stream.getTracks()) {
                    track.stop();
                }
            }
        }
    }
    checkForErrorListener() {
        if (this.listeners("error").length === 0) {
            throw new Error("You MUST attach an error listener using call.on('error', function() {})");
        }
    }
    sendCandidateQueue() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.candidateSendQueue.length === 0) {
                return;
            }
            const cands = this.candidateSendQueue;
            this.candidateSendQueue = [];
            ++this.candidateSendTries;
            const content = {
                candidates: cands,
            };
            logger_1.logger.debug("Attempting to send " + cands.length + " candidates");
            try {
                yield this.sendVoipEvent(event_1.EventType.CallCandidates, content);
            }
            catch (error) {
                // don't retry this event: we'll send another one later as we might
                // have more candidates by then.
                if (error.event)
                    this.client.cancelPendingEvent(error.event);
                // put all the candidates we failed to send back in the queue
                this.candidateSendQueue.push(...cands);
                if (this.candidateSendTries > 5) {
                    logger_1.logger.debug("Failed to send candidates on attempt " + this.candidateSendTries +
                        ". Giving up on this call.", error);
                    const code = CallErrorCode.SignallingFailed;
                    const message = "Signalling failed";
                    this.emit(CallEvent.Error, new CallError(code, message, error));
                    this.hangup(code, false);
                    return;
                }
                const delayMs = 500 * Math.pow(2, this.candidateSendTries);
                ++this.candidateSendTries;
                logger_1.logger.debug("Failed to send candidates. Retrying in " + delayMs + "ms", error);
                setTimeout(() => {
                    this.sendCandidateQueue();
                }, delayMs);
            }
        });
    }
    placeCall(constraintsType) {
        return __awaiter(this, void 0, void 0, function* () {
            // XXX Find a better way to do this
            this.client.callEventHandler.calls.set(this.callId, this);
            this.setState(CallState.WaitLocalMedia);
            this.direction = CallDirection.Outbound;
            // make sure we have valid turn creds. Unless something's gone wrong, it should
            // poll and keep the credentials valid so this should be instant.
            const haveTurnCreds = yield this.client.checkTurnServers();
            if (!haveTurnCreds) {
                logger_1.logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");
            }
            // create the peer connection now so it can be gathering candidates while we get user
            // media (assuming a candidate pool size is configured)
            this.peerConn = this.createPeerConnection();
            try {
                let mediaStream;
                if (constraintsType === ConstraintsType.Audio) {
                    mediaStream = yield this.client.getLocalAudioStream();
                }
                else {
                    mediaStream = yield this.client.getLocalVideoStream();
                }
                this.gotUserMediaForInvite(mediaStream);
            }
            catch (e) {
                this.getUserMediaFailed(e);
                return;
            }
        });
    }
    createPeerConnection() {
        const pc = new window.RTCPeerConnection({
            iceTransportPolicy: this.forceTURN ? 'relay' : undefined,
            iceServers: this.turnServers,
            iceCandidatePoolSize: this.client.iceCandidatePoolSize,
        });
        // 'connectionstatechange' would be better, but firefox doesn't implement that.
        pc.addEventListener('iceconnectionstatechange', this.onIceConnectionStateChanged);
        pc.addEventListener('signalingstatechange', this.onSignallingStateChanged);
        pc.addEventListener('icecandidate', this.gotLocalIceCandidate);
        pc.addEventListener('icegatheringstatechange', this.onIceGatheringStateChange);
        pc.addEventListener('track', this.onTrack);
        pc.addEventListener('negotiationneeded', this.onNegotiationNeeded);
        return pc;
    }
    partyIdMatches(msg) {
        // They must either match or both be absent (in which case opponentPartyId will be null)
        // Also we ignore party IDs on the invite/offer if the version is 0, so we must do the same
        // here and use null if the version is 0 (woe betide any opponent sending messages in the
        // same call with different versions)
        const msgPartyId = msg.version === 0 ? null : msg.party_id || null;
        return msgPartyId === this.opponentPartyId;
    }
    // Commits to an opponent for the call
    // ev: An invite or answer event
    chooseOpponent(ev) {
        // I choo-choo-choose you
        const msg = ev.getContent();
        logger_1.logger.debug(`Choosing party ID ${msg.party_id} for call ID ${this.callId}`);
        this.opponentVersion = msg.version;
        if (this.opponentVersion === 0) {
            // set to null to indicate that we've chosen an opponent, but because
            // they're v0 they have no party ID (even if they sent one, we're ignoring it)
            this.opponentPartyId = null;
        }
        else {
            // set to their party ID, or if they're naughty and didn't send one despite
            // not being v0, set it to null to indicate we picked an opponent with no
            // party ID
            this.opponentPartyId = msg.party_id || null;
        }
        this.opponentCaps = msg.capabilities || {};
        this.opponentMember = ev.sender;
    }
    addBufferedIceCandidates() {
        return __awaiter(this, void 0, void 0, function* () {
            const bufferedCands = this.remoteCandidateBuffer.get(this.opponentPartyId);
            if (bufferedCands) {
                logger_1.logger.info(`Adding ${bufferedCands.length} buffered candidates for opponent ${this.opponentPartyId}`);
                yield this.addIceCandidates(bufferedCands);
            }
            this.remoteCandidateBuffer = null;
        });
    }
    addIceCandidates(cands) {
        return __awaiter(this, void 0, void 0, function* () {
            for (const cand of cands) {
                if ((cand.sdpMid === null || cand.sdpMid === undefined) &&
                    (cand.sdpMLineIndex === null || cand.sdpMLineIndex === undefined)) {
                    logger_1.logger.debug("Ignoring remote ICE candidate with no sdpMid or sdpMLineIndex");
                    continue;
                }
                logger_1.logger.debug("Call " + this.callId + " got remote ICE " + cand.sdpMid + " candidate: " + cand.candidate);
                try {
                    yield this.peerConn.addIceCandidate(cand);
                }
                catch (err) {
                    if (!this.ignoreOffer) {
                        logger_1.logger.info("Failed to add remote ICE candidate", err);
                    }
                }
            }
        });
    }
}
exports.MatrixCall = MatrixCall;
function setTracksEnabled(tracks, enabled) {
    for (let i = 0; i < tracks.length; i++) {
        tracks[i].enabled = enabled;
    }
}
function getUserMediaContraints(type) {
    const isWebkit = !!navigator.webkitGetUserMedia;
    switch (type) {
        case ConstraintsType.Audio: {
            return {
                audio: {
                    deviceId: audioInput ? { ideal: audioInput } : undefined,
                },
                video: false,
            };
        }
        case ConstraintsType.Video: {
            return {
                audio: {
                    deviceId: audioInput ? { ideal: audioInput } : undefined,
                }, video: {
                    deviceId: videoInput ? { ideal: videoInput } : undefined,
                    /* We want 640x360.  Chrome will give it only if we ask exactly,
                       FF refuses entirely if we ask exactly, so have to ask for ideal
                       instead
                       XXX: Is this still true?
                     */
                    width: isWebkit ? { exact: 640 } : { ideal: 640 },
                    height: isWebkit ? { exact: 360 } : { ideal: 360 },
                },
            };
        }
    }
}
exports.getUserMediaContraints = getUserMediaContraints;
function getScreenshareContraints(selectDesktopCapturerSource) {
    var _a;
    return __awaiter(this, void 0, void 0, function* () {
        if (((_a = window.electron) === null || _a === void 0 ? void 0 : _a.getDesktopCapturerSources) && selectDesktopCapturerSource) {
            // We have access to getDesktopCapturerSources()
            logger_1.logger.debug("Electron getDesktopCapturerSources() is available...");
            const selectedSource = yield selectDesktopCapturerSource();
            if (!selectedSource)
                return null;
            return {
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: "desktop",
                        chromeMediaSourceId: selectedSource.id,
                    },
                },
            };
        }
        else {
            // We do not have access to the Electron desktop capturer,
            // therefore we can assume we are on the web
            logger_1.logger.debug("Electron desktopCapturer is not available...");
            return {
                audio: false,
                video: true,
            };
        }
    });
}
let audioInput;
let videoInput;
/**
 * Set an audio input device to use for MatrixCalls
 * @function
 * @param {string=} deviceId the identifier for the device
 * undefined treated as unset
 */
function setAudioInput(deviceId) { audioInput = deviceId; }
exports.setAudioInput = setAudioInput;
/**
 * Set a video input device to use for MatrixCalls
 * @function
 * @param {string=} deviceId the identifier for the device
 * undefined treated as unset
 */
function setVideoInput(deviceId) { videoInput = deviceId; }
exports.setVideoInput = setVideoInput;
/**
 * DEPRECATED
 * Use client.createCall()
 *
 * Create a new Matrix call for the browser.
 * @param {MatrixClient} client The client instance to use.
 * @param {string} roomId The room the call is in.
 * @param {Object?} options DEPRECATED optional options map.
 * @param {boolean} options.forceTURN DEPRECATED whether relay through TURN should be
 * forced. This option is deprecated - use opts.forceTURN when creating the matrix client
 * since it's only possible to set this option on outbound calls.
 * @return {MatrixCall} the call or null if the browser doesn't support calling.
 */
function createNewMatrixCall(client, roomId, options) {
    // typeof prevents Node from erroring on an undefined reference
    if (typeof (window) === 'undefined' || typeof (document) === 'undefined') {
        // NB. We don't log here as apps try to create a call object as a test for
        // whether calls are supported, so we shouldn't fill the logs up.
        return null;
    }
    // Firefox throws on so little as accessing the RTCPeerConnection when operating in
    // a secure mode. There's some information at https://bugzilla.mozilla.org/show_bug.cgi?id=1542616
    // though the concern is that the browser throwing a SecurityError will brick the
    // client creation process.
    try {
        const supported = Boolean(window.RTCPeerConnection || window.RTCSessionDescription ||
            window.RTCIceCandidate || navigator.mediaDevices);
        if (!supported) {
            // Adds a lot of noise to test runs, so disable logging there.
            if (process.env.NODE_ENV !== "test") {
                logger_1.logger.error("WebRTC is not supported in this browser / environment");
            }
            return null;
        }
    }
    catch (e) {
        logger_1.logger.error("Exception thrown when trying to access WebRTC", e);
        return null;
    }
    const optionsForceTURN = options ? options.forceTURN : false;
    const opts = {
        client: client,
        roomId: roomId,
        invitee: options && options.invitee,
        turnServers: client.getTurnServers(),
        // call level options
        forceTURN: client.forceTURN || optionsForceTURN,
    };
    const call = new MatrixCall(opts);
    client.reEmitter.reEmit(call, Object.values(CallEvent));
    return call;
}
exports.createNewMatrixCall = createNewMatrixCall;

}).call(this)}).call(this,require('_process'))

},{"../@types/event":58,"../logger":106,"../randomstring":123,"../utils":137,"./callEventTypes":140,"./callFeed":141,"_process":40,"events":36}],139:[function(require,module,exports){
"use strict";
/*
Copyright 2020 The Matrix.org Foundation C.I.C.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallEventHandler = void 0;
const logger_1 = require("../logger");
const call_1 = require("./call");
const event_1 = require("../@types/event");
// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some
// time to press the 'accept' button
const RING_GRACE_PERIOD = 3000;
class CallEventHandler {
    constructor(client) {
        this.evaluateEventBuffer = () => __awaiter(this, void 0, void 0, function* () {
            if (this.client.getSyncState() === "SYNCING") {
                yield Promise.all(this.callEventBuffer.map(event => {
                    this.client.decryptEventIfNeeded(event);
                }));
                const ignoreCallIds = new Set();
                // inspect the buffer and mark all calls which have been answered
                // or hung up before passing them to the call event handler.
                for (const ev of this.callEventBuffer) {
                    if (ev.getType() === event_1.EventType.CallAnswer ||
                        ev.getType() === event_1.EventType.CallHangup) {
                        ignoreCallIds.add(ev.getContent().call_id);
                    }
                }
                // now loop through the buffer chronologically and inject them
                for (const e of this.callEventBuffer) {
                    if (e.getType() === event_1.EventType.CallInvite &&
                        ignoreCallIds.has(e.getContent().call_id)) {
                        // This call has previously been answered or hung up: ignore it
                        continue;
                    }
                    try {
                        this.handleCallEvent(e);
                    }
                    catch (e) {
                        logger_1.logger.error("Caught exception handling call event", e);
                    }
                }
                this.callEventBuffer = [];
            }
        });
        this.onEvent = (event) => {
            this.client.decryptEventIfNeeded(event);
            // any call events or ones that might be once they're decrypted
            if (this.eventIsACall(event) || event.isBeingDecrypted()) {
                // queue up for processing once all events from this sync have been
                // processed (see above).
                this.callEventBuffer.push(event);
            }
            if (event.isBeingDecrypted() || event.isDecryptionFailure()) {
                // add an event listener for once the event is decrypted.
                event.once("Event.decrypted", () => {
                    if (!this.eventIsACall(event))
                        return;
                    if (this.callEventBuffer.includes(event)) {
                        // we were waiting for that event to decrypt, so recheck the buffer
                        this.evaluateEventBuffer();
                    }
                    else {
                        // This one wasn't buffered so just run the event handler for it
                        // straight away
                        try {
                            this.handleCallEvent(event);
                        }
                        catch (e) {
                            logger_1.logger.error("Caught exception handling call event", e);
                        }
                    }
                });
            }
        };
        this.client = client;
        this.calls = new Map();
        // The sync code always emits one event at a time, so it will patiently
        // wait for us to finish processing a call invite before delivering the
        // next event, even if that next event is a hangup. We therefore accumulate
        // all our call events and then process them on the 'sync' event, ie.
        // each time a sync has completed. This way, we can avoid emitting incoming
        // call events if we get both the invite and answer/hangup in the same sync.
        // This happens quite often, eg. replaying sync from storage, catchup sync
        // after loading and after we've been offline for a bit.
        this.callEventBuffer = [];
        this.candidateEventsByCall = new Map();
    }
    start() {
        this.client.on("sync", this.evaluateEventBuffer);
        this.client.on("event", this.onEvent);
    }
    stop() {
        this.client.removeListener("sync", this.evaluateEventBuffer);
        this.client.removeListener("event", this.onEvent);
    }
    eventIsACall(event) {
        const type = event.getType();
        /**
         * Unstable prefixes:
         *   - org.matrix.call. : MSC3086 https://github.com/matrix-org/matrix-doc/pull/3086
         */
        return type.startsWith("m.call.") || type.startsWith("org.matrix.call.");
    }
    handleCallEvent(event) {
        const content = event.getContent();
        let call = content.call_id ? this.calls.get(content.call_id) : undefined;
        //console.info("RECV %s content=%s", event.getType(), JSON.stringify(content));
        if (event.getType() === event_1.EventType.CallInvite) {
            if (event.getSender() === this.client.credentials.userId) {
                return; // ignore invites you send
            }
            if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) {
                return; // expired call
            }
            if (call && call.state === call_1.CallState.Ended) {
                return; // stale/old invite event
            }
            if (call) {
                logger_1.logger.log(`WARN: Already have a MatrixCall with id ${content.call_id} but got an ` +
                    `invite. Clobbering.`);
            }
            if (content.invitee && content.invitee !== this.client.getUserId()) {
                return; // This invite was meant for another user in the room
            }
            const timeUntilTurnCresExpire = this.client.getTurnServersExpiry() - Date.now();
            logger_1.logger.info("Current turn creds expire in " + timeUntilTurnCresExpire + " ms");
            call = call_1.createNewMatrixCall(this.client, event.getRoomId(), {
                forceTURN: this.client.forceTURN,
            });
            if (!call) {
                logger_1.logger.log("Incoming call ID " + content.call_id + " but this client " +
                    "doesn't support WebRTC");
                // don't hang up the call: there could be other clients
                // connected that do support WebRTC and declining the
                // the call on their behalf would be really annoying.
                return;
            }
            call.callId = content.call_id;
            const invitePromise = call.initWithInvite(event);
            this.calls.set(call.callId, call);
            // if we stashed candidate events for that call ID, play them back now
            if (this.candidateEventsByCall.get(call.callId)) {
                for (const ev of this.candidateEventsByCall.get(call.callId)) {
                    call.onRemoteIceCandidatesReceived(ev);
                }
            }
            // Were we trying to call that user (room)?
            let existingCall;
            for (const thisCall of this.calls.values()) {
                const isCalling = [call_1.CallState.WaitLocalMedia, call_1.CallState.CreateOffer, call_1.CallState.InviteSent].includes(thisCall.state);
                if (call.roomId === thisCall.roomId &&
                    thisCall.direction === call_1.CallDirection.Outbound &&
                    call.invitee === thisCall.invitee &&
                    isCalling) {
                    existingCall = thisCall;
                    break;
                }
            }
            if (existingCall) {
                // If we've only got to wait_local_media or create_offer and
                // we've got an invite, pick the incoming call because we know
                // we haven't sent our invite yet otherwise, pick whichever
                // call has the lowest call ID (by string comparison)
                if (existingCall.state === call_1.CallState.WaitLocalMedia ||
                    existingCall.state === call_1.CallState.CreateOffer ||
                    existingCall.callId > call.callId) {
                    logger_1.logger.log("Glare detected: answering incoming call " + call.callId +
                        " and canceling outgoing call " + existingCall.callId);
                    existingCall.replacedBy(call);
                    call.answer();
                }
                else {
                    logger_1.logger.log("Glare detected: rejecting incoming call " + call.callId +
                        " and keeping outgoing call " + existingCall.callId);
                    call.hangup(call_1.CallErrorCode.Replaced, true);
                }
            }
            else {
                invitePromise.then(() => {
                    this.client.emit("Call.incoming", call);
                });
            }
        }
        else if (event.getType() === event_1.EventType.CallAnswer) {
            if (!call) {
                return;
            }
            if (event.getSender() === this.client.credentials.userId) {
                if (call.state === call_1.CallState.Ringing) {
                    call.onAnsweredElsewhere(content);
                }
            }
            else {
                call.onAnswerReceived(event);
            }
        }
        else if (event.getType() === event_1.EventType.CallCandidates) {
            if (event.getSender() === this.client.credentials.userId) {
                return;
            }
            if (!call) {
                // store the candidates; we may get a call eventually.
                if (!this.candidateEventsByCall.has(content.call_id)) {
                    this.candidateEventsByCall.set(content.call_id, []);
                }
                this.candidateEventsByCall.get(content.call_id).push(event);
            }
            else {
                call.onRemoteIceCandidatesReceived(event);
            }
        }
        else if ([event_1.EventType.CallHangup, event_1.EventType.CallReject].includes(event.getType())) {
            // Note that we also observe our own hangups here so we can see
            // if we've already rejected a call that would otherwise be valid
            if (!call) {
                // if not live, store the fact that the call has ended because
                // we're probably getting events backwards so
                // the hangup will come before the invite
                call = call_1.createNewMatrixCall(this.client, event.getRoomId());
                if (call) {
                    call.callId = content.call_id;
                    call.initWithHangup(event);
                    this.calls.set(content.call_id, call);
                }
            }
            else {
                if (call.state !== call_1.CallState.Ended) {
                    if (event.getType() === event_1.EventType.CallHangup) {
                        call.onHangupReceived(content);
                    }
                    else {
                        call.onRejectReceived(content);
                    }
                    this.calls.delete(content.call_id);
                }
            }
        }
        else if (event.getType() === event_1.EventType.CallSelectAnswer) {
            if (!call)
                return;
            if (event.getContent().party_id === call.ourPartyId) {
                // Ignore remote echo
                return;
            }
            call.onSelectAnswerReceived(event);
        }
        else if (event.getType() === event_1.EventType.CallNegotiate) {
            if (!call)
                return;
            if (event.getContent().party_id === call.ourPartyId) {
                // Ignore remote echo
                return;
            }
            call.onNegotiateReceived(event);
        }
        else if (event.getType() === event_1.EventType.CallAssertedIdentity ||
            event.getType() === event_1.EventType.CallAssertedIdentityPrefix) {
            if (!call)
                return;
            if (event.getContent().party_id === call.ourPartyId) {
                // Ignore remote echo (not that we send asserted identity, but still...)
                return;
            }
            call.onAssertedIdentityReceived(event);
        }
    }
}
exports.CallEventHandler = CallEventHandler;

},{"../@types/event":58,"../logger":106,"./call":138}],140:[function(require,module,exports){
"use strict";
// allow camelcase as these are events type that go onto the wire
/* eslint-disable camelcase */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SDPStreamMetadataPurpose = void 0;
var SDPStreamMetadataPurpose;
(function (SDPStreamMetadataPurpose) {
    SDPStreamMetadataPurpose["Usermedia"] = "m.usermedia";
    SDPStreamMetadataPurpose["Screenshare"] = "m.screenshare";
})(SDPStreamMetadataPurpose = exports.SDPStreamMetadataPurpose || (exports.SDPStreamMetadataPurpose = {}));
/* eslint-enable camelcase */

},{}],141:[function(require,module,exports){
"use strict";
/*
Copyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallFeed = exports.CallFeedEvent = void 0;
const events_1 = __importDefault(require("events"));
var CallFeedEvent;
(function (CallFeedEvent) {
    CallFeedEvent["NewStream"] = "new_stream";
})(CallFeedEvent = exports.CallFeedEvent || (exports.CallFeedEvent = {}));
class CallFeed extends events_1.default {
    constructor(stream, userId, purpose, client, roomId) {
        super();
        this.stream = stream;
        this.userId = userId;
        this.purpose = purpose;
        this.client = client;
        this.roomId = roomId;
    }
    /**
     * Returns callRoom member
     * @returns member of the callRoom
     */
    getMember() {
        const callRoom = this.client.getRoom(this.roomId);
        return callRoom.getMember(this.userId);
    }
    /**
     * Returns true if CallFeed is local, otherwise returns false
     * @returns {boolean} is local?
     */
    isLocal() {
        return this.userId === this.client.getUserId();
    }
    // TODO: The two following methods should be later replaced
    // by something that will also check if the remote is muted
    /**
     * Returns true if audio is muted or if there are no audio
     * tracks, otherwise returns false
     * @returns {boolean} is audio muted?
     */
    isAudioMuted() {
        return this.stream.getAudioTracks().length === 0;
    }
    /**
     * Returns true video is muted or if there are no video
     * tracks, otherwise returns false
     * @returns {boolean} is video muted?
     */
    isVideoMuted() {
        // We assume only one video track
        return this.stream.getVideoTracks().length === 0;
    }
    /**
     * Replaces the current MediaStream with a new one.
     * This method should be only used by MatrixCall.
     * @param newStream new stream with which to replace the current one
     */
    setNewStream(newStream) {
        this.stream = newStream;
        this.emit(CallFeedEvent.NewStream, this.stream);
    }
}
exports.CallFeed = CallFeed;

},{"events":36}]},{},[63])
//# sourceMappingURL=browser-matrix.js.map
