', {}, {\n CurrentPageURL: getRedactedUrl()\n })\n }, { expl: (0, _languageHandler._td)('Your User Agent'), value: navigator.userAgent }, { expl: (0, _languageHandler._td)('Your device resolution'), value: resolution }];\n\n var ErrorDialog = _index2.default.getComponent('dialogs.ErrorDialog');\n _Modal2.default.createTrackedDialog('Analytics Details', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Analytics'),\n description: React.createElement(\n 'div',\n { className: 'mx_AnalyticsModal' },\n React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)('The information being sent to us to help make Riot.im better includes:')\n ),\n React.createElement(\n 'table',\n null,\n rows.map(function (row) {\n return React.createElement(\n 'tr',\n { key: row[0] },\n React.createElement(\n 'td',\n null,\n (0, _languageHandler._t)(customVariables[row[0]].expl)\n ),\n row[1] !== undefined && React.createElement(\n 'td',\n null,\n React.createElement(\n 'code',\n null,\n row[1]\n )\n )\n );\n }),\n otherVariables.map(function (item, index) {\n return React.createElement(\n 'tr',\n { key: index },\n React.createElement(\n 'td',\n null,\n (0, _languageHandler._t)(item.expl)\n ),\n React.createElement(\n 'td',\n null,\n React.createElement(\n 'code',\n null,\n item.value\n )\n )\n );\n })\n ),\n React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)('Where this page includes identifiable information, such as a room, ' + 'user or group ID, that data is removed before being sent to the server.')\n )\n )\n });\n }\n }]);\n return Analytics;\n}();\n\nif (!global.mxAnalytics) {\n global.mxAnalytics = new Analytics();\n}\nmodule.exports = global.mxAnalytics;\n//# sourceMappingURL=Analytics.js.map","\"use strict\";\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * Holds the current Platform object used by the code to do anything\n * specific to the platform we're running on (eg. web, electron)\n * Platforms are provided by the app layer.\n * This allows the app layer to set a Platform without necessarily\n * having to have a MatrixChat object\n */\nvar PlatformPeg = function () {\n function PlatformPeg() {\n (0, _classCallCheck3.default)(this, PlatformPeg);\n\n this.platform = null;\n }\n\n /**\n * Returns the current Platform object for the application.\n * This should be an instance of a class extending BasePlatform.\n */\n\n\n (0, _createClass3.default)(PlatformPeg, [{\n key: \"get\",\n value: function get() {\n return this.platform;\n }\n\n /**\n * Sets the current platform handler object to use for the\n * application.\n * This should be an instance of a class extending BasePlatform.\n */\n\n }, {\n key: \"set\",\n value: function set(plaf) {\n this.platform = plaf;\n }\n }]);\n return PlatformPeg;\n}();\n\nif (!global.mxPlatformPeg) {\n global.mxPlatformPeg = new PlatformPeg();\n}\nmodule.exports = global.mxPlatformPeg;\n//# sourceMappingURL=PlatformPeg.js.map","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n","// 7.1.13 ToObject(argument)\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return Object(defined(it));\n};\n","\"use strict\";\n\nexports.__esModule = true;\n\nvar _iterator = require(\"../core-js/symbol/iterator\");\n\nvar _iterator2 = _interopRequireDefault(_iterator);\n\nvar _symbol = require(\"../core-js/symbol\");\n\nvar _symbol2 = _interopRequireDefault(_symbol);\n\nvar _typeof = typeof _symbol2.default === \"function\" && typeof _iterator2.default === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === \"function\" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? \"symbol\" : typeof obj; };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = typeof _symbol2.default === \"function\" && _typeof(_iterator2.default) === \"symbol\" ? function (obj) {\n return typeof obj === \"undefined\" ? \"undefined\" : _typeof(obj);\n} : function (obj) {\n return obj && typeof _symbol2.default === \"function\" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? \"symbol\" : typeof obj === \"undefined\" ? \"undefined\" : _typeof(obj);\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isOnlyCtrlOrCmdKeyEvent = isOnlyCtrlOrCmdKeyEvent;\nexports.isOnlyCtrlOrCmdIgnoreShiftKeyEvent = isOnlyCtrlOrCmdIgnoreShiftKeyEvent;\n/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* a selection of key codes, as used in KeyboardEvent.keyCode */\nvar KeyCode = exports.KeyCode = {\n BACKSPACE: 8,\n TAB: 9,\n ENTER: 13,\n SHIFT: 16,\n ESCAPE: 27,\n SPACE: 32,\n PAGE_UP: 33,\n PAGE_DOWN: 34,\n END: 35,\n HOME: 36,\n LEFT: 37,\n UP: 38,\n RIGHT: 39,\n DOWN: 40,\n DELETE: 46,\n KEY_A: 65,\n KEY_B: 66,\n KEY_C: 67,\n KEY_D: 68,\n KEY_E: 69,\n KEY_F: 70,\n KEY_G: 71,\n KEY_H: 72,\n KEY_I: 73,\n KEY_J: 74,\n KEY_K: 75,\n KEY_L: 76,\n KEY_M: 77,\n KEY_N: 78,\n KEY_O: 79,\n KEY_P: 80,\n KEY_Q: 81,\n KEY_R: 82,\n KEY_S: 83,\n KEY_T: 84,\n KEY_U: 85,\n KEY_V: 86,\n KEY_W: 87,\n KEY_X: 88,\n KEY_Y: 89,\n KEY_Z: 90,\n KEY_BACKTICK: 223 // DO NOT USE THIS: browsers disagree on backtick 192 vs 223\n};\n\nvar Key = exports.Key = {\n HOME: \"Home\",\n End: \"End\",\n PAGE_UP: \"PageUp\",\n PAGE_DOWN: \"PageDown\",\n BACKTICK: \"`\",\n\n K: \"k\"\n};\n\nfunction isOnlyCtrlOrCmdKeyEvent(ev) {\n var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;\n if (isMac) {\n return ev.metaKey && !ev.altKey && !ev.ctrlKey && !ev.shiftKey;\n } else {\n return ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey;\n }\n}\n\nfunction isOnlyCtrlOrCmdIgnoreShiftKeyEvent(ev) {\n var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;\n if (isMac) {\n return ev.metaKey && !ev.altKey && !ev.ctrlKey;\n } else {\n return ev.ctrlKey && !ev.altKey && !ev.metaKey;\n }\n}\n//# sourceMappingURL=Keyboard.js.map","/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017, 2018 New Vector Ltd\nCopyright 2019 Michael Telatynski <7t3chguy@gmail.com>\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _assign = require('babel-runtime/core-js/object/assign');\n\nvar _assign2 = _interopRequireDefault(_assign);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nexports.unicodeToShortcode = unicodeToShortcode;\nexports.shortcodeToUnicode = shortcodeToUnicode;\nexports.processHtmlForSending = processHtmlForSending;\nexports.sanitizedHtmlNode = sanitizedHtmlNode;\nexports.isUrlPermitted = isUrlPermitted;\nexports.bodyToHtml = bodyToHtml;\nexports.linkifyString = linkifyString;\nexports.linkifyElement = linkifyElement;\nexports.linkifyAndSanitizeHtml = linkifyAndSanitizeHtml;\nexports.checkBlockNode = checkBlockNode;\n\nvar _ReplyThread = require('./components/views/elements/ReplyThread');\n\nvar _ReplyThread2 = _interopRequireDefault(_ReplyThread);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _sanitizeHtml = require('sanitize-html');\n\nvar _sanitizeHtml2 = _interopRequireDefault(_sanitizeHtml);\n\nvar _highlight = require('highlight.js');\n\nvar _highlight2 = _interopRequireDefault(_highlight);\n\nvar _linkifyjs = require('linkifyjs');\n\nvar linkify = _interopRequireWildcard(_linkifyjs);\n\nvar _linkifyMatrix = require('./linkify-matrix');\n\nvar _linkifyMatrix2 = _interopRequireDefault(_linkifyMatrix);\n\nvar _element = require('linkifyjs/element');\n\nvar _element2 = _interopRequireDefault(_element);\n\nvar _string = require('linkifyjs/string');\n\nvar _string2 = _interopRequireDefault(_string);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _url = require('url');\n\nvar _url2 = _interopRequireDefault(_url);\n\nvar _compact = require('emojibase-data/en/compact.json');\n\nvar _compact2 = _interopRequireDefault(_compact);\n\nvar _emojibaseRegex = require('emojibase-regex');\n\nvar _emojibaseRegex2 = _interopRequireDefault(_emojibaseRegex);\n\nvar _Permalinks = require('./utils/permalinks/Permalinks');\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n(0, _linkifyMatrix2.default)(linkify);\n\n// Anything outside the basic multilingual plane will be a surrogate pair\nvar SURROGATE_PAIR_PATTERN = /([\\ud800-\\udbff])([\\udc00-\\udfff])/;\n// And there a bunch more symbol characters that emojibase has within the\n// BMP, so this includes the ranges from 'letterlike symbols' to\n// 'miscellaneous symbols and arrows' which should catch all of them\n// (with plenty of false positives, but that's OK)\nvar SYMBOL_PATTERN = /([\\u2100-\\u2bff])/;\n\n// Regex pattern for Zero-Width joiner unicode characters\nvar ZWJ_REGEX = new RegExp('\\u200D|\\u2003', \"g\");\n\n// Regex pattern for whitespace characters\nvar WHITESPACE_REGEX = new RegExp(\"\\\\s\", \"g\");\n\nvar BIGEMOJI_REGEX = new RegExp('^(' + _emojibaseRegex2.default.source + ')+$', 'i');\nvar SINGLE_EMOJI_REGEX = new RegExp('^(' + _emojibaseRegex2.default.source + ')$', 'i');\n\nvar COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;\n\nvar PERMITTED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'magnet'];\n\nvar VARIATION_SELECTOR = String.fromCharCode(0xFE0F);\n\n/*\n * Return true if the given string contains emoji\n * Uses a much, much simpler regex than emojibase's so will give false\n * positives, but useful for fast-path testing strings to see if they\n * need emojification.\n * unicodeToImage uses this function.\n */\nfunction mightContainEmoji(str) {\n return SURROGATE_PAIR_PATTERN.test(str) || SYMBOL_PATTERN.test(str);\n}\n\n/**\n * Returns the shortcode for an emoji character.\n *\n * @param {String} char The emoji character\n * @return {String} The shortcode (such as :thumbup:)\n */\nfunction unicodeToShortcode(char) {\n // Check against both the char and the char with an empty variation selector appended because that's how\n // emoji-base stores its base emojis which have variations. https://github.com/vector-im/riot-web/issues/9785\n var emptyVariation = char + VARIATION_SELECTOR;\n var data = _compact2.default.find(function (e) {\n return e.unicode === char || e.unicode === emptyVariation;\n });\n return data && data.shortcodes ? ':' + data.shortcodes[0] + ':' : '';\n}\n\n/**\n * Returns the unicode character for an emoji shortcode\n *\n * @param {String} shortcode The shortcode (such as :thumbup:)\n * @return {String} The emoji character; null if none exists\n */\nfunction shortcodeToUnicode(shortcode) {\n shortcode = shortcode.slice(1, shortcode.length - 1);\n var data = _compact2.default.find(function (e) {\n return e.shortcodes && e.shortcodes.includes(shortcode);\n });\n return data ? data.unicode : null;\n}\n\nfunction processHtmlForSending(html) {\n var contentDiv = document.createElement('div');\n contentDiv.innerHTML = html;\n\n if (contentDiv.children.length === 0) {\n return contentDiv.innerHTML;\n }\n\n var contentHTML = \"\";\n for (var i = 0; i < contentDiv.children.length; i++) {\n var element = contentDiv.children[i];\n if (element.tagName.toLowerCase() === 'p') {\n contentHTML += element.innerHTML;\n // Don't add a
for the last \n if (i !== contentDiv.children.length - 1) {\n contentHTML += '
';\n }\n } else {\n var temp = document.createElement('div');\n temp.appendChild(element.cloneNode(true));\n contentHTML += temp.innerHTML;\n }\n }\n\n return contentHTML;\n}\n\n/*\n * Given an untrusted HTML string, return a React node with an sanitized version\n * of that HTML.\n */\nfunction sanitizedHtmlNode(insaneHtml) {\n var saneHtml = (0, _sanitizeHtml2.default)(insaneHtml, sanitizeHtmlParams);\n\n return _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: saneHtml }, dir: 'auto' });\n}\n\n/**\n * Tests if a URL from an untrusted source may be safely put into the DOM\n * The biggest threat here is javascript: URIs.\n * Note that the HTML sanitiser library has its own internal logic for\n * doing this, to which we pass the same list of schemes. This is used in\n * other places we need to sanitise URLs.\n * @return true if permitted, otherwise false\n */\nfunction isUrlPermitted(inputUrl) {\n try {\n var parsed = _url2.default.parse(inputUrl);\n if (!parsed.protocol) return false;\n // URL parser protocol includes the trailing colon\n return PERMITTED_URL_SCHEMES.includes(parsed.protocol.slice(0, -1));\n } catch (e) {\n return false;\n }\n}\n\nvar transformTags = { // custom to matrix\n // add blank targets to all hyperlinks except vector URLs\n 'a': function a(tagName, attribs) {\n if (attribs.href) {\n attribs.target = '_blank'; // by default\n\n var transformed = (0, _Permalinks.tryTransformPermalinkToLocalHref)(attribs.href);\n if (transformed !== attribs.href || attribs.href.match(_linkifyMatrix2.default.VECTOR_URL_PATTERN)) {\n attribs.href = transformed;\n delete attribs.target;\n }\n }\n attribs.rel = 'noopener'; // https://mathiasbynens.github.io/rel-noopener/\n return { tagName: tagName, attribs: attribs };\n },\n 'img': function img(tagName, attribs) {\n // Strip out imgs that aren't `mxc` here instead of using allowedSchemesByTag\n // because transformTags is used _before_ we filter by allowedSchemesByTag and\n // we don't want to allow images with `https?` `src`s.\n if (!attribs.src || !attribs.src.startsWith('mxc://')) {\n return { tagName: tagName, attribs: {} };\n }\n attribs.src = _MatrixClientPeg2.default.get().mxcUrlToHttp(attribs.src, attribs.width || 800, attribs.height || 600);\n return { tagName: tagName, attribs: attribs };\n },\n 'code': function code(tagName, attribs) {\n if (typeof attribs.class !== 'undefined') {\n // Filter out all classes other than ones starting with language- for syntax highlighting.\n var classes = attribs.class.split(/\\s/).filter(function (cl) {\n return cl.startsWith('language-');\n });\n attribs.class = classes.join(' ');\n }\n return { tagName: tagName, attribs: attribs };\n },\n '*': function _(tagName, attribs) {\n // Delete any style previously assigned, style is an allowedTag for font and span\n // because attributes are stripped after transforming\n delete attribs.style;\n\n // Sanitise and transform data-mx-color and data-mx-bg-color to their CSS\n // equivalents\n var customCSSMapper = {\n 'data-mx-color': 'color',\n 'data-mx-bg-color': 'background-color'\n // $customAttributeKey: $cssAttributeKey\n };\n\n var style = \"\";\n (0, _keys2.default)(customCSSMapper).forEach(function (customAttributeKey) {\n var cssAttributeKey = customCSSMapper[customAttributeKey];\n var customAttributeValue = attribs[customAttributeKey];\n if (customAttributeValue && typeof customAttributeValue === 'string' && COLOR_REGEX.test(customAttributeValue)) {\n style += cssAttributeKey + \":\" + customAttributeValue + \";\";\n delete attribs[customAttributeKey];\n }\n });\n\n if (style) {\n attribs.style = style;\n }\n\n return { tagName: tagName, attribs: attribs };\n }\n};\n\nvar sanitizeHtmlParams = {\n allowedTags: ['font', // custom to matrix for IRC-style font coloring\n 'del', // for markdown\n 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'sup', 'sub', 'nl', 'li', 'b', 'i', 'u', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'span', 'img'],\n allowedAttributes: {\n // custom ones first:\n font: ['color', 'data-mx-bg-color', 'data-mx-color', 'style'], // custom to matrix\n span: ['data-mx-bg-color', 'data-mx-color', 'data-mx-spoiler', 'style'], // custom to matrix\n a: ['href', 'name', 'target', 'rel'], // remote target: custom to matrix\n img: ['src', 'width', 'height', 'alt', 'title'],\n ol: ['start'],\n code: ['class'] // We don't actually allow all classes, we filter them in transformTags\n },\n // Lots of these won't come up by default because we don't allow them\n selfClosing: ['img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta'],\n // URL schemes we permit\n allowedSchemes: PERMITTED_URL_SCHEMES,\n\n allowProtocolRelative: false,\n transformTags: transformTags\n};\n\n// this is the same as the above except with less rewriting\nvar composerSanitizeHtmlParams = (0, _assign2.default)({}, sanitizeHtmlParams);\ncomposerSanitizeHtmlParams.transformTags = {\n 'code': transformTags['code'],\n '*': transformTags['*']\n};\n\nvar BaseHighlighter = function () {\n function BaseHighlighter(highlightClass, highlightLink) {\n (0, _classCallCheck3.default)(this, BaseHighlighter);\n\n this.highlightClass = highlightClass;\n this.highlightLink = highlightLink;\n }\n\n /**\n * apply the highlights to a section of text\n *\n * @param {string} safeSnippet The snippet of text to apply the highlights\n * to.\n * @param {string[]} safeHighlights A list of substrings to highlight,\n * sorted by descending length.\n *\n * returns a list of results (strings for HtmlHighligher, react nodes for\n * TextHighlighter).\n */\n\n\n (0, _createClass3.default)(BaseHighlighter, [{\n key: 'applyHighlights',\n value: function applyHighlights(safeSnippet, safeHighlights) {\n var lastOffset = 0;\n var offset = void 0;\n var nodes = [];\n\n var safeHighlight = safeHighlights[0];\n while ((offset = safeSnippet.toLowerCase().indexOf(safeHighlight.toLowerCase(), lastOffset)) >= 0) {\n // handle preamble\n if (offset > lastOffset) {\n var subSnippet = safeSnippet.substring(lastOffset, offset);\n nodes = nodes.concat(this._applySubHighlights(subSnippet, safeHighlights));\n }\n\n // do highlight. use the original string rather than safeHighlight\n // to preserve the original casing.\n var endOffset = offset + safeHighlight.length;\n nodes.push(this._processSnippet(safeSnippet.substring(offset, endOffset), true));\n\n lastOffset = endOffset;\n }\n\n // handle postamble\n if (lastOffset !== safeSnippet.length) {\n subSnippet = safeSnippet.substring(lastOffset, undefined);\n nodes = nodes.concat(this._applySubHighlights(subSnippet, safeHighlights));\n }\n return nodes;\n }\n }, {\n key: '_applySubHighlights',\n value: function _applySubHighlights(safeSnippet, safeHighlights) {\n if (safeHighlights[1]) {\n // recurse into this range to check for the next set of highlight matches\n return this.applyHighlights(safeSnippet, safeHighlights.slice(1));\n } else {\n // no more highlights to be found, just return the unhighlighted string\n return [this._processSnippet(safeSnippet, false)];\n }\n }\n }]);\n return BaseHighlighter;\n}();\n\nvar HtmlHighlighter = function (_BaseHighlighter) {\n (0, _inherits3.default)(HtmlHighlighter, _BaseHighlighter);\n\n function HtmlHighlighter() {\n (0, _classCallCheck3.default)(this, HtmlHighlighter);\n return (0, _possibleConstructorReturn3.default)(this, (HtmlHighlighter.__proto__ || (0, _getPrototypeOf2.default)(HtmlHighlighter)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(HtmlHighlighter, [{\n key: '_processSnippet',\n\n /* highlight the given snippet if required\n *\n * snippet: content of the span; must have been sanitised\n * highlight: true to highlight as a search match\n *\n * returns an HTML string\n */\n value: function _processSnippet(snippet, highlight) {\n if (!highlight) {\n // nothing required here\n return snippet;\n }\n\n var span = \"\" + snippet + \"\";\n\n if (this.highlightLink) {\n span = \"\" + span + \"\";\n }\n return span;\n }\n }]);\n return HtmlHighlighter;\n}(BaseHighlighter);\n\nvar TextHighlighter = function (_BaseHighlighter2) {\n (0, _inherits3.default)(TextHighlighter, _BaseHighlighter2);\n\n function TextHighlighter(highlightClass, highlightLink) {\n (0, _classCallCheck3.default)(this, TextHighlighter);\n\n var _this2 = (0, _possibleConstructorReturn3.default)(this, (TextHighlighter.__proto__ || (0, _getPrototypeOf2.default)(TextHighlighter)).call(this, highlightClass, highlightLink));\n\n _this2._key = 0;\n return _this2;\n }\n\n /* create a node to hold the given content\n *\n * snippet: content of the span\n * highlight: true to highlight as a search match\n *\n * returns a React node\n */\n\n\n (0, _createClass3.default)(TextHighlighter, [{\n key: '_processSnippet',\n value: function _processSnippet(snippet, highlight) {\n var key = this._key++;\n\n var node = _react2.default.createElement(\n 'span',\n { key: key, className: highlight ? this.highlightClass : null },\n snippet\n );\n\n if (highlight && this.highlightLink) {\n node = _react2.default.createElement(\n 'a',\n { key: key, href: this.highlightLink },\n node\n );\n }\n\n return node;\n }\n }]);\n return TextHighlighter;\n}(BaseHighlighter);\n\n/* turn a matrix event body into html\n *\n * content: 'content' of the MatrixEvent\n *\n * highlights: optional list of words to highlight, ordered by longest word first\n *\n * opts.highlightLink: optional href to add to highlighted words\n * opts.disableBigEmoji: optional argument to disable the big emoji class.\n * opts.stripReplyFallback: optional argument specifying the event is a reply and so fallback needs removing\n * opts.returnString: return an HTML string rather than JSX elements\n * opts.forComposerQuote: optional param to lessen the url rewriting done by sanitization, for quoting into composer\n */\n\n\nfunction bodyToHtml(content, highlights) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n var isHtmlMessage = content.format === \"org.matrix.custom.html\" && content.formatted_body;\n var bodyHasEmoji = false;\n\n var sanitizeParams = sanitizeHtmlParams;\n if (opts.forComposerQuote) {\n sanitizeParams = composerSanitizeHtmlParams;\n }\n\n var strippedBody = void 0;\n var safeBody = void 0;\n var isDisplayedWithHtml = void 0;\n // XXX: We sanitize the HTML whilst also highlighting its text nodes, to avoid accidentally trying\n // to highlight HTML tags themselves. However, this does mean that we don't highlight textnodes which\n // are interrupted by HTML tags (not that we did before) - e.g. foobar won't get highlighted\n // by an attempt to search for 'foobar'. Then again, the search query probably wouldn't work either\n try {\n if (highlights && highlights.length > 0) {\n var highlighter = new HtmlHighlighter(\"mx_EventTile_searchHighlight\", opts.highlightLink);\n var safeHighlights = highlights.map(function (highlight) {\n return (0, _sanitizeHtml2.default)(highlight, sanitizeParams);\n });\n // XXX: hacky bodge to temporarily apply a textFilter to the sanitizeParams structure.\n sanitizeParams.textFilter = function (safeText) {\n return highlighter.applyHighlights(safeText, safeHighlights).join('');\n };\n }\n\n var formattedBody = content.formatted_body;\n if (opts.stripReplyFallback && formattedBody) formattedBody = _ReplyThread2.default.stripHTMLReply(formattedBody);\n strippedBody = opts.stripReplyFallback ? _ReplyThread2.default.stripPlainReply(content.body) : content.body;\n\n bodyHasEmoji = mightContainEmoji(isHtmlMessage ? formattedBody : content.body);\n\n // Only generate safeBody if the message was sent as org.matrix.custom.html\n if (isHtmlMessage) {\n isDisplayedWithHtml = true;\n safeBody = (0, _sanitizeHtml2.default)(formattedBody, sanitizeParams);\n }\n } finally {\n delete sanitizeParams.textFilter;\n }\n\n if (opts.returnString) {\n return isDisplayedWithHtml ? safeBody : strippedBody;\n }\n\n var emojiBody = false;\n if (!opts.disableBigEmoji && bodyHasEmoji) {\n var contentBodyTrimmed = strippedBody !== undefined ? strippedBody.trim() : '';\n\n // Ignore spaces in body text. Emojis with spaces in between should\n // still be counted as purely emoji messages.\n contentBodyTrimmed = contentBodyTrimmed.replace(WHITESPACE_REGEX, '');\n\n // Remove zero width joiner characters from emoji messages. This ensures\n // that emojis that are made up of multiple unicode characters are still\n // presented as large.\n contentBodyTrimmed = contentBodyTrimmed.replace(ZWJ_REGEX, '');\n\n var match = BIGEMOJI_REGEX.exec(contentBodyTrimmed);\n emojiBody = match && match[0] && match[0].length === contentBodyTrimmed.length && (\n // Prevent user pills expanding for users with only emoji in\n // their username. Permalinks (links in pills) can be any URL\n // now, so we just check for an HTTP-looking thing.\n content.formatted_body == undefined || !content.formatted_body.includes(\"http:\") && !content.formatted_body.includes(\"https:\"));\n }\n\n var className = (0, _classnames2.default)({\n 'mx_EventTile_body': true,\n 'mx_EventTile_bigEmoji': emojiBody,\n 'markdown-body': isHtmlMessage && !emojiBody\n });\n\n return isDisplayedWithHtml ? _react2.default.createElement('span', { key: 'body', className: className, dangerouslySetInnerHTML: { __html: safeBody }, dir: 'auto' }) : _react2.default.createElement(\n 'span',\n { key: 'body', className: className, dir: 'auto' },\n strippedBody\n );\n}\n\n/**\n * Linkifies the given string. This is a wrapper around 'linkifyjs/string'.\n *\n * @param {string} str\n * @returns {string}\n */\nfunction linkifyString(str) {\n return (0, _string2.default)(str);\n}\n\n/**\n * Linkifies the given DOM element. This is a wrapper around 'linkifyjs/element'.\n *\n * @param {object} element DOM element to linkify\n * @param {object} [options] Options for linkifyElement. Default: linkifyMatrix.options\n * @returns {object}\n */\nfunction linkifyElement(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _linkifyMatrix2.default.options;\n\n return (0, _element2.default)(element, options);\n}\n\n/**\n * Linkify the given string and sanitize the HTML afterwards.\n *\n * @param {string} dirtyHtml The HTML string to sanitize and linkify\n * @returns {string}\n */\nfunction linkifyAndSanitizeHtml(dirtyHtml) {\n return (0, _sanitizeHtml2.default)(linkifyString(dirtyHtml), sanitizeHtmlParams);\n}\n\n/**\n * Returns if a node is a block element or not.\n * Only takes html nodes into account that are allowed in matrix messages.\n *\n * @param {Node} node\n * @returns {bool}\n */\nfunction checkBlockNode(node) {\n switch (node.nodeName) {\n case \"H1\":\n case \"H2\":\n case \"H3\":\n case \"H4\":\n case \"H5\":\n case \"H6\":\n case \"PRE\":\n case \"BLOCKQUOTE\":\n case \"DIV\":\n case \"P\":\n case \"UL\":\n case \"OL\":\n case \"LI\":\n case \"HR\":\n case \"TABLE\":\n case \"THEAD\":\n case \"TBODY\":\n case \"TR\":\n case \"TH\":\n case \"TD\":\n return true;\n default:\n return false;\n }\n}\n//# sourceMappingURL=HtmlUtils.js.map","'use strict';\n\nvar _stringify = require('babel-runtime/core-js/json/stringify');\n\nvar _stringify2 = _interopRequireDefault(_stringify);\n\nvar _assign = require('babel-runtime/core-js/object/assign');\n\nvar _assign2 = _interopRequireDefault(_assign);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _dispatcher = require('../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _utils = require('flux/utils');\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _index = require('../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _Modal = require('../Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _languageHandler = require('../languageHandler');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2017, 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nvar INITIAL_STATE = {\n // Whether we're joining the currently viewed room (see isJoining())\n joining: false,\n // Any error that has occurred during joining\n joinError: null,\n // The room ID of the room currently being viewed\n roomId: null,\n\n // The event to scroll to when the room is first viewed\n initialEventId: null,\n // Whether to highlight the initial event\n isInitialEventHighlighted: false,\n\n // The room alias of the room (or null if not originally specified in view_room)\n roomAlias: null,\n // Whether the current room is loading\n roomLoading: false,\n // Any error that has occurred during loading\n roomLoadError: null,\n\n forwardingEvent: null,\n\n quotingEvent: null\n};\n\n/**\n * A class for storing application state for RoomView. This is the RoomView's interface\n* with a subset of the js-sdk.\n * ```\n */\n\nvar RoomViewStore = function (_Store) {\n (0, _inherits3.default)(RoomViewStore, _Store);\n\n function RoomViewStore() {\n (0, _classCallCheck3.default)(this, RoomViewStore);\n\n // Initialise state\n var _this = (0, _possibleConstructorReturn3.default)(this, (RoomViewStore.__proto__ || (0, _getPrototypeOf2.default)(RoomViewStore)).call(this, _dispatcher2.default));\n\n _this._state = INITIAL_STATE;\n return _this;\n }\n\n (0, _createClass3.default)(RoomViewStore, [{\n key: '_setState',\n value: function _setState(newState) {\n this._state = (0, _assign2.default)(this._state, newState);\n this.__emitChange();\n }\n }, {\n key: '__onDispatch',\n value: function __onDispatch(payload) {\n switch (payload.action) {\n // view_room:\n // - room_alias: '#somealias:matrix.org'\n // - room_id: '!roomid123:matrix.org'\n // - event_id: '$213456782:matrix.org'\n // - event_offset: 100\n // - highlighted: true\n case 'view_room':\n this._viewRoom(payload);\n break;\n case 'view_my_groups':\n case 'view_group':\n this._setState({\n roomId: null,\n roomAlias: null\n });\n break;\n case 'view_room_error':\n this._viewRoomError(payload);\n break;\n case 'will_join':\n this._setState({\n joining: true\n });\n break;\n case 'cancel_join':\n this._setState({\n joining: false\n });\n break;\n // join_room:\n // - opts: options for joinRoom\n case 'join_room':\n this._joinRoom(payload);\n break;\n case 'join_room_error':\n this._joinRoomError(payload);\n break;\n case 'on_client_not_viable':\n case 'on_logged_out':\n this.reset();\n break;\n case 'forward_event':\n this._setState({\n forwardingEvent: payload.event\n });\n break;\n case 'reply_to_event':\n // If currently viewed room does not match the room in which we wish to reply then change rooms\n // this can happen when performing a search across all rooms\n if (payload.event && payload.event.getRoomId() !== this._state.roomId) {\n _dispatcher2.default.dispatch({\n action: 'view_room',\n room_id: payload.event.getRoomId(),\n replyingToEvent: payload.event\n });\n } else {\n this._setState({\n replyingToEvent: payload.event\n });\n }\n break;\n case 'open_room_settings':\n {\n var RoomSettingsDialog = _index2.default.getComponent(\"dialogs.RoomSettingsDialog\");\n _Modal2.default.createTrackedDialog('Room settings', '', RoomSettingsDialog, {\n roomId: payload.room_id || this._state.roomId\n }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true);\n break;\n }\n }\n }\n }, {\n key: '_viewRoom',\n value: function _viewRoom(payload) {\n if (payload.room_id) {\n var newState = {\n roomId: payload.room_id,\n roomAlias: payload.room_alias,\n initialEventId: payload.event_id,\n isInitialEventHighlighted: payload.highlighted,\n forwardingEvent: null,\n roomLoading: false,\n roomLoadError: null,\n // should peek by default\n shouldPeek: payload.should_peek === undefined ? true : payload.should_peek,\n // have we sent a join request for this room and are waiting for a response?\n joining: payload.joining || false,\n // Reset replyingToEvent because we don't want cross-room because bad UX\n replyingToEvent: null,\n // pull the user out of Room Settings\n isEditingSettings: false\n };\n\n // Allow being given an event to be replied to when switching rooms but sanity check its for this room\n if (payload.replyingToEvent && payload.replyingToEvent.getRoomId() === payload.room_id) {\n newState.replyingToEvent = payload.replyingToEvent;\n }\n\n if (this._state.forwardingEvent) {\n _dispatcher2.default.dispatch({\n action: 'send_event',\n room_id: newState.roomId,\n event: this._state.forwardingEvent\n });\n }\n\n this._setState(newState);\n\n if (payload.auto_join) {\n this._joinRoom(payload);\n }\n } else if (payload.room_alias) {\n // Resolve the alias and then do a second dispatch with the room ID acquired\n this._setState({\n roomId: null,\n initialEventId: null,\n initialEventPixelOffset: null,\n isInitialEventHighlighted: null,\n roomAlias: payload.room_alias,\n roomLoading: true,\n roomLoadError: null\n });\n _MatrixClientPeg2.default.get().getRoomIdForAlias(payload.room_alias).done(function (result) {\n _dispatcher2.default.dispatch({\n action: 'view_room',\n room_id: result.room_id,\n event_id: payload.event_id,\n highlighted: payload.highlighted,\n room_alias: payload.room_alias,\n auto_join: payload.auto_join,\n oob_data: payload.oob_data\n });\n }, function (err) {\n _dispatcher2.default.dispatch({\n action: 'view_room_error',\n room_id: null,\n room_alias: payload.room_alias,\n err: err\n });\n });\n }\n }\n }, {\n key: '_viewRoomError',\n value: function _viewRoomError(payload) {\n this._setState({\n roomId: payload.room_id,\n roomAlias: payload.room_alias,\n roomLoading: false,\n roomLoadError: payload.err\n });\n }\n }, {\n key: '_joinRoom',\n value: function _joinRoom(payload) {\n this._setState({\n joining: true\n });\n _MatrixClientPeg2.default.get().joinRoom(this._state.roomAlias || this._state.roomId, payload.opts).done(function () {\n // We don't actually need to do anything here: we do *not*\n // clear the 'joining' flag because the Room object and/or\n // our 'joined' member event may not have come down the sync\n // stream yet, and that's the point at which we'd consider\n // the user joined to the room.\n }, function (err) {\n _dispatcher2.default.dispatch({\n action: 'join_room_error',\n err: err\n });\n var msg = err.message ? err.message : (0, _stringify2.default)(err);\n // XXX: We are relying on the error message returned by browsers here.\n // This isn't great, but it does generalize the error being shown to users.\n if (msg && msg.startsWith(\"CORS request rejected\")) {\n msg = (0, _languageHandler._t)(\"There was an error joining the room\");\n }\n if (err.errcode === 'M_INCOMPATIBLE_ROOM_VERSION') {\n msg = React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)(\"Sorry, your homeserver is too old to participate in this room.\"),\n React.createElement('br', null),\n (0, _languageHandler._t)(\"Please contact your homeserver administrator.\")\n );\n }\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Failed to join room', '', ErrorDialog, {\n title: (0, _languageHandler._t)(\"Failed to join room\"),\n description: msg\n });\n });\n }\n }, {\n key: '_joinRoomError',\n value: function _joinRoomError(payload) {\n this._setState({\n joining: false,\n joinError: payload.err\n });\n }\n }, {\n key: 'reset',\n value: function reset() {\n this._state = (0, _assign2.default)({}, INITIAL_STATE);\n }\n\n // The room ID of the room currently being viewed\n\n }, {\n key: 'getRoomId',\n value: function getRoomId() {\n return this._state.roomId;\n }\n\n // The event to scroll to when the room is first viewed\n\n }, {\n key: 'getInitialEventId',\n value: function getInitialEventId() {\n return this._state.initialEventId;\n }\n\n // Whether to highlight the initial event\n\n }, {\n key: 'isInitialEventHighlighted',\n value: function isInitialEventHighlighted() {\n return this._state.isInitialEventHighlighted;\n }\n\n // The room alias of the room (or null if not originally specified in view_room)\n\n }, {\n key: 'getRoomAlias',\n value: function getRoomAlias() {\n return this._state.roomAlias;\n }\n\n // Whether the current room is loading (true whilst resolving an alias)\n\n }, {\n key: 'isRoomLoading',\n value: function isRoomLoading() {\n return this._state.roomLoading;\n }\n\n // Any error that has occurred during loading\n\n }, {\n key: 'getRoomLoadError',\n value: function getRoomLoadError() {\n return this._state.roomLoadError;\n }\n\n // True if we're expecting the user to be joined to the room currently being\n // viewed. Note that this is left true after the join request has finished,\n // since we should still consider a join to be in progress until the room\n // & member events come down the sync.\n //\n // This flag remains true after the room has been sucessfully joined,\n // (this store doesn't listen for the appropriate member events)\n // so you should always observe the joined state from the member event\n // if a room object is present.\n // ie. The correct logic is:\n // if (room) {\n // if (myMember.membership == 'joined') {\n // // user is joined to the room\n // } else {\n // // Not joined\n // }\n // } else {\n // if (RoomViewStore.isJoining()) {\n // // show spinner\n // } else {\n // // show join prompt\n // }\n // }\n\n }, {\n key: 'isJoining',\n value: function isJoining() {\n return this._state.joining;\n }\n\n // Any error that has occurred during joining\n\n }, {\n key: 'getJoinError',\n value: function getJoinError() {\n return this._state.joinError;\n }\n\n // The mxEvent if one is about to be forwarded\n\n }, {\n key: 'getForwardingEvent',\n value: function getForwardingEvent() {\n return this._state.forwardingEvent;\n }\n\n // The mxEvent if one is currently being replied to/quoted\n\n }, {\n key: 'getQuotingEvent',\n value: function getQuotingEvent() {\n return this._state.replyingToEvent;\n }\n }, {\n key: 'shouldPeek',\n value: function shouldPeek() {\n return this._state.shouldPeek;\n }\n }]);\n return RoomViewStore;\n}(_utils.Store);\n\nvar singletonRoomViewStore = null;\nif (!singletonRoomViewStore) {\n singletonRoomViewStore = new RoomViewStore();\n}\nmodule.exports = singletonRoomViewStore;\n//# sourceMappingURL=RoomViewStore.js.map","module.exports = { \"default\": require(\"core-js/library/fn/array/from\"), __esModule: true };","'use strict';\nvar $at = require('./_string-at')(true);\n\n// 21.1.3.27 String.prototype[@@iterator]()\nrequire('./_iter-define')(String, 'String', function (iterated) {\n this._t = String(iterated); // target\n this._i = 0; // next index\n// 21.1.5.2.1 %StringIteratorPrototype%.next()\n}, function () {\n var O = this._t;\n var index = this._i;\n var point;\n if (index >= O.length) return { value: undefined, done: true };\n point = $at(O, index);\n this._i += point.length;\n return { value: point, done: false };\n});\n","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // 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\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // 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.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","// most Object methods by ES6 should accept primitives\nvar $export = require('./_export');\nvar core = require('./_core');\nvar fails = require('./_fails');\nmodule.exports = function (KEY, exec) {\n var fn = (core.Object || {})[KEY] || Object[KEY];\n var exp = {};\n exp[KEY] = exec(fn);\n $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);\n};\n","\"use strict\";\n\n/*\nCopyright 2018 André Jaenisch\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module logger\n */\nvar log = require(\"loglevel\");\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nvar DEFAULT_NAME_SPACE = \"matrix\";\nvar logger = log.getLogger(DEFAULT_NAME_SPACE);\nlogger.setLevel(log.levels.DEBUG);\n\n/**\n * Drop-in replacement for console
using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n*/\nmodule.exports = logger;\n//# sourceMappingURL=logger.js.map","'use strict';\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _defineProperty2 = require('babel-runtime/helpers/defineProperty');\n\nvar _defineProperty3 = _interopRequireDefault(_defineProperty2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _promise = require('babel-runtime/core-js/promise');\n\nvar _promise2 = _interopRequireDefault(_promise);\n\nvar _bluebird = require('bluebird');\n\n// Limit the maximum number of ongoing promises returned by fn to LIMIT and\n// use a FIFO queue to handle the backlog.\nvar limitConcurrency = function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(fn) {\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (!(ongoingRequestCount >= LIMIT)) {\n _context.next = 3;\n break;\n }\n\n _context.next = 3;\n return (0, _bluebird.resolve)(new _promise2.default(function (resolve, reject) {\n backlogQueue.push(resolve);\n }));\n\n case 3:\n\n ongoingRequestCount++;\n _context.prev = 4;\n _context.next = 7;\n return (0, _bluebird.resolve)(fn());\n\n case 7:\n return _context.abrupt('return', _context.sent);\n\n case 10:\n _context.prev = 10;\n _context.t0 = _context['catch'](4);\n throw _context.t0;\n\n case 13:\n _context.prev = 13;\n\n ongoingRequestCount--;\n checkBacklog();\n return _context.finish(13);\n\n case 17:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[4, 10, 13, 17]]);\n }));\n\n return function limitConcurrency(_x) {\n return _ref.apply(this, arguments);\n };\n}();\n\n/**\n * Global store for tracking group summary, members, invited members and rooms.\n */\n\n\nvar _events = require('events');\n\nvar _events2 = _interopRequireDefault(_events);\n\nvar _groups = require('../groups');\n\nvar _FlairStore = require('./FlairStore');\n\nvar _FlairStore2 = _interopRequireDefault(_FlairStore);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction parseMembersResponse(response) {\n return response.chunk.map(function (apiMember) {\n return (0, _groups.groupMemberFromApiObject)(apiMember);\n });\n}\n\nfunction parseRoomsResponse(response) {\n return response.chunk.map(function (apiRoom) {\n return (0, _groups.groupRoomFromApiObject)(apiRoom);\n });\n}\n\n// The number of ongoing group requests\nvar ongoingRequestCount = 0;\n\n// This has arbitrarily been set to a small number to lower the priority\n// of doing group-related requests because we care about other important\n// requests like hitting /sync.\nvar LIMIT = 3; // Maximum number of ongoing group requests\n\n// FIFO queue of functions to call in the backlog\nvar backlogQueue = [\n // () => {...}\n];\n\n// Pull from the FIFO queue\nfunction checkBacklog() {\n var item = backlogQueue.shift();\n if (typeof item === 'function') item();\n}\nvar GroupStore = function (_EventEmitter) {\n (0, _inherits3.default)(GroupStore, _EventEmitter);\n\n function GroupStore() {\n var _this$_fetchResourceP, _this$_resourceFetche;\n\n (0, _classCallCheck3.default)(this, GroupStore);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (GroupStore.__proto__ || (0, _getPrototypeOf2.default)(GroupStore)).call(this));\n\n _this.STATE_KEY = {\n GroupMembers: 'GroupMembers',\n GroupInvitedMembers: 'GroupInvitedMembers',\n Summary: 'Summary',\n GroupRooms: 'GroupRooms'\n };\n\n _this._state = {};\n _this._state[_this.STATE_KEY.Summary] = {};\n _this._state[_this.STATE_KEY.GroupRooms] = {};\n _this._state[_this.STATE_KEY.GroupMembers] = {};\n _this._state[_this.STATE_KEY.GroupInvitedMembers] = {};\n\n _this._ready = {};\n _this._ready[_this.STATE_KEY.Summary] = {};\n _this._ready[_this.STATE_KEY.GroupRooms] = {};\n _this._ready[_this.STATE_KEY.GroupMembers] = {};\n _this._ready[_this.STATE_KEY.GroupInvitedMembers] = {};\n\n _this._fetchResourcePromise = (_this$_fetchResourceP = {}, (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.Summary, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupRooms, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupMembers, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupInvitedMembers, {}), _this$_fetchResourceP);\n\n _this._resourceFetcher = (_this$_resourceFetche = {}, (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.Summary, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupSummary(groupId);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupRooms, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupRooms(groupId).then(parseRoomsResponse);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupMembers, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupUsers(groupId).then(parseMembersResponse);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupInvitedMembers, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupInvitedUsers(groupId).then(parseMembersResponse);\n });\n }), _this$_resourceFetche);\n return _this;\n }\n\n (0, _createClass3.default)(GroupStore, [{\n key: '_fetchResource',\n value: function _fetchResource(stateKey, groupId) {\n var _this2 = this;\n\n // Ongoing request, ignore\n if (this._fetchResourcePromise[stateKey][groupId]) return;\n\n var clientPromise = this._resourceFetcher[stateKey](groupId);\n\n // Indicate ongoing request\n this._fetchResourcePromise[stateKey][groupId] = clientPromise;\n\n clientPromise.then(function (result) {\n _this2._state[stateKey][groupId] = result;\n _this2._ready[stateKey][groupId] = true;\n _this2._notifyListeners();\n }).catch(function (err) {\n // Invited users not visible to non-members\n if (stateKey === _this2.STATE_KEY.GroupInvitedMembers && err.httpStatus === 403) {\n return;\n }\n\n console.error('Failed to get resource ' + stateKey + ' for ' + groupId, err);\n _this2.emit('error', err, groupId, stateKey);\n }).finally(function () {\n // Indicate finished request, allow for future fetches\n delete _this2._fetchResourcePromise[stateKey][groupId];\n });\n\n return clientPromise;\n }\n }, {\n key: '_notifyListeners',\n value: function _notifyListeners() {\n this.emit('update');\n }\n\n /**\n * Register a listener to recieve updates from the store. This also\n * immediately triggers an update to send the current state of the\n * store (which could be the initial state).\n *\n * If a group ID is specified, this also causes a fetch of all data\n * of the specified group, which might cause 4 separate HTTP\n * requests, but only if said requests aren't already ongoing.\n *\n * @param {string?} groupId the ID of the group to fetch data for.\n * Optional.\n * @param {function} fn the function to call when the store updates.\n * @return {Object} tok a registration \"token\" with a single\n * property `unregister`, a function that can\n * be called to unregister the listener such\n * that it won't be called any more.\n */\n\n }, {\n key: 'registerListener',\n value: function registerListener(groupId, fn) {\n var _this3 = this;\n\n this.on('update', fn);\n // Call to set initial state (before fetching starts)\n this.emit('update');\n\n if (groupId) {\n this._fetchResource(this.STATE_KEY.Summary, groupId);\n this._fetchResource(this.STATE_KEY.GroupRooms, groupId);\n this._fetchResource(this.STATE_KEY.GroupMembers, groupId);\n this._fetchResource(this.STATE_KEY.GroupInvitedMembers, groupId);\n }\n\n // Similar to the Store of flux/utils, we return a \"token\" that\n // can be used to unregister the listener.\n return {\n unregister: function unregister() {\n _this3.unregisterListener(fn);\n }\n };\n }\n }, {\n key: 'unregisterListener',\n value: function unregisterListener(fn) {\n this.removeListener('update', fn);\n }\n }, {\n key: 'isStateReady',\n value: function isStateReady(groupId, id) {\n return this._ready[id][groupId];\n }\n }, {\n key: 'getGroupIdsForRoomId',\n value: function getGroupIdsForRoomId(roomId) {\n var _this4 = this;\n\n var groupIds = (0, _keys2.default)(this._state[this.STATE_KEY.GroupRooms]);\n return groupIds.filter(function (groupId) {\n var rooms = _this4._state[_this4.STATE_KEY.GroupRooms][groupId] || [];\n return rooms.some(function (room) {\n return room.roomId === roomId;\n });\n });\n }\n }, {\n key: 'getSummary',\n value: function getSummary(groupId) {\n return this._state[this.STATE_KEY.Summary][groupId] || {};\n }\n }, {\n key: 'getGroupRooms',\n value: function getGroupRooms(groupId) {\n return this._state[this.STATE_KEY.GroupRooms][groupId] || [];\n }\n }, {\n key: 'getGroupMembers',\n value: function getGroupMembers(groupId) {\n return this._state[this.STATE_KEY.GroupMembers][groupId] || [];\n }\n }, {\n key: 'getGroupInvitedMembers',\n value: function getGroupInvitedMembers(groupId) {\n return this._state[this.STATE_KEY.GroupInvitedMembers][groupId] || [];\n }\n }, {\n key: 'getGroupPublicity',\n value: function getGroupPublicity(groupId) {\n return (this._state[this.STATE_KEY.Summary][groupId] || {}).user ? (this._state[this.STATE_KEY.Summary][groupId] || {}).user.is_publicised : null;\n }\n }, {\n key: 'isUserPrivileged',\n value: function isUserPrivileged(groupId) {\n return (this._state[this.STATE_KEY.Summary][groupId] || {}).user ? (this._state[this.STATE_KEY.Summary][groupId] || {}).user.is_privileged : null;\n }\n }, {\n key: 'refreshGroupRooms',\n value: function refreshGroupRooms(groupId) {\n return this._fetchResource(this.STATE_KEY.GroupRooms, groupId);\n }\n }, {\n key: 'refreshGroupMembers',\n value: function refreshGroupMembers(groupId) {\n return this._fetchResource(this.STATE_KEY.GroupMembers, groupId);\n }\n }, {\n key: 'addRoomToGroup',\n value: function addRoomToGroup(groupId, roomId, isPublic) {\n return _MatrixClientPeg2.default.get().addRoomToGroup(groupId, roomId, isPublic).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'updateGroupRoomVisibility',\n value: function updateGroupRoomVisibility(groupId, roomId, isPublic) {\n return _MatrixClientPeg2.default.get().updateGroupRoomVisibility(groupId, roomId, isPublic).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'removeRoomFromGroup',\n value: function removeRoomFromGroup(groupId, roomId) {\n return _MatrixClientPeg2.default.get().removeRoomFromGroup(groupId, roomId)\n // Room might be in the summary, refresh just in case\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId)).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'inviteUserToGroup',\n value: function inviteUserToGroup(groupId, userId) {\n return _MatrixClientPeg2.default.get().inviteUserToGroup(groupId, userId).then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'acceptGroupInvite',\n value: function acceptGroupInvite(groupId) {\n return _MatrixClientPeg2.default.get().acceptGroupInvite(groupId)\n // The user should now be able to access (personal) group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might be able to see more rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId))\n // The user should now not appear as an invited member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'joinGroup',\n value: function joinGroup(groupId) {\n return _MatrixClientPeg2.default.get().joinGroup(groupId)\n // The user should now be able to access (personal) group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might be able to see more rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId))\n // The user should now not appear as an invited member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'leaveGroup',\n value: function leaveGroup(groupId) {\n return _MatrixClientPeg2.default.get().leaveGroup(groupId)\n // The user should now not be able to access group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might only be able to see a subset of rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now not appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId));\n }\n }, {\n key: 'addRoomToGroupSummary',\n value: function addRoomToGroupSummary(groupId, roomId, categoryId) {\n return _MatrixClientPeg2.default.get().addRoomToGroupSummary(groupId, roomId, categoryId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'addUserToGroupSummary',\n value: function addUserToGroupSummary(groupId, userId, roleId) {\n return _MatrixClientPeg2.default.get().addUserToGroupSummary(groupId, userId, roleId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'removeRoomFromGroupSummary',\n value: function removeRoomFromGroupSummary(groupId, roomId) {\n return _MatrixClientPeg2.default.get().removeRoomFromGroupSummary(groupId, roomId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'removeUserFromGroupSummary',\n value: function removeUserFromGroupSummary(groupId, userId) {\n return _MatrixClientPeg2.default.get().removeUserFromGroupSummary(groupId, userId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'setGroupPublicity',\n value: function setGroupPublicity(groupId, isPublished) {\n return _MatrixClientPeg2.default.get().setGroupPublicity(groupId, isPublished).then(function () {\n _FlairStore2.default.invalidatePublicisedGroups(_MatrixClientPeg2.default.get().credentials.userId);\n }).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }]);\n return GroupStore;\n}(_events2.default);\n\nvar singletonGroupStore = null;\nif (!singletonGroupStore) {\n singletonGroupStore = new GroupStore();\n}\nmodule.exports = singletonGroupStore;\n//# sourceMappingURL=GroupStore.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.closest = exports.distance = exports.patch = exports.absolute = exports.negate = exports.isEqual = exports.subtract = exports.add = undefined;\n\nvar _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');\n\nvar _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);\n\nvar _defineProperty2 = require('babel-runtime/helpers/defineProperty');\n\nvar _defineProperty3 = _interopRequireDefault(_defineProperty2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar add = exports.add = function add(point1, point2) {\n return {\n x: point1.x + point2.x,\n y: point1.y + point2.y\n };\n};\n\nvar subtract = exports.subtract = function subtract(point1, point2) {\n return {\n x: point1.x - point2.x,\n y: point1.y - point2.y\n };\n};\n\nvar isEqual = exports.isEqual = function isEqual(point1, point2) {\n return point1.x === point2.x && point1.y === point2.y;\n};\n\nvar negate = exports.negate = function negate(point) {\n return {\n x: point.x !== 0 ? -point.x : 0,\n y: point.y !== 0 ? -point.y : 0\n };\n};\n\nvar absolute = exports.absolute = function absolute(point) {\n return {\n x: Math.abs(point.x),\n y: Math.abs(point.y)\n };\n};\n\nvar patch = exports.patch = function patch(line, value) {\n var _ref;\n\n var otherValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n return _ref = {}, (0, _defineProperty3.default)(_ref, line, value), (0, _defineProperty3.default)(_ref, line === 'x' ? 'y' : 'x', otherValue), _ref;\n};\n\nvar distance = exports.distance = function distance(point1, point2) {\n return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));\n};\n\nvar closest = exports.closest = function closest(target, points) {\n return Math.min.apply(Math, (0, _toConsumableArray3.default)(points.map(function (point) {\n return distance(target, point);\n })));\n};","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');\n\nvar _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _index = require('../../../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _lodash = require('lodash');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// Invoke validation from user input (when typing, etc.) at most once every N ms.\nvar VALIDATION_THROTTLE_MS = 200; /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nvar Field = function (_React$PureComponent) {\n (0, _inherits3.default)(Field, _React$PureComponent);\n\n function Field() {\n (0, _classCallCheck3.default)(this, Field);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (Field.__proto__ || (0, _getPrototypeOf2.default)(Field)).call(this));\n\n _this.onFocus = function (ev) {\n _this.validate({\n focused: true\n });\n // Parent component may have supplied its own `onFocus` as well\n if (_this.props.onFocus) {\n _this.props.onFocus(ev);\n }\n };\n\n _this.onChange = function (ev) {\n _this.validateOnChange();\n // Parent component may have supplied its own `onChange` as well\n if (_this.props.onChange) {\n _this.props.onChange(ev);\n }\n };\n\n _this.onBlur = function (ev) {\n _this.validate({\n focused: false\n });\n // Parent component may have supplied its own `onBlur` as well\n if (_this.props.onBlur) {\n _this.props.onBlur(ev);\n }\n };\n\n _this.validateOnChange = (0, _lodash.debounce)(function () {\n _this.validate({\n focused: true\n });\n }, VALIDATION_THROTTLE_MS);\n\n _this.state = {\n valid: undefined,\n feedback: undefined\n };\n return _this;\n }\n\n (0, _createClass3.default)(Field, [{\n key: 'focus',\n value: function focus() {\n this.input.focus();\n }\n }, {\n key: 'validate',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(_ref2) {\n var focused = _ref2.focused,\n _ref2$allowEmpty = _ref2.allowEmpty,\n allowEmpty = _ref2$allowEmpty === undefined ? true : _ref2$allowEmpty;\n\n var value, _ref3, valid, feedback;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (this.props.onValidate) {\n _context.next = 2;\n break;\n }\n\n return _context.abrupt('return');\n\n case 2:\n value = this.input ? this.input.value : null;\n _context.next = 5;\n return (0, _bluebird.resolve)(this.props.onValidate({\n value: value,\n focused: focused,\n allowEmpty: allowEmpty\n }));\n\n case 5:\n _ref3 = _context.sent;\n valid = _ref3.valid;\n feedback = _ref3.feedback;\n\n\n if (feedback) {\n this.setState({\n valid: valid,\n feedback: feedback,\n feedbackVisible: true\n });\n } else {\n // When we receive null `feedback`, we want to hide the tooltip.\n // We leave the previous `feedback` content in state without updating it,\n // so that we can hide the tooltip containing the most recent feedback\n // via CSS animation.\n this.setState({\n valid: valid,\n feedbackVisible: false\n });\n }\n\n case 9:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function validate(_x) {\n return _ref.apply(this, arguments);\n }\n\n return validate;\n }()\n\n /*\n * This was changed from throttle to debounce: this is more traditional for\n * form validation since it means that the validation doesn't happen at all\n * until the user stops typing for a bit (debounce defaults to not running on\n * the leading edge). If we're doing an HTTP hit on each validation, we have more\n * incentive to prevent validating input that's very unlikely to be valid.\n * We may find that we actually want different behaviour for registration\n * fields, in which case we can add some options to control it.\n */\n\n }, {\n key: 'render',\n value: function render() {\n var _this2 = this;\n\n var _props = this.props,\n element = _props.element,\n prefix = _props.prefix,\n postfix = _props.postfix,\n className = _props.className,\n onValidate = _props.onValidate,\n children = _props.children,\n tooltipContent = _props.tooltipContent,\n flagInvalid = _props.flagInvalid,\n tooltipClassName = _props.tooltipClassName,\n inputProps = (0, _objectWithoutProperties3.default)(_props, ['element', 'prefix', 'postfix', 'className', 'onValidate', 'children', 'tooltipContent', 'flagInvalid', 'tooltipClassName']);\n\n\n var inputElement = element || \"input\";\n\n // Set some defaults for the element\n inputProps.type = inputProps.type || \"text\";\n inputProps.ref = function (input) {\n return _this2.input = input;\n };\n inputProps.placeholder = inputProps.placeholder || inputProps.label;\n\n inputProps.onFocus = this.onFocus;\n inputProps.onChange = this.onChange;\n inputProps.onBlur = this.onBlur;\n\n var fieldInput = _react2.default.createElement(inputElement, inputProps, children);\n\n var prefixContainer = null;\n if (prefix) {\n prefixContainer = _react2.default.createElement(\n 'span',\n { className: 'mx_Field_prefix' },\n prefix\n );\n }\n var postfixContainer = null;\n if (postfix) {\n postfixContainer = _react2.default.createElement(\n 'span',\n { className: 'mx_Field_postfix' },\n postfix\n );\n }\n\n var hasValidationFlag = flagInvalid !== null && flagInvalid !== undefined;\n var fieldClasses = (0, _classnames2.default)(\"mx_Field\", 'mx_Field_' + inputElement, className, {\n // If we have a prefix element, leave the label always at the top left and\n // don't animate it, as it looks a bit clunky and would add complexity to do\n // properly.\n mx_Field_labelAlwaysTopLeft: prefix,\n mx_Field_valid: onValidate && this.state.valid === true,\n mx_Field_invalid: hasValidationFlag ? flagInvalid : onValidate && this.state.valid === false\n });\n\n // Handle displaying feedback on validity\n var Tooltip = _index2.default.getComponent(\"elements.Tooltip\");\n var fieldTooltip = void 0;\n if (tooltipContent || this.state.feedback) {\n var addlClassName = tooltipClassName ? tooltipClassName : '';\n fieldTooltip = _react2.default.createElement(Tooltip, {\n tooltipClassName: 'mx_Field_tooltip ' + addlClassName,\n visible: this.state.feedbackVisible,\n label: tooltipContent || this.state.feedback\n });\n }\n\n return _react2.default.createElement(\n 'div',\n { className: fieldClasses },\n prefixContainer,\n fieldInput,\n _react2.default.createElement(\n 'label',\n { htmlFor: this.props.id },\n this.props.label\n ),\n postfixContainer,\n fieldTooltip\n );\n }\n }]);\n return Field;\n}(_react2.default.PureComponent);\n\nField.propTypes = {\n // The field's ID, which binds the input and label together.\n id: _propTypes2.default.string.isRequired,\n // The element to create. Defaults to \"input\".\n // To define options for a select, use \n element: _propTypes2.default.oneOf([\"input\", \"select\", \"textarea\"]),\n // The field's type (when used as an ). Defaults to \"text\".\n type: _propTypes2.default.string,\n // The field's label string.\n label: _propTypes2.default.string,\n // The field's placeholder string. Defaults to the label.\n placeholder: _propTypes2.default.string,\n // The field's value.\n // This is a controlled component, so the value is required.\n value: _propTypes2.default.string.isRequired,\n // Optional component to include inside the field before the input.\n prefix: _propTypes2.default.node,\n // Optional component to include inside the field after the input.\n postfix: _propTypes2.default.node,\n // The callback called whenever the contents of the field\n // changes. Returns an object with `valid` boolean field\n // and a `feedback` react component field to provide feedback\n // to the user.\n onValidate: _propTypes2.default.func,\n // If specified, overrides the value returned by onValidate.\n flagInvalid: _propTypes2.default.bool,\n // If specified, contents will appear as a tooltip on the element and\n // validation feedback tooltips will be suppressed.\n tooltipContent: _propTypes2.default.node,\n // If specified alongside tooltipContent, the class name to apply to the\n // tooltip itself.\n tooltipClassName: _propTypes2.default.string,\n // If specified, an additional class name to apply to the field container\n className: _propTypes2.default.string\n // All other props pass through to the .\n};\nexports.default = Field;\nmodule.exports = exports['default'];\n//# sourceMappingURL=Field.js.map","var dP = require('./_object-dp');\nvar createDesc = require('./_property-desc');\nmodule.exports = require('./_descriptors') ? function (object, key, value) {\n return dP.f(object, key, createDesc(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var global = require('./_global');\nvar hide = require('./_hide');\nvar has = require('./_has');\nvar SRC = require('./_uid')('src');\nvar $toString = require('./_function-to-string');\nvar TO_STRING = 'toString';\nvar TPL = ('' + $toString).split(TO_STRING);\n\nrequire('./_core').inspectSource = function (it) {\n return $toString.call(it);\n};\n\n(module.exports = function (O, key, val, safe) {\n var isFunction = typeof val == 'function';\n if (isFunction) has(val, 'name') || hide(val, 'name', key);\n if (O[key] === val) return;\n if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));\n if (O === global) {\n O[key] = val;\n } else if (!safe) {\n delete O[key];\n hide(O, key, val);\n } else if (O[key]) {\n O[key] = val;\n } else {\n hide(O, key, val);\n }\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, TO_STRING, function toString() {\n return typeof this == 'function' && this[SRC] || $toString.call(this);\n});\n","var $export = require('./_export');\nvar fails = require('./_fails');\nvar defined = require('./_defined');\nvar quot = /\"/g;\n// B.2.3.2.1 CreateHTML(string, tag, attribute, value)\nvar createHTML = function (string, tag, attribute, value) {\n var S = String(defined(string));\n var p1 = '<' + tag;\n if (attribute !== '') p1 += ' ' + attribute + '=\"' + String(value).replace(quot, '"') + '\"';\n return p1 + '>' + S + '' + tag + '>';\n};\nmodule.exports = function (NAME, exec) {\n var O = {};\n O[NAME] = exec(createHTML);\n $export($export.P + $export.F * fails(function () {\n var test = ''[NAME]('\"');\n return test !== test.toLowerCase() || test.split('\"').length > 3;\n }), 'String', O);\n};\n","module.exports = true;\n","module.exports = { \"default\": require(\"core-js/library/fn/set\"), __esModule: true };","\n\nvar simpleIsEqual = function simpleIsEqual(a, b) {\n return a === b;\n};\n\nexport default function (resultFn) {\n var isEqual = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : simpleIsEqual;\n\n var lastThis = void 0;\n var lastArgs = [];\n var lastResult = void 0;\n var calledOnce = false;\n\n var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) {\n return isEqual(newArg, lastArgs[index]);\n };\n\n var result = function result() {\n for (var _len = arguments.length, newArgs = Array(_len), _key = 0; _key < _len; _key++) {\n newArgs[_key] = arguments[_key];\n }\n\n if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {\n return lastResult;\n }\n\n calledOnce = true;\n lastThis = this;\n lastArgs = newArgs;\n lastResult = resultFn.apply(this, newArgs);\n return lastResult;\n };\n\n return result;\n}","var hasOwnProperty = {}.hasOwnProperty;\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","// to indexed object, toObject with fallback for non-array-like ES3 strings\nvar IObject = require('./_iobject');\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return IObject(defined(it));\n};\n","var pIE = require('./_object-pie');\nvar createDesc = require('./_property-desc');\nvar toIObject = require('./_to-iobject');\nvar toPrimitive = require('./_to-primitive');\nvar has = require('./_has');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nexports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) {\n O = toIObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return gOPD(O, P);\n } catch (e) { /* empty */ }\n if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);\n};\n","// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)\nvar has = require('./_has');\nvar toObject = require('./_to-object');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar ObjectProto = Object.prototype;\n\nmodule.exports = Object.getPrototypeOf || function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectProto : null;\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","var def = require('./_object-dp').f;\nvar has = require('./_has');\nvar TAG = require('./_wks')('toStringTag');\n\nmodule.exports = function (it, tag, stat) {\n if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });\n};\n","require('./es6.array.iterator');\nvar global = require('./_global');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar TO_STRING_TAG = require('./_wks')('toStringTag');\n\nvar DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +\n 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +\n 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +\n 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +\n 'TextTrackList,TouchList').split(',');\n\nfor (var i = 0; i < DOMIterables.length; i++) {\n var NAME = DOMIterables[i];\n var Collection = global[NAME];\n var proto = Collection && Collection.prototype;\n if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);\n Iterators[NAME] = Iterators.Array;\n}\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');\n\nvar _slicedToArray3 = _interopRequireDefault(_slicedToArray2);\n\nvar _entries = require('babel-runtime/core-js/object/entries');\n\nvar _entries2 = _interopRequireDefault(_entries);\n\nvar _values = require('babel-runtime/core-js/object/values');\n\nvar _values2 = _interopRequireDefault(_values);\n\nvar _stringify = require('babel-runtime/core-js/json/stringify');\n\nvar _stringify2 = _interopRequireDefault(_stringify);\n\nvar _promise = require('babel-runtime/core-js/promise');\n\nvar _promise2 = _interopRequireDefault(_promise);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _SdkConfig = require('../SdkConfig');\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nvar _dispatcher = require('../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _url = require('url');\n\nvar url = _interopRequireWildcard(_url);\n\nvar _WidgetEchoStore = require('../stores/WidgetEchoStore');\n\nvar _WidgetEchoStore2 = _interopRequireDefault(_WidgetEchoStore);\n\nvar _SettingsStore = require('../settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nvar _ActiveWidgetStore = require('../stores/ActiveWidgetStore');\n\nvar _ActiveWidgetStore2 = _interopRequireDefault(_ActiveWidgetStore);\n\nvar _IntegrationManagers = require('../integrations/IntegrationManagers');\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// How long we wait for the state event echo to come back from the server\n// before waitFor[Room/User]Widget rejects its promise\nvar WIDGET_WAIT_TIME = 20000; /*\n Copyright 2017 Vector Creations Ltd\n Copyright 2018 New Vector Ltd\n Copyright 2019 Travis Ralston\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.\n * @param {Object} variables The key/value pairs to replace the template\n * variables with. E.g. { '$bar': 'baz' }.\n * @return {string} The result of replacing all template variables e.g. '/foo/baz'.\n */\nfunction encodeUri(pathTemplate, variables) {\n for (var key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n pathTemplate = pathTemplate.replace(key, encodeURIComponent(variables[key]));\n }\n return pathTemplate;\n}\n\nvar WidgetUtils = function () {\n function WidgetUtils() {\n (0, _classCallCheck3.default)(this, WidgetUtils);\n }\n\n (0, _createClass3.default)(WidgetUtils, null, [{\n key: 'canUserModifyWidgets',\n\n /* Returns true if user is able to send state events to modify widgets in this room\n * (Does not apply to non-room-based / user widgets)\n * @param roomId -- The ID of the room to check\n * @return Boolean -- true if the user can modify widgets in this room\n * @throws Error -- specifies the error reason\n */\n value: function canUserModifyWidgets(roomId) {\n if (!roomId) {\n console.warn('No room ID specified');\n return false;\n }\n\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n console.warn('User must be be logged in');\n return false;\n }\n\n var room = client.getRoom(roomId);\n if (!room) {\n console.warn('Room ID ' + roomId + ' is not recognised');\n return false;\n }\n\n var me = client.credentials.userId;\n if (!me) {\n console.warn('Failed to get user ID');\n return false;\n }\n\n if (room.getMyMembership() !== \"join\") {\n console.warn('User ' + me + ' is not in room ' + roomId);\n return false;\n }\n\n return room.currentState.maySendStateEvent('im.vector.modular.widgets', me);\n }\n\n /**\n * Returns true if specified url is a scalar URL, typically https://scalar.vector.im/api\n * @param {[type]} testUrlString URL to check\n * @return {Boolean} True if specified URL is a scalar URL\n */\n\n }, {\n key: 'isScalarUrl',\n value: function isScalarUrl(testUrlString) {\n if (!testUrlString) {\n console.error('Scalar URL check failed. No URL specified');\n return false;\n }\n\n var testUrl = url.parse(testUrlString);\n var scalarUrls = _SdkConfig2.default.get().integrations_widgets_urls;\n if (!scalarUrls || scalarUrls.length === 0) {\n var defaultManager = _IntegrationManagers.IntegrationManagers.sharedInstance().getPrimaryManager();\n if (defaultManager) {\n scalarUrls = [defaultManager.apiUrl];\n } else {\n scalarUrls = [];\n }\n }\n\n for (var i = 0; i < scalarUrls.length; i++) {\n var scalarUrl = url.parse(scalarUrls[i]);\n if (testUrl && scalarUrl) {\n if (testUrl.protocol === scalarUrl.protocol && testUrl.host === scalarUrl.host && testUrl.pathname.startsWith(scalarUrl.pathname)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Returns a promise that resolves when a widget with the given\n * ID has been added as a user widget (ie. the accountData event\n * arrives) or rejects after a timeout\n *\n * @param {string} widgetId The ID of the widget to wait for\n * @param {boolean} add True to wait for the widget to be added,\n * false to wait for it to be deleted.\n * @returns {Promise} that resolves when the widget is in the\n * requested state according to the `add` param\n */\n\n }, {\n key: 'waitForUserWidget',\n value: function waitForUserWidget(widgetId, add) {\n return new _promise2.default(function (resolve, reject) {\n // Tests an account data event, returning true if it's in the state\n // we're waiting for it to be in\n function eventInIntendedState(ev) {\n if (!ev || !ev.getContent()) return false;\n if (add) {\n return ev.getContent()[widgetId] !== undefined;\n } else {\n return ev.getContent()[widgetId] === undefined;\n }\n }\n\n var startingAccountDataEvent = _MatrixClientPeg2.default.get().getAccountData('m.widgets');\n if (eventInIntendedState(startingAccountDataEvent)) {\n resolve();\n return;\n }\n\n function onAccountData(ev) {\n var currentAccountDataEvent = _MatrixClientPeg2.default.get().getAccountData('m.widgets');\n if (eventInIntendedState(currentAccountDataEvent)) {\n _MatrixClientPeg2.default.get().removeListener('accountData', onAccountData);\n clearTimeout(timerId);\n resolve();\n }\n }\n var timerId = setTimeout(function () {\n _MatrixClientPeg2.default.get().removeListener('accountData', onAccountData);\n reject(new Error(\"Timed out waiting for widget ID \" + widgetId + \" to appear\"));\n }, WIDGET_WAIT_TIME);\n _MatrixClientPeg2.default.get().on('accountData', onAccountData);\n });\n }\n\n /**\n * Returns a promise that resolves when a widget with the given\n * ID has been added as a room widget in the given room (ie. the\n * room state event arrives) or rejects after a timeout\n *\n * @param {string} widgetId The ID of the widget to wait for\n * @param {string} roomId The ID of the room to wait for the widget in\n * @param {boolean} add True to wait for the widget to be added,\n * false to wait for it to be deleted.\n * @returns {Promise} that resolves when the widget is in the\n * requested state according to the `add` param\n */\n\n }, {\n key: 'waitForRoomWidget',\n value: function waitForRoomWidget(widgetId, roomId, add) {\n return new _promise2.default(function (resolve, reject) {\n // Tests a list of state events, returning true if it's in the state\n // we're waiting for it to be in\n function eventsInIntendedState(evList) {\n var widgetPresent = evList.some(function (ev) {\n return ev.getContent() && ev.getContent()['id'] === widgetId;\n });\n if (add) {\n return widgetPresent;\n } else {\n return !widgetPresent;\n }\n }\n\n var room = _MatrixClientPeg2.default.get().getRoom(roomId);\n var startingWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n if (eventsInIntendedState(startingWidgetEvents)) {\n resolve();\n return;\n }\n\n function onRoomStateEvents(ev) {\n if (ev.getRoomId() !== roomId) return;\n\n var currentWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n\n if (eventsInIntendedState(currentWidgetEvents)) {\n _MatrixClientPeg2.default.get().removeListener('RoomState.events', onRoomStateEvents);\n clearTimeout(timerId);\n resolve();\n }\n }\n var timerId = setTimeout(function () {\n _MatrixClientPeg2.default.get().removeListener('RoomState.events', onRoomStateEvents);\n reject(new Error(\"Timed out waiting for widget ID \" + widgetId + \" to appear\"));\n }, WIDGET_WAIT_TIME);\n _MatrixClientPeg2.default.get().on('RoomState.events', onRoomStateEvents);\n });\n }\n }, {\n key: 'setUserWidget',\n value: function setUserWidget(widgetId, widgetType, widgetUrl, widgetName, widgetData) {\n var content = {\n type: widgetType,\n url: widgetUrl,\n name: widgetName,\n data: widgetData\n };\n\n var client = _MatrixClientPeg2.default.get();\n // Get the current widgets and clone them before we modify them, otherwise\n // we'll modify the content of the old event.\n var userWidgets = JSON.parse((0, _stringify2.default)(WidgetUtils.getUserWidgets()));\n\n // Delete existing widget with ID\n try {\n delete userWidgets[widgetId];\n } catch (e) {\n console.error('$widgetId is non-configurable');\n }\n\n var addingWidget = Boolean(widgetUrl);\n\n // Add new widget / update\n if (addingWidget) {\n userWidgets[widgetId] = {\n content: content,\n sender: client.getUserId(),\n state_key: widgetId,\n type: 'm.widget',\n id: widgetId\n };\n }\n\n // This starts listening for when the echo comes back from the server\n // since the widget won't appear added until this happens. If we don't\n // wait for this, the action will complete but if the user is fast enough,\n // the widget still won't actually be there.\n return client.setAccountData('m.widgets', userWidgets).then(function () {\n return WidgetUtils.waitForUserWidget(widgetId, addingWidget);\n }).then(function () {\n _dispatcher2.default.dispatch({ action: \"user_widget_updated\" });\n });\n }\n }, {\n key: 'setRoomWidget',\n value: function setRoomWidget(roomId, widgetId, widgetType, widgetUrl, widgetName, widgetData) {\n var content = void 0;\n\n var addingWidget = Boolean(widgetUrl);\n\n if (addingWidget) {\n content = {\n type: widgetType,\n url: widgetUrl,\n name: widgetName,\n data: widgetData\n };\n } else {\n content = {};\n }\n\n _WidgetEchoStore2.default.setRoomWidgetEcho(roomId, widgetId, content);\n\n var client = _MatrixClientPeg2.default.get();\n // TODO - Room widgets need to be moved to 'm.widget' state events\n // https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit?usp=sharing\n return client.sendStateEvent(roomId, \"im.vector.modular.widgets\", content, widgetId).then(function () {\n return WidgetUtils.waitForRoomWidget(widgetId, roomId, addingWidget);\n }).finally(function () {\n _WidgetEchoStore2.default.removeRoomWidgetEcho(roomId, widgetId);\n });\n }\n\n /**\n * Get room specific widgets\n * @param {object} room The room to get widgets force\n * @return {[object]} Array containing current / active room widgets\n */\n\n }, {\n key: 'getRoomWidgets',\n value: function getRoomWidgets(room) {\n var appsStateEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n if (!appsStateEvents) {\n return [];\n }\n\n return appsStateEvents.filter(function (ev) {\n return ev.getContent().type && ev.getContent().url;\n });\n }\n\n /**\n * Get user specific widgets (not linked to a specific room)\n * @return {object} Event content object containing current / active user widgets\n */\n\n }, {\n key: 'getUserWidgets',\n value: function getUserWidgets() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n throw new Error('User not logged in');\n }\n var userWidgets = client.getAccountData('m.widgets');\n if (userWidgets && userWidgets.getContent()) {\n return userWidgets.getContent();\n }\n return {};\n }\n\n /**\n * Get user specific widgets (not linked to a specific room) as an array\n * @return {[object]} Array containing current / active user widgets\n */\n\n }, {\n key: 'getUserWidgetsArray',\n value: function getUserWidgetsArray() {\n return (0, _values2.default)(WidgetUtils.getUserWidgets());\n }\n\n /**\n * Get active stickerpicker widgets (stickerpickers are user widgets by nature)\n * @return {[object]} Array containing current / active stickerpicker widgets\n */\n\n }, {\n key: 'getStickerpickerWidgets',\n value: function getStickerpickerWidgets() {\n var widgets = WidgetUtils.getUserWidgetsArray();\n return widgets.filter(function (widget) {\n return widget.content && widget.content.type === \"m.stickerpicker\";\n });\n }\n\n /**\n * Get all integration manager widgets for this user.\n * @returns {Object[]} An array of integration manager user widgets.\n */\n\n }, {\n key: 'getIntegrationManagerWidgets',\n value: function getIntegrationManagerWidgets() {\n var widgets = WidgetUtils.getUserWidgetsArray();\n return widgets.filter(function (w) {\n return w.content && w.content.type === \"m.integration_manager\";\n });\n }\n }, {\n key: 'removeIntegrationManagerWidgets',\n value: function removeIntegrationManagerWidgets() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n throw new Error('User not logged in');\n }\n var widgets = client.getAccountData('m.widgets');\n if (!widgets) return;\n var userWidgets = widgets.getContent() || {};\n (0, _entries2.default)(userWidgets).forEach(function (_ref) {\n var _ref2 = (0, _slicedToArray3.default)(_ref, 2),\n key = _ref2[0],\n widget = _ref2[1];\n\n if (widget.content && widget.content.type === \"m.integration_manager\") {\n delete userWidgets[key];\n }\n });\n return client.setAccountData('m.widgets', userWidgets);\n }\n }, {\n key: 'addIntegrationManagerWidget',\n value: function addIntegrationManagerWidget(name, uiUrl, apiUrl) {\n return WidgetUtils.setUserWidget(\"integration_manager_\" + new Date().getTime(), \"m.integration_manager\", uiUrl, \"Integration Manager: \" + name, { \"api_url\": apiUrl });\n }\n\n /**\n * Remove all stickerpicker widgets (stickerpickers are user widgets by nature)\n * @return {Promise} Resolves on account data updated\n */\n\n }, {\n key: 'removeStickerpickerWidgets',\n value: function removeStickerpickerWidgets() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n throw new Error('User not logged in');\n }\n var widgets = client.getAccountData('m.widgets');\n if (!widgets) return;\n var userWidgets = widgets.getContent() || {};\n (0, _entries2.default)(userWidgets).forEach(function (_ref3) {\n var _ref4 = (0, _slicedToArray3.default)(_ref3, 2),\n key = _ref4[0],\n widget = _ref4[1];\n\n if (widget.content && widget.content.type === 'm.stickerpicker') {\n delete userWidgets[key];\n }\n });\n return client.setAccountData('m.widgets', userWidgets);\n }\n }, {\n key: 'makeAppConfig',\n value: function makeAppConfig(appId, app, sender, roomId) {\n var myUserId = _MatrixClientPeg2.default.get().credentials.userId;\n var user = _MatrixClientPeg2.default.get().getUser(myUserId);\n var params = {\n '$matrix_user_id': myUserId,\n '$matrix_room_id': roomId,\n '$matrix_display_name': user ? user.displayName : myUserId,\n '$matrix_avatar_url': user ? _MatrixClientPeg2.default.get().mxcUrlToHttp(user.avatarUrl) : '',\n\n // TODO: Namespace themes through some standard\n '$theme': _SettingsStore2.default.getValue(\"theme\")\n };\n\n app.id = appId;\n app.name = app.name || app.type;\n\n if (app.data) {\n (0, _keys2.default)(app.data).forEach(function (key) {\n params['$' + key] = app.data[key];\n });\n\n app.waitForIframeLoad = app.data.waitForIframeLoad === 'false' ? false : true;\n }\n\n app.url = encodeUri(app.url, params);\n app.creatorUserId = sender && sender.userId ? sender.userId : null;\n\n return app;\n }\n }, {\n key: 'getCapWhitelistForAppTypeInRoomId',\n value: function getCapWhitelistForAppTypeInRoomId(appType, roomId) {\n var enableScreenshots = _SettingsStore2.default.getValue(\"enableWidgetScreenshots\", roomId);\n\n var capWhitelist = enableScreenshots ? [\"m.capability.screenshot\"] : [];\n\n // Obviously anyone that can add a widget can claim it's a jitsi widget,\n // so this doesn't really offer much over the set of domains we load\n // widgets from at all, but it probably makes sense for sanity.\n if (appType == 'jitsi') capWhitelist.push(\"m.always_on_screen\");\n\n return capWhitelist;\n }\n }, {\n key: 'getWidgetSecurityKey',\n value: function getWidgetSecurityKey(widgetId, widgetUrl, isUserWidget) {\n var widgetLocation = _ActiveWidgetStore2.default.getRoomId(widgetId);\n\n if (isUserWidget) {\n var userWidget = WidgetUtils.getUserWidgetsArray().find(function (w) {\n return w.id === widgetId && w.content && w.content.url === widgetUrl;\n });\n\n if (!userWidget) {\n throw new Error(\"No matching user widget to form security key\");\n }\n\n widgetLocation = userWidget.sender;\n }\n\n if (!widgetLocation) {\n throw new Error(\"Failed to locate where the widget resides\");\n }\n\n return encodeURIComponent(widgetLocation + '::' + widgetUrl);\n }\n }]);\n return WidgetUtils;\n}();\n\nexports.default = WidgetUtils;\nmodule.exports = exports['default'];\n//# sourceMappingURL=WidgetUtils.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.IntegrationManagers = undefined;\n\nvar _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');\n\nvar _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _bluebird = require('bluebird');\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _SdkConfig = require('../SdkConfig');\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nvar _index = require('../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _Modal = require('../Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _IntegrationManagerInstance = require('./IntegrationManagerInstance');\n\nvar _WidgetUtils = require('../utils/WidgetUtils');\n\nvar _WidgetUtils2 = _interopRequireDefault(_WidgetUtils);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar HS_MANAGERS_REFRESH_INTERVAL = 8 * 60 * 60 * 1000; // 8 hours\n/*\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar KIND_PREFERENCE = [\n// Ordered: first is most preferred, last is least preferred.\n_IntegrationManagerInstance.KIND_ACCOUNT, _IntegrationManagerInstance.KIND_HOMESERVER, _IntegrationManagerInstance.KIND_CONFIG];\n\nvar IntegrationManagers = exports.IntegrationManagers = function () {\n (0, _createClass3.default)(IntegrationManagers, null, [{\n key: 'sharedInstance',\n value: function sharedInstance() {\n if (!IntegrationManagers._instance) {\n IntegrationManagers._instance = new IntegrationManagers();\n }\n return IntegrationManagers._instance;\n }\n }]);\n\n function IntegrationManagers() {\n (0, _classCallCheck3.default)(this, IntegrationManagers);\n this._managers = [];\n this._wellknownRefreshTimerId = null;\n\n this._compileManagers();\n }\n\n (0, _createClass3.default)(IntegrationManagers, [{\n key: 'startWatching',\n value: function startWatching() {\n var _this = this;\n\n this.stopWatching();\n this._client = _MatrixClientPeg2.default.get();\n this._client.on(\"accountData\", this._onAccountData.bind(this));\n this._compileManagers();\n setInterval(function () {\n return _this._setupHomeserverManagers();\n }, HS_MANAGERS_REFRESH_INTERVAL);\n }\n }, {\n key: 'stopWatching',\n value: function stopWatching() {\n if (!this._client) return;\n this._client.removeListener(\"accountData\", this._onAccountData.bind(this));\n if (this._wellknownRefreshTimerId !== null) clearInterval(this._wellknownRefreshTimerId);\n }\n }, {\n key: '_compileManagers',\n value: function _compileManagers() {\n this._managers = [];\n this._setupConfiguredManager();\n this._setupHomeserverManagers();\n this._setupAccountManagers();\n }\n }, {\n key: '_setupConfiguredManager',\n value: function _setupConfiguredManager() {\n var apiUrl = _SdkConfig2.default.get()['integrations_rest_url'];\n var uiUrl = _SdkConfig2.default.get()['integrations_ui_url'];\n\n if (apiUrl && uiUrl) {\n this._managers.push(new _IntegrationManagerInstance.IntegrationManagerInstance(_IntegrationManagerInstance.KIND_CONFIG, apiUrl, uiUrl));\n this._primaryManager = null; // reset primary\n }\n }\n }, {\n key: '_setupHomeserverManagers',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {\n var homeserverDomain, discoveryResponse, managers, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, hsManager;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.prev = 0;\n\n console.log(\"Updating homeserver-configured integration managers...\");\n homeserverDomain = _MatrixClientPeg2.default.getHomeserverName();\n _context.next = 5;\n return (0, _bluebird.resolve)(_matrixJsSdk.AutoDiscovery.getRawClientConfig(homeserverDomain));\n\n case 5:\n discoveryResponse = _context.sent;\n\n if (!(discoveryResponse && discoveryResponse['m.integrations'])) {\n _context.next = 41;\n break;\n }\n\n managers = discoveryResponse['m.integrations']['managers'];\n\n if (!Array.isArray(managers)) managers = []; // make it an array so we can wipe the HS managers\n\n console.log('Homeserver has ' + managers.length + ' integration managers');\n\n // Clear out any known managers for the homeserver\n // TODO: Log out of the scalar clients\n this._managers = this._managers.filter(function (m) {\n return m.kind !== _IntegrationManagerInstance.KIND_HOMESERVER;\n });\n\n // Now add all the managers the homeserver wants us to have\n _iteratorNormalCompletion = true;\n _didIteratorError = false;\n _iteratorError = undefined;\n _context.prev = 14;\n _iterator = (0, _getIterator3.default)(managers);\n\n case 16:\n if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {\n _context.next = 24;\n break;\n }\n\n hsManager = _step.value;\n\n if (hsManager[\"api_url\"]) {\n _context.next = 20;\n break;\n }\n\n return _context.abrupt('continue', 21);\n\n case 20:\n this._managers.push(new _IntegrationManagerInstance.IntegrationManagerInstance(_IntegrationManagerInstance.KIND_HOMESERVER, hsManager[\"api_url\"], hsManager[\"ui_url\"]) // optional\n );\n\n case 21:\n _iteratorNormalCompletion = true;\n _context.next = 16;\n break;\n\n case 24:\n _context.next = 30;\n break;\n\n case 26:\n _context.prev = 26;\n _context.t0 = _context['catch'](14);\n _didIteratorError = true;\n _iteratorError = _context.t0;\n\n case 30:\n _context.prev = 30;\n _context.prev = 31;\n\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n\n case 33:\n _context.prev = 33;\n\n if (!_didIteratorError) {\n _context.next = 36;\n break;\n }\n\n throw _iteratorError;\n\n case 36:\n return _context.finish(33);\n\n case 37:\n return _context.finish(30);\n\n case 38:\n\n this._primaryManager = null; // reset primary\n _context.next = 42;\n break;\n\n case 41:\n console.log(\"Homeserver has no integration managers\");\n\n case 42:\n _context.next = 47;\n break;\n\n case 44:\n _context.prev = 44;\n _context.t1 = _context['catch'](0);\n\n console.error(_context.t1);\n // Errors during discovery are non-fatal\n\n case 47:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[0, 44], [14, 26, 30, 38], [31,, 33, 37]]);\n }));\n\n function _setupHomeserverManagers() {\n return _ref.apply(this, arguments);\n }\n\n return _setupHomeserverManagers;\n }()\n }, {\n key: '_setupAccountManagers',\n value: function _setupAccountManagers() {\n var _this2 = this;\n\n if (!this._client || !this._client.getUserId()) return; // not logged in\n var widgets = _WidgetUtils2.default.getIntegrationManagerWidgets();\n widgets.forEach(function (w) {\n var data = w.content['data'];\n if (!data) return;\n\n var uiUrl = w.content['url'];\n var apiUrl = data['api_url'];\n if (!apiUrl || !uiUrl) return;\n\n var manager = new _IntegrationManagerInstance.IntegrationManagerInstance(_IntegrationManagerInstance.KIND_ACCOUNT, apiUrl, uiUrl);\n manager.id = w['id'] || w['state_key'] || '';\n _this2._managers.push(manager);\n });\n this._primaryManager = null; // reset primary\n }\n }, {\n key: '_onAccountData',\n value: function _onAccountData(ev) {\n if (ev.getType() === 'm.widgets') {\n this._compileManagers();\n }\n }\n }, {\n key: 'hasManager',\n value: function hasManager() {\n return this._managers.length > 0;\n }\n }, {\n key: 'getOrderedManagers',\n value: function getOrderedManagers() {\n var _this3 = this;\n\n var ordered = [];\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n var _loop = function _loop() {\n var kind = _step2.value;\n\n var managers = _this3._managers.filter(function (m) {\n return m.kind === kind;\n });\n if (!managers || !managers.length) return 'continue';\n\n if (kind === _IntegrationManagerInstance.KIND_ACCOUNT) {\n // Order by state_keys (IDs)\n managers.sort(function (a, b) {\n return a.id.localeCompare(b.id);\n });\n }\n\n ordered.push.apply(ordered, (0, _toConsumableArray3.default)(managers));\n };\n\n for (var _iterator2 = (0, _getIterator3.default)(KIND_PREFERENCE), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var _ret = _loop();\n\n if (_ret === 'continue') continue;\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n return ordered;\n }\n }, {\n key: 'getPrimaryManager',\n value: function getPrimaryManager() {\n if (this.hasManager()) {\n if (this._primaryManager) return this._primaryManager;\n\n this._primaryManager = this.getOrderedManagers()[0];\n return this._primaryManager;\n } else {\n return null;\n }\n }\n }, {\n key: 'openNoManagerDialog',\n value: function openNoManagerDialog() {\n // TODO: Is it Integrations (plural) or Integration (singular). Singular is easier spoken.\n var IntegrationsManager = _index2.default.getComponent(\"views.settings.IntegrationsManager\");\n _Modal2.default.createTrackedDialog(\"Integration Manager\", \"None\", IntegrationsManager, { configured: false }, 'mx_IntegrationsManager');\n }\n }, {\n key: 'openAll',\n value: function openAll() {\n var room = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var screen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var integrationId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n var TabbedIntegrationManagerDialog = _index2.default.getComponent(\"views.dialogs.TabbedIntegrationManagerDialog\");\n _Modal2.default.createTrackedDialog('Tabbed Integration Manager', '', TabbedIntegrationManagerDialog, { room: room, screen: screen, integrationId: integrationId }, 'mx_TabbedIntegrationManagerDialog');\n }\n }, {\n key: 'overwriteManagerOnAccount',\n value: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(manager) {\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return (0, _bluebird.resolve)(_WidgetUtils2.default.removeIntegrationManagerWidgets());\n\n case 2:\n _context2.next = 4;\n return (0, _bluebird.resolve)(_WidgetUtils2.default.addIntegrationManagerWidget(manager.name, manager.uiUrl, manager.apiUrl));\n\n case 4:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function overwriteManagerOnAccount(_x4) {\n return _ref2.apply(this, arguments);\n }\n\n return overwriteManagerOnAccount;\n }()\n\n /**\n * Attempts to discover an integration manager using only its name. This will not validate that\n * the integration manager is functional - that is the caller's responsibility.\n * @param {string} domainName The domain name to look up.\n * @returns {Promise} Resolves to an integration manager instance,\n * or null if none was found.\n */\n\n }, {\n key: 'tryDiscoverManager',\n value: function () {\n var _ref3 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(domainName) {\n var url, wkConfig, result, widget, manager;\n return _regenerator2.default.wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n console.log(\"Looking up integration manager via .well-known\");\n if (domainName.startsWith(\"http:\") || domainName.startsWith(\"https:\")) {\n // trim off the scheme and just use the domain\n url = url.parse(domainName);\n\n domainName = url.host;\n }\n\n wkConfig = void 0;\n _context3.prev = 3;\n _context3.next = 6;\n return (0, _bluebird.resolve)(fetch('https://' + domainName + '/.well-known/matrix/integrations'));\n\n case 6:\n result = _context3.sent;\n _context3.next = 9;\n return (0, _bluebird.resolve)(result.json());\n\n case 9:\n wkConfig = _context3.sent;\n _context3.next = 17;\n break;\n\n case 12:\n _context3.prev = 12;\n _context3.t0 = _context3['catch'](3);\n\n console.error(_context3.t0);\n console.warn(\"Failed to locate integration manager\");\n return _context3.abrupt('return', null);\n\n case 17:\n if (!(!wkConfig || !wkConfig[\"m.integrations_widget\"])) {\n _context3.next = 20;\n break;\n }\n\n console.warn(\"Missing integrations widget on .well-known response\");\n return _context3.abrupt('return', null);\n\n case 20:\n widget = wkConfig[\"m.integrations_widget\"];\n\n if (!(!widget[\"url\"] || !widget[\"data\"] || !widget[\"data\"][\"api_url\"])) {\n _context3.next = 24;\n break;\n }\n\n console.warn(\"Malformed .well-known response for integrations widget\");\n return _context3.abrupt('return', null);\n\n case 24:\n\n // All discovered managers are per-user managers\n manager = new _IntegrationManagerInstance.IntegrationManagerInstance(_IntegrationManagerInstance.KIND_ACCOUNT, widget[\"data\"][\"api_url\"], widget[\"url\"]);\n\n console.log(\"Got an integration manager (untested)\");\n\n // We don't test the manager because the caller may need to do extra\n // checks or similar with it. For instance, they may need to deal with\n // terms of service or want to call something particular.\n\n return _context3.abrupt('return', manager);\n\n case 27:\n case 'end':\n return _context3.stop();\n }\n }\n }, _callee3, this, [[3, 12]]);\n }));\n\n function tryDiscoverManager(_x5) {\n return _ref3.apply(this, arguments);\n }\n\n return tryDiscoverManager;\n }()\n }]);\n return IntegrationManagers;\n}();\n\n// For debugging\n\n\nglobal.mxIntegrationManagers = IntegrationManagers;\n//# sourceMappingURL=IntegrationManagers.js.map","var core = module.exports = { version: '2.6.9' };\nif (typeof __e == 'number') __e = core; // eslint-disable-line no-undef\n","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n","'use strict';\nvar fails = require('./_fails');\n\nmodule.exports = function (method, arg) {\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call\n arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);\n });\n};\n","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n","// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])\nvar anObject = require('./_an-object');\nvar dPs = require('./_object-dps');\nvar enumBugKeys = require('./_enum-bug-keys');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar Empty = function () { /* empty */ };\nvar PROTOTYPE = 'prototype';\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar createDict = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = require('./_dom-create')('iframe');\n var i = enumBugKeys.length;\n var lt = '<';\n var gt = '>';\n var iframeDocument;\n iframe.style.display = 'none';\n require('./_html').appendChild(iframe);\n iframe.src = 'javascript:'; // eslint-disable-line no-script-url\n // createDict = iframe.contentWindow.Object;\n // html.removeChild(iframe);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);\n iframeDocument.close();\n createDict = iframeDocument.F;\n while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];\n return createDict();\n};\n\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n Empty[PROTOTYPE] = anObject(O);\n result = new Empty();\n Empty[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = createDict();\n return Properties === undefined ? result : dPs(result, Properties);\n};\n","var shared = require('./_shared')('keys');\nvar uid = require('./_uid');\nmodule.exports = function (key) {\n return shared[key] || (shared[key] = uid(key));\n};\n","/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n * @module models/event\n */\n\nvar _isFinite = require('babel-runtime/core-js/number/is-finite');\n\nvar _isFinite2 = _interopRequireDefault(_isFinite);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _events = require('events');\n\nvar _utils = require('../utils.js');\n\nvar _utils2 = _interopRequireDefault(_utils);\n\nvar _logger = require('../../src/logger');\n\nvar _logger2 = _interopRequireDefault(_logger);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Enum for event statuses.\n * @readonly\n * @enum {string}\n */\nvar EventStatus = {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT: \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING: \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING: \"sending\",\n /** The event is in a queue waiting to be sent. */\n QUEUED: \"queued\",\n /** The event has been sent to the server, but we have not yet received the\n * echo. */\n SENT: \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED: \"cancelled\"\n};\nmodule.exports.EventStatus = EventStatus;\n\nvar interns = {};\nfunction intern(str) {\n if (!interns[str]) {\n interns[str] = str;\n }\n return interns[str];\n}\n\n/**\n * Construct a Matrix Event object\n * @constructor\n *\n * @param {Object} event The raw event to be wrapped in this DAO\n *\n * @prop {Object} event The raw (possibly encrypted) event. Do not access\n * this property directly unless you absolutely have to. Prefer the getter\n * methods defined on this class. Using the getter methods shields your app\n * from changes to event JSON between Matrix versions.\n *\n * @prop {RoomMember} sender The room member who sent this event, or null e.g.\n * this is a presence event. This is only guaranteed to be set for events that\n * appear in a timeline, ie. do not guarantee that it will be set on state\n * events.\n * @prop {RoomMember} target The room member who is the target of this event, e.g.\n * the invitee, the person being banned, etc.\n * @prop {EventStatus} status The sending status of the event.\n * @prop {Error} error most recent error associated with sending the event, if any\n * @prop {boolean} forwardLooking True if this event is 'forward looking', meaning\n * that getDirectionalContent() will return event.content and not event.prev_content.\n * Default: true. This property is experimental and may change.\n */\nmodule.exports.MatrixEvent = function MatrixEvent(event) {\n // intern the values of matrix events to force share strings and reduce the\n // amount of needless string duplication. This can save moderate amounts of\n // memory (~10% on a 350MB heap).\n // 'membership' at the event level (rather than the content level) is a legacy\n // field that Riot never otherwise looks at, but it will still take up a lot\n // of space if we don't intern it.\n [\"state_key\", \"type\", \"sender\", \"room_id\", \"membership\"].forEach(function (prop) {\n if (!event[prop]) {\n return;\n }\n event[prop] = intern(event[prop]);\n });\n\n [\"membership\", \"avatar_url\", \"displayname\"].forEach(function (prop) {\n if (!event.content || !event.content[prop]) {\n return;\n }\n event.content[prop] = intern(event.content[prop]);\n });\n\n [\"rel_type\"].forEach(function (prop) {\n if (!event.content || !event.content[\"m.relates_to\"] || !event.content[\"m.relates_to\"][prop]) {\n return;\n }\n event.content[\"m.relates_to\"][prop] = intern(event.content[\"m.relates_to\"][prop]);\n });\n\n this.event = event || {};\n\n this.sender = null;\n this.target = null;\n this.status = null;\n this.error = null;\n this.forwardLooking = true;\n this._pushActions = null;\n this._replacingEvent = null;\n this._localRedactionEvent = null;\n this._isCancelled = false;\n\n this._clearEvent = {};\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n this._senderCurve25519Key = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n this._claimedEd25519Key = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * _senderCurve25519Key and _claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n this._forwardingCurve25519KeyChain = [];\n\n /* if we have a process decrypting this event, a Promise which resolves\n * when it is finished. Normally null.\n */\n this._decryptionPromise = null;\n\n /* flag to indicate if we should retry decrypting this event after the\n * first attempt (eg, we have received new data which means that a second\n * attempt may succeed)\n */\n this._retryDecryption = false;\n};\n_utils2.default.inherits(module.exports.MatrixEvent, _events.EventEmitter);\n\n_utils2.default.extend(module.exports.MatrixEvent.prototype, {\n\n /**\n * Get the event_id for this event.\n * @return {string} The event ID, e.g. $143350589368169JsLZx:localhost\n *
\n */\n getId: function getId() {\n return this.event.event_id;\n },\n\n /**\n * Get the user_id for this event.\n * @return {string} The user ID, e.g. @alice:matrix.org
\n */\n getSender: function getSender() {\n return this.event.sender || this.event.user_id; // v2 / v1\n },\n\n /**\n * Get the (decrypted, if necessary) type of event.\n *\n * @return {string} The event type, e.g. m.room.message
\n */\n getType: function getType() {\n return this._clearEvent.type || this.event.type;\n },\n\n /**\n * Get the (possibly encrypted) type of the event that will be sent to the\n * homeserver.\n *\n * @return {string} The event type.\n */\n getWireType: function getWireType() {\n return this.event.type;\n },\n\n /**\n * Get the room_id for this event. This will return undefined
\n * for m.presence
events.\n * @return {string} The room ID, e.g. !cURbafjkfsMDVwdRDQ:matrix.org\n *
\n */\n getRoomId: function getRoomId() {\n return this.event.room_id;\n },\n\n /**\n * Get the timestamp of this event.\n * @return {Number} The event timestamp, e.g. 1433502692297
\n */\n getTs: function getTs() {\n return this.event.origin_server_ts;\n },\n\n /**\n * Get the timestamp of this event, as a Date object.\n * @return {Date} The event date, e.g. new Date(1433502692297)
\n */\n getDate: function getDate() {\n return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;\n },\n\n /**\n * Get the (decrypted, if necessary) event content JSON, even if the event\n * was replaced by another event.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getOriginalContent: function getOriginalContent() {\n if (this._localRedactionEvent) {\n return {};\n }\n return this._clearEvent.content || this.event.content || {};\n },\n\n /**\n * Get the (decrypted, if necessary) event content JSON,\n * or the content from the replacing event, if any.\n * See `makeReplaced`.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getContent: function getContent() {\n if (this._localRedactionEvent) {\n return {};\n } else if (this._replacingEvent) {\n return this._replacingEvent.getContent()[\"m.new_content\"] || {};\n } else {\n return this.getOriginalContent();\n }\n },\n\n /**\n * Get the (possibly encrypted) event content JSON that will be sent to the\n * homeserver.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getWireContent: function getWireContent() {\n return this.event.content || {};\n },\n\n /**\n * Get the previous event content JSON. This will only return something for\n * state events which exist in the timeline.\n * @return {Object} The previous event content JSON, or an empty object.\n */\n getPrevContent: function getPrevContent() {\n // v2 then v1 then default\n return this.getUnsigned().prev_content || this.event.prev_content || {};\n },\n\n /**\n * Get either 'content' or 'prev_content' depending on if this event is\n * 'forward-looking' or not. This can be modified via event.forwardLooking.\n * In practice, this means we get the chronologically earlier content value\n * for this event (this method should surely be called getEarlierContent)\n * This method is experimental and may change.\n * @return {Object} event.content if this event is forward-looking, else\n * event.prev_content.\n */\n getDirectionalContent: function getDirectionalContent() {\n return this.forwardLooking ? this.getContent() : this.getPrevContent();\n },\n\n /**\n * Get the age of this event. This represents the age of the event when the\n * event arrived at the device, and not the age of the event when this\n * function was called.\n * @return {Number} The age of this event in milliseconds.\n */\n getAge: function getAge() {\n return this.getUnsigned().age || this.event.age; // v2 / v1\n },\n\n /**\n * Get the event state_key if it has one. This will return undefined\n *
for message events.\n * @return {string} The event's state_key
.\n */\n getStateKey: function getStateKey() {\n return this.event.state_key;\n },\n\n /**\n * Check if this event is a state event.\n * @return {boolean} True if this is a state event.\n */\n isState: function isState() {\n return this.event.state_key !== undefined;\n },\n\n /**\n * Replace the content of this event with encrypted versions.\n * (This is used when sending an event; it should not be used by applications).\n *\n * @internal\n *\n * @param {string} crypto_type type of the encrypted event - typically\n * \"m.room.encrypted\"\n *\n * @param {object} crypto_content raw 'content' for the encrypted event.\n *\n * @param {string} senderCurve25519Key curve25519 key to record for the\n * sender of this event.\n * See {@link module:models/event.MatrixEvent#getSenderKey}.\n *\n * @param {string} claimedEd25519Key claimed ed25519 key to record for the\n * sender if this event.\n * See {@link module:models/event.MatrixEvent#getClaimedEd25519Key}\n */\n makeEncrypted: function makeEncrypted(crypto_type, crypto_content, senderCurve25519Key, claimedEd25519Key) {\n // keep the plain-text data for 'view source'\n this._clearEvent = {\n type: this.event.type,\n content: this.event.content\n };\n this.event.type = crypto_type;\n this.event.content = crypto_content;\n this._senderCurve25519Key = senderCurve25519Key;\n this._claimedEd25519Key = claimedEd25519Key;\n },\n\n /**\n * Check if this event is currently being decrypted.\n *\n * @return {boolean} True if this event is currently being decrypted, else false.\n */\n isBeingDecrypted: function isBeingDecrypted() {\n return this._decryptionPromise != null;\n },\n\n /**\n * Check if this event is an encrypted event which we failed to decrypt\n *\n * (This implies that we might retry decryption at some point in the future)\n *\n * @return {boolean} True if this event is an encrypted event which we\n * couldn't decrypt.\n */\n isDecryptionFailure: function isDecryptionFailure() {\n return this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype === \"m.bad.encrypted\";\n },\n\n /**\n * Start the process of trying to decrypt this event.\n *\n * (This is used within the SDK: it isn't intended for use by applications)\n *\n * @internal\n *\n * @param {module:crypto} crypto crypto module\n *\n * @returns {Promise} promise which resolves (to undefined) when the decryption\n * attempt is completed.\n */\n attemptDecryption: function () {\n var _ref = (0, _bluebird.method)(function (crypto) {\n // start with a couple of sanity checks.\n if (!this.isEncrypted()) {\n throw new Error(\"Attempt to decrypt event which isn't encrypted\");\n }\n\n if (this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== \"m.bad.encrypted\") {\n // we may want to just ignore this? let's start with rejecting it.\n throw new Error(\"Attempt to decrypt event which has already been encrypted\");\n }\n\n // if we already have a decryption attempt in progress, then it may\n // fail because it was using outdated info. We now have reason to\n // succeed where it failed before, but we don't want to have multiple\n // attempts going at the same time, so just set a flag that says we have\n // new info.\n //\n if (this._decryptionPromise) {\n _logger2.default.log('Event ' + this.getId() + ' already being decrypted; queueing a retry');\n this._retryDecryption = true;\n return this._decryptionPromise;\n }\n\n this._decryptionPromise = this._decryptionLoop(crypto);\n return this._decryptionPromise;\n });\n\n function attemptDecryption(_x) {\n return _ref.apply(this, arguments);\n }\n\n return attemptDecryption;\n }(),\n\n /**\n * Cancel any room key request for this event and resend another.\n *\n * @param {module:crypto} crypto crypto module\n * @param {string} userId the user who received this event\n *\n * @returns {Promise} a promise that resolves when the request is queued\n */\n cancelAndResendKeyRequest: function cancelAndResendKeyRequest(crypto, userId) {\n var wireContent = this.getWireContent();\n return crypto.requestRoomKey({\n algorithm: wireContent.algorithm,\n room_id: this.getRoomId(),\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key\n }, this.getKeyRequestRecipients(userId), true);\n },\n\n /**\n * Calculate the recipients for keyshare requests.\n *\n * @param {string} userId the user who received this event.\n *\n * @returns {Array} array of recipients\n */\n getKeyRequestRecipients: function getKeyRequestRecipients(userId) {\n // send the request to all of our own devices, and the\n // original sending device if it wasn't us.\n var wireContent = this.getWireContent();\n var recipients = [{\n userId: userId, deviceId: '*'\n }];\n var sender = this.getSender();\n if (sender !== userId) {\n recipients.push({\n userId: sender, deviceId: wireContent.device_id\n });\n }\n return recipients;\n },\n\n _decryptionLoop: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(crypto) {\n var res, err;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return (0, _bluebird.resolve)(_bluebird2.default.resolve());\n\n case 2:\n if (!true) {\n _context.next = 37;\n break;\n }\n\n this._retryDecryption = false;\n\n res = void 0;\n err = void 0;\n _context.prev = 6;\n\n if (crypto) {\n _context.next = 11;\n break;\n }\n\n res = this._badEncryptedMessage(\"Encryption not enabled\");\n _context.next = 14;\n break;\n\n case 11:\n _context.next = 13;\n return (0, _bluebird.resolve)(crypto.decryptEvent(this));\n\n case 13:\n res = _context.sent;\n\n case 14:\n _context.next = 29;\n break;\n\n case 16:\n _context.prev = 16;\n _context.t0 = _context['catch'](6);\n\n if (!(_context.t0.name !== \"DecryptionError\")) {\n _context.next = 23;\n break;\n }\n\n // not a decryption error: log the whole exception as an error\n // (and don't bother with a retry)\n _logger2.default.error('Error decrypting event (id=' + this.getId() + '): ' + (_context.t0.stack || _context.t0));\n this._decryptionPromise = null;\n this._retryDecryption = false;\n return _context.abrupt('return');\n\n case 23:\n\n err = _context.t0;\n\n // see if we have a retry queued.\n //\n // NB: make sure to keep this check in the same tick of the\n // event loop as `_decryptionPromise = null` below - otherwise we\n // risk a race:\n //\n // * A: we check _retryDecryption here and see that it is\n // false\n // * B: we get a second call to attemptDecryption, which sees\n // that _decryptionPromise is set so sets\n // _retryDecryption\n // * A: we continue below, clear _decryptionPromise, and\n // never do the retry.\n //\n\n if (!this._retryDecryption) {\n _context.next = 27;\n break;\n }\n\n // decryption error, but we have a retry queued.\n _logger2.default.log('Got error decrypting event (id=' + this.getId() + ': ' + (_context.t0 + '), but retrying'));\n return _context.abrupt('continue', 2);\n\n case 27:\n\n // decryption error, no retries queued. Warn about the error and\n // set it to m.bad.encrypted.\n _logger2.default.warn('Error decrypting event (id=' + this.getId() + '): ' + _context.t0.detailedString);\n\n res = this._badEncryptedMessage(_context.t0.message);\n\n case 29:\n\n // at this point, we've either successfully decrypted the event, or have given up\n // (and set res to a 'badEncryptedMessage'). Either way, we can now set the\n // cleartext of the event and raise Event.decrypted.\n //\n // make sure we clear '_decryptionPromise' before sending the 'Event.decrypted' event,\n // otherwise the app will be confused to see `isBeingDecrypted` still set when\n // there isn't an `Event.decrypted` on the way.\n //\n // see also notes on _retryDecryption above.\n //\n this._decryptionPromise = null;\n this._retryDecryption = false;\n this._setClearData(res);\n\n // Before we emit the event, clear the push actions so that they can be recalculated\n // by relevant code. We do this because the clear event has now changed, making it\n // so that existing rules can be re-run over the applicable properties. Stuff like\n // highlighting when the user's name is mentioned rely on this happening. We also want\n // to set the push actions before emitting so that any notification listeners don't\n // pick up the wrong contents.\n this.setPushActions(null);\n\n this.emit(\"Event.decrypted\", this, err);\n\n return _context.abrupt('return');\n\n case 37:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[6, 16]]);\n }));\n\n function _decryptionLoop(_x2) {\n return _ref2.apply(this, arguments);\n }\n\n return _decryptionLoop;\n }(),\n\n _badEncryptedMessage: function _badEncryptedMessage(reason) {\n return {\n clearEvent: {\n type: \"m.room.message\",\n content: {\n msgtype: \"m.bad.encrypted\",\n body: \"** Unable to decrypt: \" + reason + \" **\"\n }\n }\n };\n },\n\n /**\n * Update the cleartext data on this event.\n *\n * (This is used after decrypting an event; it should not be used by applications).\n *\n * @internal\n *\n * @fires module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:crypto~EventDecryptionResult} decryptionResult\n * the decryption result, including the plaintext and some key info\n */\n _setClearData: function _setClearData(decryptionResult) {\n this._clearEvent = decryptionResult.clearEvent;\n this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null;\n this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null;\n this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || [];\n },\n\n /**\n * Gets the cleartext content for this event. If the event is not encrypted,\n * or encryption has not been completed, this will return null.\n *\n * @returns {Object} The cleartext (decrypted) content for the event\n */\n getClearContent: function getClearContent() {\n var ev = this._clearEvent;\n return ev && ev.content ? ev.content : null;\n },\n\n /**\n * Check if the event is encrypted.\n * @return {boolean} True if this event is encrypted.\n */\n isEncrypted: function isEncrypted() {\n return this.event.type === \"m.room.encrypted\";\n },\n\n /**\n * The curve25519 key for the device that we think sent this event\n *\n * For an Olm-encrypted event, this is inferred directly from the DH\n * exchange at the start of the session: the curve25519 key is involved in\n * the DH exchange, so only a device which holds the private part of that\n * key can establish such a session.\n *\n * For a megolm-encrypted event, it is inferred from the Olm message which\n * established the megolm session\n *\n * @return {string}\n */\n getSenderKey: function getSenderKey() {\n return this._senderCurve25519Key;\n },\n\n /**\n * The additional keys the sender of this encrypted event claims to possess.\n *\n * Just a wrapper for #getClaimedEd25519Key (q.v.)\n *\n * @return {Object}\n */\n getKeysClaimed: function getKeysClaimed() {\n return {\n ed25519: this._claimedEd25519Key\n };\n },\n\n /**\n * Get the ed25519 the sender of this event claims to own.\n *\n * For Olm messages, this claim is encoded directly in the plaintext of the\n * event itself. For megolm messages, it is implied by the m.room_key event\n * which established the megolm session.\n *\n * Until we download the device list of the sender, it's just a claim: the\n * device list gives a proof that the owner of the curve25519 key used for\n * this event (and returned by #getSenderKey) also owns the ed25519 key by\n * signing the public curve25519 key with the ed25519 key.\n *\n * In general, applications should not use this method directly, but should\n * instead use MatrixClient.getEventSenderDeviceInfo.\n *\n * @return {string}\n */\n getClaimedEd25519Key: function getClaimedEd25519Key() {\n return this._claimedEd25519Key;\n },\n\n /**\n * Get the curve25519 keys of the devices which were involved in telling us\n * about the claimedEd25519Key and sender curve25519 key.\n *\n * Normally this will be empty, but in the case of a forwarded megolm\n * session, the sender keys are sent to us by another device (the forwarding\n * device), which we need to trust to do this. In that case, the result will\n * be a list consisting of one entry.\n *\n * If the device that sent us the key (A) got it from another device which\n * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on.\n *\n * @return {string[]} base64-encoded curve25519 keys, from oldest to newest.\n */\n getForwardingCurve25519KeyChain: function getForwardingCurve25519KeyChain() {\n return this._forwardingCurve25519KeyChain;\n },\n\n getUnsigned: function getUnsigned() {\n return this.event.unsigned || {};\n },\n\n unmarkLocallyRedacted: function unmarkLocallyRedacted() {\n var value = this._localRedactionEvent;\n this._localRedactionEvent = null;\n if (this.event.unsigned) {\n this.event.unsigned.redacted_because = null;\n }\n return !!value;\n },\n\n markLocallyRedacted: function markLocallyRedacted(redactionEvent) {\n if (this._localRedactionEvent) {\n return;\n }\n this.emit(\"Event.beforeRedaction\", this, redactionEvent);\n this._localRedactionEvent = redactionEvent;\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redactionEvent.event;\n },\n\n /**\n * Update the content of an event in the same way it would be by the server\n * if it were redacted before it was sent to us\n *\n * @param {module:models/event.MatrixEvent} redaction_event\n * event causing the redaction\n */\n makeRedacted: function makeRedacted(redaction_event) {\n // quick sanity-check\n if (!redaction_event.event) {\n throw new Error(\"invalid redaction_event in makeRedacted\");\n }\n\n this._localRedactionEvent = null;\n\n this.emit(\"Event.beforeRedaction\", this, redaction_event);\n\n this._replacingEvent = null;\n // we attempt to replicate what we would see from the server if\n // the event had been redacted before we saw it.\n //\n // The server removes (most of) the content of the event, and adds a\n // \"redacted_because\" key to the unsigned section containing the\n // redacted event.\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redaction_event.event;\n\n var key = void 0;\n for (key in this.event) {\n if (!this.event.hasOwnProperty(key)) {\n continue;\n }\n if (!_REDACT_KEEP_KEY_MAP[key]) {\n delete this.event[key];\n }\n }\n\n var keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {};\n var content = this.getContent();\n for (key in content) {\n if (!content.hasOwnProperty(key)) {\n continue;\n }\n if (!keeps[key]) {\n delete content[key];\n }\n }\n },\n\n /**\n * Check if this event has been redacted\n *\n * @return {boolean} True if this event has been redacted\n */\n isRedacted: function isRedacted() {\n return Boolean(this.getUnsigned().redacted_because);\n },\n\n /**\n * Check if this event is a redaction of another event\n *\n * @return {boolean} True if this event is a redaction\n */\n isRedaction: function isRedaction() {\n return this.getType() === \"m.room.redaction\";\n },\n\n /**\n * Get the push actions, if known, for this event\n *\n * @return {?Object} push actions\n */\n getPushActions: function getPushActions() {\n return this._pushActions;\n },\n\n /**\n * Set the push actions for this event.\n *\n * @param {Object} pushActions push actions\n */\n setPushActions: function setPushActions(pushActions) {\n this._pushActions = pushActions;\n },\n\n /**\n * Replace the `event` property and recalculate any properties based on it.\n * @param {Object} event the object to assign to the `event` property\n */\n handleRemoteEcho: function handleRemoteEcho(event) {\n var oldUnsigned = this.getUnsigned();\n var oldId = this.getId();\n this.event = event;\n // if this event was redacted before it was sent, it's locally marked as redacted.\n // At this point, we've received the remote echo for the event, but not yet for\n // the redaction that we are sending ourselves. Preserve the locally redacted\n // state by copying over redacted_because so we don't get a flash of\n // redacted, not-redacted, redacted as remote echos come in\n if (oldUnsigned.redacted_because) {\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = oldUnsigned.redacted_because;\n }\n // successfully sent.\n this.setStatus(null);\n if (this.getId() !== oldId) {\n // emit the event if it changed\n this.emit(\"Event.localEventIdReplaced\", this);\n }\n },\n\n /**\n * Whether the event is in any phase of sending, send failure, waiting for\n * remote echo, etc.\n *\n * @return {boolean}\n */\n isSending: function isSending() {\n return !!this.status;\n },\n\n\n /**\n * Update the event's sending status and emit an event as well.\n *\n * @param {String} status The new status\n */\n setStatus: function setStatus(status) {\n this.status = status;\n this.emit(\"Event.status\", this, status);\n },\n replaceLocalEventId: function replaceLocalEventId(eventId) {\n this.event.event_id = eventId;\n this.emit(\"Event.localEventIdReplaced\", this);\n },\n\n\n /**\n * Get whether the event is a relation event, and of a given type if\n * `relType` is passed in.\n *\n * @param {string?} relType if given, checks that the relation is of the\n * given type\n * @return {boolean}\n */\n isRelation: function isRelation() {\n var relType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;\n\n // Relation info is lifted out of the encrypted content when sent to\n // encrypted rooms, so we have to check `getWireContent` for this.\n var content = this.getWireContent();\n var relation = content && content[\"m.relates_to\"];\n return relation && relation.rel_type && relation.event_id && (relType && relation.rel_type === relType || !relType);\n },\n\n\n /**\n * Get relation info for the event, if any.\n *\n * @return {Object}\n */\n getRelation: function getRelation() {\n if (!this.isRelation()) {\n return null;\n }\n return this.getWireContent()[\"m.relates_to\"];\n },\n\n\n /**\n * Set an event that replaces the content of this event, through an m.replace relation.\n *\n * @param {MatrixEvent?} newEvent the event with the replacing content, if any.\n */\n makeReplaced: function makeReplaced(newEvent) {\n // don't allow redacted events to be replaced.\n // if newEvent is null we allow to go through though,\n // as with local redaction, the replacing event might get\n // cancelled, which should be reflected on the target event.\n if (this.isRedacted() && newEvent) {\n return;\n }\n if (this._replacingEvent !== newEvent) {\n this._replacingEvent = newEvent;\n this.emit(\"Event.replaced\", this);\n }\n },\n\n\n /**\n * Returns the status of any associated edit or redaction\n * (not for reactions/annotations as their local echo doesn't affect the orignal event),\n * or else the status of the event.\n *\n * @return {EventStatus}\n */\n getAssociatedStatus: function getAssociatedStatus() {\n if (this._replacingEvent) {\n return this._replacingEvent.status;\n } else if (this._localRedactionEvent) {\n return this._localRedactionEvent.status;\n }\n return this.status;\n },\n getServerAggregatedRelation: function getServerAggregatedRelation(relType) {\n var relations = this.getUnsigned()[\"m.relations\"];\n if (relations) {\n return relations[relType];\n }\n },\n\n\n /**\n * Returns the event ID of the event replacing the content of this event, if any.\n *\n * @return {string?}\n */\n replacingEventId: function replacingEventId() {\n var replaceRelation = this.getServerAggregatedRelation(\"m.replace\");\n if (replaceRelation) {\n return replaceRelation.event_id;\n } else if (this._replacingEvent) {\n return this._replacingEvent.getId();\n }\n },\n\n\n /**\n * Returns the event replacing the content of this event, if any.\n * Replacements are aggregated on the server, so this would only\n * return an event in case it came down the sync, or for local echo of edits.\n *\n * @return {MatrixEvent?}\n */\n replacingEvent: function replacingEvent() {\n return this._replacingEvent;\n },\n\n\n /**\n * Returns the origin_server_ts of the event replacing the content of this event, if any.\n *\n * @return {Date?}\n */\n replacingEventDate: function replacingEventDate() {\n var replaceRelation = this.getServerAggregatedRelation(\"m.replace\");\n if (replaceRelation) {\n var ts = replaceRelation.origin_server_ts;\n if ((0, _isFinite2.default)(ts)) {\n return new Date(ts);\n }\n } else if (this._replacingEvent) {\n return this._replacingEvent.getDate();\n }\n },\n\n\n /**\n * Returns the event that wants to redact this event, but hasn't been sent yet.\n * @return {MatrixEvent} the event\n */\n localRedactionEvent: function localRedactionEvent() {\n return this._localRedactionEvent;\n },\n\n\n /**\n * For relations and redactions, returns the event_id this event is referring to.\n *\n * @return {string?}\n */\n getAssociatedId: function getAssociatedId() {\n var relation = this.getRelation();\n if (relation) {\n return relation.event_id;\n } else if (this.isRedaction()) {\n return this.event.redacts;\n }\n },\n\n\n /**\n * Checks if this event is associated with another event. See `getAssociatedId`.\n *\n * @return {bool}\n */\n hasAssocation: function hasAssocation() {\n return !!this.getAssociatedId();\n },\n\n\n /**\n * Update the related id with a new one.\n *\n * Used to replace a local id with remote one before sending\n * an event with a related id.\n *\n * @param {string} eventId the new event id\n */\n updateAssociatedId: function updateAssociatedId(eventId) {\n var relation = this.getRelation();\n if (relation) {\n relation.event_id = eventId;\n } else if (this.isRedaction()) {\n this.event.redacts = eventId;\n }\n },\n\n\n /**\n * Flags an event as cancelled due to future conditions. For example, a verification\n * request event in the same sync transaction may be flagged as cancelled to warn\n * listeners that a cancellation event is coming down the same pipe shortly.\n * @param {boolean} cancelled Whether the event is to be cancelled or not.\n */\n flagCancelled: function flagCancelled() {\n var cancelled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n\n this._isCancelled = cancelled;\n },\n\n\n /**\n * Gets whether or not the event is flagged as cancelled. See flagCancelled() for\n * more information.\n * @returns {boolean} True if the event is cancelled, false otherwise.\n */\n isCancelled: function isCancelled() {\n return this._isCancelled;\n },\n\n\n /**\n * Summarise the event as JSON for debugging. If encrypted, include both the\n * decrypted and encrypted view of the event. This is named `toJSON` for use\n * with `JSON.stringify` which checks objects for functions named `toJSON`\n * and will call them to customise the output if they are defined.\n *\n * @return {Object}\n */\n toJSON: function toJSON() {\n var event = {\n type: this.getType(),\n sender: this.getSender(),\n content: this.getContent(),\n event_id: this.getId(),\n origin_server_ts: this.getTs(),\n unsigned: this.getUnsigned(),\n room_id: this.getRoomId()\n };\n\n // if this is a redaction then attach the redacts key\n if (this.isRedaction()) {\n event.redacts = this.event.redacts;\n }\n\n if (!this.isEncrypted()) {\n return event;\n }\n\n return {\n decrypted: event,\n encrypted: this.event\n };\n }\n});\n\n/* _REDACT_KEEP_KEY_MAP gives the keys we keep when an event is redacted\n *\n * This is specified here:\n * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions\n *\n * Also:\n * - We keep 'unsigned' since that is created by the local server\n * - We keep user_id for backwards-compat with v1\n */\nvar _REDACT_KEEP_KEY_MAP = ['event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state', 'content', 'unsigned', 'origin_server_ts'].reduce(function (ret, val) {\n ret[val] = 1;return ret;\n}, {});\n\n// a map from event type to the .content keys we keep when an event is redacted\nvar _REDACT_KEEP_CONTENT_MAP = {\n 'm.room.member': { 'membership': 1 },\n 'm.room.create': { 'creator': 1 },\n 'm.room.join_rules': { 'join_rule': 1 },\n 'm.room.power_levels': { 'ban': 1, 'events': 1, 'events_default': 1,\n 'kick': 1, 'redact': 1, 'state_default': 1,\n 'users': 1, 'users_default': 1\n },\n 'm.room.aliases': { 'aliases': 1 }\n};\n\n/**\n * Fires when an event is decrypted\n *\n * @event module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:models/event.MatrixEvent} event\n * The matrix event which has been decrypted\n * @param {module:crypto/algorithms/base.DecryptionError?} err\n * The error that occured during decryption, or `undefined` if no\n * error occured.\n */\n//# sourceMappingURL=event.js.map","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.ValidatedServerConfig = undefined;\n\nvar _regenerator = require(\"babel-runtime/regenerator\");\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require(\"bluebird\");\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _react = require(\"react\");\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _matrixJsSdk = require(\"matrix-js-sdk\");\n\nvar _languageHandler = require(\"../languageHandler\");\n\nvar _TypeUtils = require(\"./TypeUtils\");\n\nvar _SdkConfig = require(\"../SdkConfig\");\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar LIVELINESS_DISCOVERY_ERRORS = [_matrixJsSdk.AutoDiscovery.ERROR_INVALID_HOMESERVER, _matrixJsSdk.AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER]; /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nvar ValidatedServerConfig = exports.ValidatedServerConfig = function ValidatedServerConfig() {\n (0, _classCallCheck3.default)(this, ValidatedServerConfig);\n};\n\nvar AutoDiscoveryUtils = function () {\n function AutoDiscoveryUtils() {\n (0, _classCallCheck3.default)(this, AutoDiscoveryUtils);\n }\n\n (0, _createClass3.default)(AutoDiscoveryUtils, null, [{\n key: \"isLivelinessError\",\n\n /**\n * Checks if a given error or error message is considered an error\n * relating to the liveliness of the server. Must be an error returned\n * from this AutoDiscoveryUtils class.\n * @param {string|Error} error The error to check\n * @returns {boolean} True if the error is a liveliness error.\n */\n value: function isLivelinessError(error) {\n if (!error) return false;\n return !!LIVELINESS_DISCOVERY_ERRORS.find(function (e) {\n return e === error || e === error.message;\n });\n }\n\n /**\n * Gets the common state for auth components (login, registration, forgot\n * password) for a given validation error.\n * @param {Error} err The error encountered.\n * @param {string} pageName The page for which the error should be customized to. See\n * implementation for known values.\n * @returns {*} The state for the component, given the error.\n */\n\n }, {\n key: \"authComponentStateForError\",\n value: function authComponentStateForError(err) {\n var pageName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"login\";\n\n var title = (0, _languageHandler._t)(\"Cannot reach homeserver\");\n var body = (0, _languageHandler._t)(\"Ensure you have a stable internet connection, or get in touch with the server admin\");\n if (!AutoDiscoveryUtils.isLivelinessError(err)) {\n title = (0, _languageHandler._t)(\"Your Riot is misconfigured\");\n body = (0, _languageHandler._t)(\"Ask your Riot admin to check your config for incorrect or duplicate entries.\", {}, {\n a: function a(sub) {\n return _react2.default.createElement(\n \"a\",\n {\n href: \"https://github.com/vector-im/riot-web/blob/master/docs/config.md\",\n target: \"_blank\",\n rel: \"noopener\"\n },\n sub\n );\n }\n });\n }\n\n var isFatalError = true;\n var errorMessage = err.message ? err.message : err;\n if (errorMessage === _matrixJsSdk.AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER) {\n isFatalError = false;\n title = (0, _languageHandler._t)(\"Cannot reach identity server\");\n\n // It's annoying having a ladder for the third word in the same sentence, but our translations\n // don't make this easy to avoid.\n if (pageName === \"register\") {\n body = (0, _languageHandler._t)(\"You can register, but some features will be unavailable until the identity server is \" + \"back online. If you keep seeing this warning, check your configuration or contact a server \" + \"admin.\");\n } else if (pageName === \"reset_password\") {\n body = (0, _languageHandler._t)(\"You can reset your password, but some features will be unavailable until the identity \" + \"server is back online. If you keep seeing this warning, check your configuration or contact \" + \"a server admin.\");\n } else {\n body = (0, _languageHandler._t)(\"You can log in, but some features will be unavailable until the identity server is \" + \"back online. If you keep seeing this warning, check your configuration or contact a server \" + \"admin.\");\n }\n }\n\n return {\n serverIsAlive: false,\n serverErrorIsFatal: isFatalError,\n serverDeadError: _react2.default.createElement(\n \"div\",\n null,\n _react2.default.createElement(\n \"strong\",\n null,\n title\n ),\n _react2.default.createElement(\n \"div\",\n null,\n body\n )\n )\n };\n }\n\n /**\n * Validates a server configuration, using a pair of URLs as input.\n * @param {string} homeserverUrl The homeserver URL.\n * @param {string} identityUrl The identity server URL.\n * @param {boolean} syntaxOnly If true, errors relating to liveliness of the servers will\n * not be raised.\n * @returns {Promise} Resolves to the validated configuration.\n */\n\n }, {\n key: \"validateServerConfigWithStaticUrls\",\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(homeserverUrl, identityUrl) {\n var syntaxOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var wellknownConfig, result, url, serverName;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (homeserverUrl) {\n _context.next = 2;\n break;\n }\n\n throw (0, _languageHandler.newTranslatableError)((0, _languageHandler._td)(\"No homeserver URL provided\"));\n\n case 2:\n wellknownConfig = {\n \"m.homeserver\": {\n base_url: homeserverUrl\n }\n };\n\n\n if (identityUrl) {\n wellknownConfig['m.identity_server'] = {\n base_url: identityUrl\n };\n }\n\n _context.next = 6;\n return (0, _bluebird.resolve)(_matrixJsSdk.AutoDiscovery.fromDiscoveryConfig(wellknownConfig));\n\n case 6:\n result = _context.sent;\n url = new URL(homeserverUrl);\n serverName = url.hostname;\n return _context.abrupt(\"return\", AutoDiscoveryUtils.buildValidatedConfigFromDiscovery(serverName, result, syntaxOnly));\n\n case 10:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function validateServerConfigWithStaticUrls(_x2, _x3, _x4) {\n return _ref.apply(this, arguments);\n }\n\n return validateServerConfigWithStaticUrls;\n }()\n\n /**\n * Validates a server configuration, using a homeserver domain name as input.\n * @param {string} serverName The homeserver domain name (eg: \"matrix.org\") to validate.\n * @param {boolean} syntaxOnly If true, errors relating to liveliness of the servers will\n * not be raised.\n * @returns {Promise} Resolves to the validated configuration.\n */\n\n }, {\n key: \"validateServerName\",\n value: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(serverName) {\n var syntaxOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var result;\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return (0, _bluebird.resolve)(_matrixJsSdk.AutoDiscovery.findClientConfig(serverName));\n\n case 2:\n result = _context2.sent;\n return _context2.abrupt(\"return\", AutoDiscoveryUtils.buildValidatedConfigFromDiscovery(serverName, result));\n\n case 4:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function validateServerName(_x6, _x7) {\n return _ref2.apply(this, arguments);\n }\n\n return validateServerName;\n }()\n\n /**\n * Validates a server configuration, using a pre-calculated AutoDiscovery result as\n * input.\n * @param {string} serverName The domain name the AutoDiscovery result is for.\n * @param {*} discoveryResult The AutoDiscovery result.\n * @param {boolean} syntaxOnly If true, errors relating to liveliness of the servers will\n * not be raised.\n * @returns {Promise} Resolves to the validated configuration.\n */\n\n }, {\n key: \"buildValidatedConfigFromDiscovery\",\n value: function buildValidatedConfigFromDiscovery(serverName, discoveryResult) {\n var syntaxOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n if (!discoveryResult || !discoveryResult[\"m.homeserver\"]) {\n // This shouldn't happen without major misconfiguration, so we'll log a bit of information\n // in the log so we can find this bit of codee but otherwise tell teh user \"it broke\".\n console.error(\"Ended up in a state of not knowing which homeserver to connect to.\");\n throw (0, _languageHandler.newTranslatableError)((0, _languageHandler._td)(\"Unexpected error resolving homeserver configuration\"));\n }\n\n var hsResult = discoveryResult['m.homeserver'];\n var isResult = discoveryResult['m.identity_server'];\n\n var defaultConfig = _SdkConfig2.default.get()[\"validated_server_config\"];\n\n // Validate the identity server first because an invalid identity server causes\n // and invalid homeserver, which may not be picked up correctly.\n\n // Note: In the cases where we rely on the default IS from the config (namely\n // lack of identity server provided by the discovery method), we intentionally do not\n // validate it. This has already been validated and this helps some off-the-grid usage\n // of Riot.\n var preferredIdentityUrl = defaultConfig && defaultConfig['isUrl'];\n if (isResult && isResult.state === _matrixJsSdk.AutoDiscovery.SUCCESS) {\n preferredIdentityUrl = isResult[\"base_url\"];\n } else if (isResult && isResult.state !== _matrixJsSdk.AutoDiscovery.PROMPT) {\n console.error(\"Error determining preferred identity server URL:\", isResult);\n if (!syntaxOnly || !AutoDiscoveryUtils.isLivelinessError(isResult.error)) {\n if (_matrixJsSdk.AutoDiscovery.ALL_ERRORS.indexOf(isResult.error) !== -1) {\n throw (0, _languageHandler.newTranslatableError)(isResult.error);\n }\n throw (0, _languageHandler.newTranslatableError)((0, _languageHandler._td)(\"Unexpected error resolving identity server configuration\"));\n } // else the error is not related to syntax - continue anyways.\n\n // rewrite homeserver error if we don't care about problems\n if (syntaxOnly) {\n hsResult.error = _matrixJsSdk.AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Also use the user's supplied identity server if provided\n if (isResult[\"base_url\"]) preferredIdentityUrl = isResult[\"base_url\"];\n }\n }\n\n if (hsResult.state !== _matrixJsSdk.AutoDiscovery.SUCCESS) {\n console.error(\"Error processing homeserver config:\", hsResult);\n if (!syntaxOnly || !AutoDiscoveryUtils.isLivelinessError(hsResult.error)) {\n if (_matrixJsSdk.AutoDiscovery.ALL_ERRORS.indexOf(hsResult.error) !== -1) {\n throw (0, _languageHandler.newTranslatableError)(hsResult.error);\n }\n throw (0, _languageHandler.newTranslatableError)((0, _languageHandler._td)(\"Unexpected error resolving homeserver configuration\"));\n } // else the error is not related to syntax - continue anyways.\n }\n\n var preferredHomeserverUrl = hsResult[\"base_url\"];\n var preferredHomeserverName = serverName ? serverName : hsResult[\"server_name\"];\n\n var url = new URL(preferredHomeserverUrl);\n if (!preferredHomeserverName) preferredHomeserverName = url.hostname;\n\n // It should have been set by now, so check it\n if (!preferredHomeserverName) {\n console.error(\"Failed to parse homeserver name from homeserver URL\");\n throw (0, _languageHandler.newTranslatableError)((0, _languageHandler._td)(\"Unexpected error resolving homeserver configuration\"));\n }\n\n return (0, _TypeUtils.makeType)(ValidatedServerConfig, {\n hsUrl: preferredHomeserverUrl,\n hsName: preferredHomeserverName,\n hsNameIsDifferent: url.hostname !== preferredHomeserverName,\n isUrl: preferredIdentityUrl,\n isDefault: false\n });\n }\n }]);\n return AutoDiscoveryUtils;\n}();\n\nexports.default = AutoDiscoveryUtils;\n//# sourceMappingURL=AutoDiscoveryUtils.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.formatDate = formatDate;\nexports.formatFullDateNoTime = formatFullDateNoTime;\nexports.formatFullDate = formatFullDate;\nexports.formatFullTime = formatFullTime;\nexports.formatTime = formatTime;\nexports.wantsDateSeparator = wantsDateSeparator;\n\nvar _languageHandler = require('./languageHandler');\n\nfunction getDaysArray() {\n return [(0, _languageHandler._t)('Sun'), (0, _languageHandler._t)('Mon'), (0, _languageHandler._t)('Tue'), (0, _languageHandler._t)('Wed'), (0, _languageHandler._t)('Thu'), (0, _languageHandler._t)('Fri'), (0, _languageHandler._t)('Sat')];\n} /*\n Copyright 2015, 2016 OpenMarket Ltd\n Copyright 2017 Vector Creations Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nfunction getMonthsArray() {\n return [(0, _languageHandler._t)('Jan'), (0, _languageHandler._t)('Feb'), (0, _languageHandler._t)('Mar'), (0, _languageHandler._t)('Apr'), (0, _languageHandler._t)('May'), (0, _languageHandler._t)('Jun'), (0, _languageHandler._t)('Jul'), (0, _languageHandler._t)('Aug'), (0, _languageHandler._t)('Sep'), (0, _languageHandler._t)('Oct'), (0, _languageHandler._t)('Nov'), (0, _languageHandler._t)('Dec')];\n}\n\nfunction pad(n) {\n return (n < 10 ? '0' : '') + n;\n}\n\nfunction twelveHourTime(date) {\n var showSeconds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var hours = date.getHours() % 12;\n var minutes = pad(date.getMinutes());\n var ampm = date.getHours() >= 12 ? (0, _languageHandler._t)('PM') : (0, _languageHandler._t)('AM');\n hours = hours ? hours : 12; // convert 0 -> 12\n if (showSeconds) {\n var seconds = pad(date.getSeconds());\n return hours + ':' + minutes + ':' + seconds + ampm;\n }\n return hours + ':' + minutes + ampm;\n}\n\nfunction formatDate(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var now = new Date();\n var days = getDaysArray();\n var months = getMonthsArray();\n if (date.toDateString() === now.toDateString()) {\n return formatTime(date, showTwelveHour);\n } else if (now.getTime() - date.getTime() < 6 * 24 * 60 * 60 * 1000) {\n // TODO: use standard date localize function provided in counterpart\n return (0, _languageHandler._t)('%(weekDayName)s %(time)s', {\n weekDayName: days[date.getDay()],\n time: formatTime(date, showTwelveHour)\n });\n } else if (now.getFullYear() === date.getFullYear()) {\n // TODO: use standard date localize function provided in counterpart\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(time)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n time: formatTime(date, showTwelveHour)\n });\n }\n return formatFullDate(date, showTwelveHour);\n}\n\nfunction formatFullDateNoTime(date) {\n var days = getDaysArray();\n var months = getMonthsArray();\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n fullYear: date.getFullYear()\n });\n}\n\nfunction formatFullDate(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var days = getDaysArray();\n var months = getMonthsArray();\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n fullYear: date.getFullYear(),\n time: formatFullTime(date, showTwelveHour)\n });\n}\n\nfunction formatFullTime(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (showTwelveHour) {\n return twelveHourTime(date, true);\n }\n return pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());\n}\n\nfunction formatTime(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (showTwelveHour) {\n return twelveHourTime(date);\n }\n return pad(date.getHours()) + ':' + pad(date.getMinutes());\n}\n\nvar MILLIS_IN_DAY = 86400000;\nfunction wantsDateSeparator(prevEventDate, nextEventDate) {\n if (!nextEventDate || !prevEventDate) {\n return false;\n }\n // Return early for events that are > 24h apart\n if (Math.abs(prevEventDate.getTime() - nextEventDate.getTime()) > MILLIS_IN_DAY) {\n return true;\n }\n\n // Compare weekdays\n return prevEventDate.getDay() !== nextEventDate.getDay();\n}\n//# sourceMappingURL=DateUtils.js.map","\"use strict\";\n\nexports.__esModule = true;\n\nexports.default = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};","module.exports = \"img/cancel.4b9715b.svg\";","module.exports = \"img/warning.05cc423.svg\";","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","// most Object methods by ES6 should accept primitives\nvar $export = require('./_export');\nvar core = require('./_core');\nvar fails = require('./_fails');\nmodule.exports = function (KEY, exec) {\n var fn = (core.Object || {})[KEY] || Object[KEY];\n var exp = {};\n exp[KEY] = exec(fn);\n $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);\n};\n","// 0 -> Array#forEach\n// 1 -> Array#map\n// 2 -> Array#filter\n// 3 -> Array#some\n// 4 -> Array#every\n// 5 -> Array#find\n// 6 -> Array#findIndex\nvar ctx = require('./_ctx');\nvar IObject = require('./_iobject');\nvar toObject = require('./_to-object');\nvar toLength = require('./_to-length');\nvar asc = require('./_array-species-create');\nmodule.exports = function (TYPE, $create) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n var create = $create || asc;\n return function ($this, callbackfn, that) {\n var O = toObject($this);\n var self = IObject(O);\n var f = ctx(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;\n var val, res;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n val = self[index];\n res = f(val, index, O);\n if (TYPE) {\n if (IS_MAP) result[index] = res; // map\n else if (res) switch (TYPE) {\n case 3: return true; // some\n case 5: return val; // find\n case 6: return index; // findIndex\n case 2: result.push(val); // filter\n } else if (IS_EVERY) return false; // every\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;\n };\n};\n","var core = require('./_core');\nvar global = require('./_global');\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || (global[SHARED] = {});\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: core.version,\n mode: require('./_library') ? 'pure' : 'global',\n copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n});\n","// IE 8- don't enum bug keys\nmodule.exports = (\n 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'\n).split(',');\n","module.exports = { \"default\": require(\"core-js/library/fn/object/entries\"), __esModule: true };","// Browser Request\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// UMD HEADER START \n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define([], factory);\n } else if (typeof exports === 'object') {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like enviroments that support module.exports,\n // like Node.\n module.exports = factory();\n } else {\n // Browser globals (root is window)\n root.returnExports = factory();\n }\n}(this, function () {\n// UMD HEADER END\n\nvar XHR = XMLHttpRequest\nif (!XHR) throw new Error('missing XMLHttpRequest')\nrequest.log = {\n 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop\n}\n\nvar DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes\n\n//\n// request\n//\n\nfunction request(options, callback) {\n // The entry-point to the API: prep the options object and pass the real work to run_xhr.\n if(typeof callback !== 'function')\n throw new Error('Bad callback given: ' + callback)\n\n if(!options)\n throw new Error('No options given')\n\n var options_onResponse = options.onResponse; // Save this for later.\n\n if(typeof options === 'string')\n options = {'uri':options};\n else\n options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.\n\n options.onResponse = options_onResponse // And put it back.\n\n if (options.verbose) request.log = getLogger();\n\n if(options.url) {\n options.uri = options.url;\n delete options.url;\n }\n\n if(!options.uri && options.uri !== \"\")\n throw new Error(\"options.uri is a required argument\");\n\n if(typeof options.uri != \"string\")\n throw new Error(\"options.uri must be a string\");\n\n var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']\n for (var i = 0; i < unsupported_options.length; i++)\n if(options[ unsupported_options[i] ])\n throw new Error(\"options.\" + unsupported_options[i] + \" is not supported\")\n\n options.callback = callback\n options.method = options.method || 'GET';\n options.headers = options.headers || {};\n options.body = options.body || null\n options.timeout = options.timeout || request.DEFAULT_TIMEOUT\n\n if(options.headers.host)\n throw new Error(\"Options.headers.host is not supported\");\n\n if(options.json) {\n options.headers.accept = options.headers.accept || 'application/json'\n if(options.method !== 'GET')\n options.headers['content-type'] = 'application/json'\n\n if(typeof options.json !== 'boolean')\n options.body = JSON.stringify(options.json)\n else if(typeof options.body !== 'string')\n options.body = JSON.stringify(options.body)\n }\n \n //BEGIN QS Hack\n var serialize = function(obj) {\n var str = [];\n for(var p in obj)\n if (obj.hasOwnProperty(p)) {\n str.push(encodeURIComponent(p) + \"=\" + encodeURIComponent(obj[p]));\n }\n return str.join(\"&\");\n }\n \n if(options.qs){\n var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);\n if(options.uri.indexOf('?') !== -1){ //no get params\n options.uri = options.uri+'&'+qs;\n }else{ //existing get params\n options.uri = options.uri+'?'+qs;\n }\n }\n //END QS Hack\n \n //BEGIN FORM Hack\n var multipart = function(obj) {\n //todo: support file type (useful?)\n var result = {};\n result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);\n var lines = [];\n for(var p in obj){\n if (obj.hasOwnProperty(p)) {\n lines.push(\n '--'+result.boundry+\"\\n\"+\n 'Content-Disposition: form-data; name=\"'+p+'\"'+\"\\n\"+\n \"\\n\"+\n obj[p]+\"\\n\"\n );\n }\n }\n lines.push( '--'+result.boundry+'--' );\n result.body = lines.join('');\n result.length = result.body.length;\n result.type = 'multipart/form-data; boundary='+result.boundry;\n return result;\n }\n \n if(options.form){\n if(typeof options.form == 'string') throw('form name unsupported');\n if(options.method === 'POST'){\n var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();\n options.headers['content-type'] = encoding;\n switch(encoding){\n case 'application/x-www-form-urlencoded':\n options.body = serialize(options.form).replace(/%20/g, \"+\");\n break;\n case 'multipart/form-data':\n var multi = multipart(options.form);\n //options.headers['content-length'] = multi.length;\n options.body = multi.body;\n options.headers['content-type'] = multi.type;\n break;\n default : throw new Error('unsupported encoding:'+encoding);\n }\n }\n }\n //END FORM Hack\n\n // If onResponse is boolean true, call back immediately when the response is known,\n // not when the full request is complete.\n options.onResponse = options.onResponse || noop\n if(options.onResponse === true) {\n options.onResponse = callback\n options.callback = noop\n }\n\n // XXX Browsers do not like this.\n //if(options.body)\n // options.headers['content-length'] = options.body.length;\n\n // HTTP basic authentication\n if(!options.headers.authorization && options.auth)\n options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);\n\n return run_xhr(options)\n}\n\nvar req_seq = 0\nfunction run_xhr(options) {\n var xhr = new XHR\n , timed_out = false\n , is_cors = is_crossDomain(options.uri)\n , supports_cors = ('withCredentials' in xhr)\n\n req_seq += 1\n xhr.seq_id = req_seq\n xhr.id = req_seq + ': ' + options.method + ' ' + options.uri\n xhr._id = xhr.id // I know I will type \"_id\" from habit all the time.\n\n if(is_cors && !supports_cors) {\n var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)\n cors_err.cors = 'unsupported'\n return options.callback(cors_err, xhr)\n }\n\n xhr.timeoutTimer = setTimeout(too_late, options.timeout)\n function too_late() {\n timed_out = true\n var er = new Error('ETIMEDOUT')\n er.code = 'ETIMEDOUT'\n er.duration = options.timeout\n\n request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })\n return options.callback(er, xhr)\n }\n\n // Some states can be skipped over, so remember what is still incomplete.\n var did = {'response':false, 'loading':false, 'end':false}\n\n xhr.onreadystatechange = on_state_change\n xhr.open(options.method, options.uri, true) // asynchronous\n if(is_cors)\n xhr.withCredentials = !! options.withCredentials\n xhr.send(options.body)\n return xhr\n\n function on_state_change(event) {\n if(timed_out)\n return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})\n\n request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})\n\n if(xhr.readyState === XHR.OPENED) {\n request.log.debug('Request started', {'id':xhr.id})\n for (var key in options.headers)\n xhr.setRequestHeader(key, options.headers[key])\n }\n\n else if(xhr.readyState === XHR.HEADERS_RECEIVED)\n on_response()\n\n else if(xhr.readyState === XHR.LOADING) {\n on_response()\n on_loading()\n }\n\n else if(xhr.readyState === XHR.DONE) {\n on_response()\n on_loading()\n on_end()\n }\n }\n\n function on_response() {\n if(did.response)\n return\n\n did.response = true\n request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})\n clearTimeout(xhr.timeoutTimer)\n xhr.statusCode = xhr.status // Node request compatibility\n\n // Detect failed CORS requests.\n if(is_cors && xhr.statusCode == 0) {\n var cors_err = new Error('CORS request rejected: ' + options.uri)\n cors_err.cors = 'rejected'\n\n // Do not process this request further.\n did.loading = true\n did.end = true\n\n return options.callback(cors_err, xhr)\n }\n\n options.onResponse(null, xhr)\n }\n\n function on_loading() {\n if(did.loading)\n return\n\n did.loading = true\n request.log.debug('Response body loading', {'id':xhr.id})\n // TODO: Maybe simulate \"data\" events by watching xhr.responseText\n }\n\n function on_end() {\n if(did.end)\n return\n\n did.end = true\n request.log.debug('Request done', {'id':xhr.id})\n\n xhr.body = xhr.responseText\n if(options.json) {\n try { xhr.body = JSON.parse(xhr.responseText) }\n catch (er) { return options.callback(er, xhr) }\n }\n\n options.callback(null, xhr, xhr.body)\n }\n\n} // request\n\nrequest.withCredentials = false;\nrequest.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;\n\n//\n// defaults\n//\n\nrequest.defaults = function(options, requester) {\n var def = function (method) {\n var d = function (params, callback) {\n if(typeof params === 'string')\n params = {'uri': params};\n else {\n params = JSON.parse(JSON.stringify(params));\n }\n for (var i in options) {\n if (params[i] === undefined) params[i] = options[i]\n }\n return method(params, callback)\n }\n return d\n }\n var de = def(request)\n de.get = def(request.get)\n de.post = def(request.post)\n de.put = def(request.put)\n de.head = def(request.head)\n return de\n}\n\n//\n// HTTP method shortcuts\n//\n\nvar shortcuts = [ 'get', 'put', 'post', 'head' ];\nshortcuts.forEach(function(shortcut) {\n var method = shortcut.toUpperCase();\n var func = shortcut.toLowerCase();\n\n request[func] = function(opts) {\n if(typeof opts === 'string')\n opts = {'method':method, 'uri':opts};\n else {\n opts = JSON.parse(JSON.stringify(opts));\n opts.method = method;\n }\n\n var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));\n return request.apply(this, args);\n }\n})\n\n//\n// CouchDB shortcut\n//\n\nrequest.couch = function(options, callback) {\n if(typeof options === 'string')\n options = {'uri':options}\n\n // Just use the request API to do JSON.\n options.json = true\n if(options.body)\n options.json = options.body\n delete options.body\n\n callback = callback || noop\n\n var xhr = request(options, couch_handler)\n return xhr\n\n function couch_handler(er, resp, body) {\n if(er)\n return callback(er, resp, body)\n\n if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {\n // The body is a Couch JSON object indicating the error.\n er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))\n for (var key in body)\n er[key] = body[key]\n return callback(er, resp, body);\n }\n\n return callback(er, resp, body);\n }\n}\n\n//\n// Utility\n//\n\nfunction noop() {}\n\nfunction getLogger() {\n var logger = {}\n , levels = ['trace', 'debug', 'info', 'warn', 'error']\n , level, i\n\n for(i = 0; i < levels.length; i++) {\n level = levels[i]\n\n logger[level] = noop\n if(typeof console !== 'undefined' && console && console[level])\n logger[level] = formatted(console, level)\n }\n\n return logger\n}\n\nfunction formatted(obj, method) {\n return formatted_logger\n\n function formatted_logger(str, context) {\n if(typeof context === 'object')\n str += ' ' + JSON.stringify(context)\n\n return obj[method].call(obj, str)\n }\n}\n\n// Return whether a URL is a cross-domain request.\nfunction is_crossDomain(url) {\n var rurl = /^([\\w\\+\\.\\-]+:)(?:\\/\\/([^\\/?#:]*)(?::(\\d+))?)?/\n\n // jQuery #8138, IE may throw an exception when accessing\n // a field from window.location if document.domain has been set\n var ajaxLocation\n try { ajaxLocation = location.href }\n catch (e) {\n // Use the href attribute of an A element since IE will modify it given document.location\n ajaxLocation = document.createElement( \"a\" );\n ajaxLocation.href = \"\";\n ajaxLocation = ajaxLocation.href;\n }\n\n var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []\n , parts = rurl.exec(url.toLowerCase() )\n\n var result = !!(\n parts &&\n ( parts[1] != ajaxLocParts[1]\n || parts[2] != ajaxLocParts[2]\n || (parts[3] || (parts[1] === \"http:\" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === \"http:\" ? 80 : 443))\n )\n )\n\n //console.debug('is_crossDomain('+url+') -> ' + result)\n return result\n}\n\n// MIT License from http://phpjs.org/functions/base64_encode:358\nfunction b64_enc (data) {\n // Encodes string using MIME base64 algorithm\n var b64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc=\"\", tmp_arr = [];\n\n if (!data) {\n return data;\n }\n\n // assume utf8 data\n // data = this.utf8_encode(data+'');\n\n do { // pack three octets into four hexets\n o1 = data.charCodeAt(i++);\n o2 = data.charCodeAt(i++);\n o3 = data.charCodeAt(i++);\n\n bits = o1<<16 | o2<<8 | o3;\n\n h1 = bits>>18 & 0x3f;\n h2 = bits>>12 & 0x3f;\n h3 = bits>>6 & 0x3f;\n h4 = bits & 0x3f;\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);\n } while (i < data.length);\n\n enc = tmp_arr.join('');\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '==';\n break;\n case 2:\n enc = enc.slice(0, -1) + '=';\n break;\n }\n\n return enc;\n}\n return request;\n//UMD FOOTER START\n}));\n//UMD FOOTER END\n","'use strict';\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _startCallApp = function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(roomId, type) {\n var managers, haveScalar, scalarClient, ErrorDialog, room, currentRoomWidgets, _ErrorDialog3, currentJitsiWidgets, _ErrorDialog4, widgetSessionId, confId, queryString, widgetUrl, apiUrl, widgetData, widgetId;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n // check for a working integrations manager. Technically we could put\n // the state event in anyway, but the resulting widget would then not\n // work for us. Better that the user knows before everyone else in the\n // room sees it.\n managers = _IntegrationManagers.IntegrationManagers.sharedInstance();\n haveScalar = true;\n\n if (!managers.hasManager()) {\n _context.next = 14;\n break;\n }\n\n _context.prev = 3;\n scalarClient = managers.getPrimaryManager().getScalarClient();\n _context.next = 7;\n return (0, _bluebird.resolve)(scalarClient.connect());\n\n case 7:\n haveScalar = scalarClient.hasCredentials();\n _context.next = 12;\n break;\n\n case 10:\n _context.prev = 10;\n _context.t0 = _context['catch'](3);\n\n case 12:\n _context.next = 15;\n break;\n\n case 14:\n haveScalar = false;\n\n case 15:\n if (haveScalar) {\n _context.next = 19;\n break;\n }\n\n ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Could not connect to the integration server', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Could not connect to the integration server'),\n description: (0, _languageHandler._t)('A conference call could not be started because the integrations server is not available')\n });\n return _context.abrupt('return');\n\n case 19:\n\n _dispatcher2.default.dispatch({\n action: 'appsDrawer',\n show: true\n });\n\n room = _MatrixClientPeg2.default.get().getRoom(roomId);\n currentRoomWidgets = _WidgetUtils2.default.getRoomWidgets(room);\n\n if (!_WidgetEchoStore2.default.roomHasPendingWidgetsOfType(roomId, currentRoomWidgets, 'jitsi')) {\n _context.next = 26;\n break;\n }\n\n _ErrorDialog3 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Call already in progress', '', _ErrorDialog3, {\n title: (0, _languageHandler._t)('Call in Progress'),\n description: (0, _languageHandler._t)('A call is currently being placed!')\n });\n return _context.abrupt('return');\n\n case 26:\n currentJitsiWidgets = currentRoomWidgets.filter(function (ev) {\n return ev.getContent().type === 'jitsi';\n });\n\n if (!(currentJitsiWidgets.length > 0)) {\n _context.next = 32;\n break;\n }\n\n console.warn(\"Refusing to start conference call widget in \" + roomId + \" a conference call widget is already present\");\n _ErrorDialog4 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Already have Jitsi Widget', '', _ErrorDialog4, {\n title: (0, _languageHandler._t)('Call in Progress'),\n description: (0, _languageHandler._t)('A call is already in progress!')\n });\n return _context.abrupt('return');\n\n case 32:\n\n // This inherits its poor naming from the field of the same name that goes into\n // the event. It's just a random string to make the Jitsi URLs unique.\n widgetSessionId = Math.random().toString(36).substring(2);\n confId = room.roomId.replace(/[^A-Za-z0-9]/g, '') + widgetSessionId;\n // NB. we can't just encodeURICompoent all of these because the $ signs need to be there\n // (but currently the only thing that needs encoding is the confId)\n\n queryString = ['confId=' + encodeURIComponent(confId), 'isAudioConf=' + (type === 'voice' ? 'true' : 'false'), 'displayName=$matrix_display_name', 'avatarUrl=$matrix_avatar_url', 'email=$matrix_user_id'].join('&');\n widgetUrl = void 0;\n\n if (_SdkConfig2.default.get().integrations_jitsi_widget_url) {\n // Try this config key. This probably isn't ideal as a way of discovering this\n // URL, but this will at least allow the integration manager to not be hardcoded.\n widgetUrl = _SdkConfig2.default.get().integrations_jitsi_widget_url + '?' + queryString;\n } else {\n apiUrl = _IntegrationManagers.IntegrationManagers.sharedInstance().getPrimaryManager().apiUrl;\n\n widgetUrl = apiUrl + '/widgets/jitsi.html?' + queryString;\n }\n\n widgetData = { widgetSessionId: widgetSessionId };\n widgetId = 'jitsi_' + _MatrixClientPeg2.default.get().credentials.userId + '_' + Date.now();\n\n\n _WidgetUtils2.default.setRoomWidget(roomId, widgetId, 'jitsi', widgetUrl, 'Jitsi', widgetData).then(function () {\n console.log('Jitsi widget added');\n }).catch(function (e) {\n if (e.errcode === 'M_FORBIDDEN') {\n var _ErrorDialog5 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n _Modal2.default.createTrackedDialog('Call Failed', '', _ErrorDialog5, {\n title: (0, _languageHandler._t)('Permission Required'),\n description: (0, _languageHandler._t)(\"You do not have permission to start a conference call in this room\")\n });\n }\n console.error(e);\n });\n\n case 40:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[3, 10]]);\n }));\n\n return function _startCallApp(_x, _x2) {\n return _ref.apply(this, arguments);\n };\n}();\n\n// FIXME: Nasty way of making sure we only register\n// with the dispatcher once\n\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _PlatformPeg = require('./PlatformPeg');\n\nvar _PlatformPeg2 = _interopRequireDefault(_PlatformPeg);\n\nvar _Modal = require('./Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _index = require('./index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('./languageHandler');\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _matrixJsSdk2 = _interopRequireDefault(_matrixJsSdk);\n\nvar _dispatcher = require('./dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _SdkConfig = require('./SdkConfig');\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nvar _cryptodevices = require('./cryptodevices');\n\nvar _WidgetUtils = require('./utils/WidgetUtils');\n\nvar _WidgetUtils2 = _interopRequireDefault(_WidgetUtils);\n\nvar _WidgetEchoStore = require('./stores/WidgetEchoStore');\n\nvar _WidgetEchoStore2 = _interopRequireDefault(_WidgetEchoStore);\n\nvar _IntegrationManagers = require('./integrations/IntegrationManagers');\n\nvar _SettingsStore = require('./settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nglobal.mxCalls = {\n //room_id: MatrixCall\n}; /*\n Copyright 2015, 2016 OpenMarket Ltd\n Copyright 2017, 2018 New Vector Ltd\n Copyright 2019 The Matrix.org Foundation C.I.C.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n/*\n * Manages a list of all the currently active calls.\n *\n * This handler dispatches when voip calls are added/updated/removed from this list:\n * {\n * action: 'call_state'\n * room_id: \n * }\n *\n * To know the state of the call, this handler exposes a getter to\n * obtain the call for a room:\n * var call = CallHandler.getCall(roomId)\n * var state = call.call_state; // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing\n *\n * This handler listens for and handles the following actions:\n * {\n * action: 'place_call',\n * type: 'voice|video',\n * room_id: \n * }\n *\n * {\n * action: 'incoming_call'\n * call: MatrixCall\n * }\n *\n * {\n * action: 'hangup'\n * room_id: \n * }\n *\n * {\n * action: 'answer'\n * room_id: \n * }\n */\n\nvar calls = global.mxCalls;\nvar ConferenceHandler = null;\n\nvar audioPromises = {};\n\nfunction play(audioId) {\n // TODO: Attach an invisible element for this instead\n // which listens?\n var audio = document.getElementById(audioId);\n if (audio) {\n if (audioPromises[audioId]) {\n audioPromises[audioId] = audioPromises[audioId].then(function () {\n audio.load();\n return audio.play();\n });\n } else {\n audioPromises[audioId] = audio.play();\n }\n }\n}\n\nfunction pause(audioId) {\n // TODO: Attach an invisible element for this instead\n // which listens?\n var audio = document.getElementById(audioId);\n if (audio) {\n if (audioPromises[audioId]) {\n audioPromises[audioId] = audioPromises[audioId].then(function () {\n return audio.pause();\n });\n } else {\n // pause doesn't actually return a promise, but might as well do this for symmetry with play();\n audioPromises[audioId] = audio.pause();\n }\n }\n}\n\nfunction _reAttemptCall(call) {\n if (call.direction === 'outbound') {\n _dispatcher2.default.dispatch({\n action: 'place_call',\n room_id: call.roomId,\n type: call.type\n });\n } else {\n call.answer();\n }\n}\n\nfunction _setCallListeners(call) {\n call.on(\"error\", function (err) {\n console.error(\"Call error:\", err);\n if (err.code === 'unknown_devices') {\n var QuestionDialog = _index2.default.getComponent(\"dialogs.QuestionDialog\");\n\n _Modal2.default.createTrackedDialog('Call Failed', '', QuestionDialog, {\n title: (0, _languageHandler._t)('Call Failed'),\n description: (0, _languageHandler._t)(\"There are unknown devices in this room: \" + \"if you proceed without verifying them, it will be \" + \"possible for someone to eavesdrop on your call.\"),\n button: (0, _languageHandler._t)('Review Devices'),\n onFinished: function onFinished(confirmed) {\n if (confirmed) {\n var room = _MatrixClientPeg2.default.get().getRoom(call.roomId);\n (0, _cryptodevices.showUnknownDeviceDialogForCalls)(_MatrixClientPeg2.default.get(), room, function () {\n _reAttemptCall(call);\n }, call.direction === 'outbound' ? (0, _languageHandler._t)(\"Call Anyway\") : (0, _languageHandler._t)(\"Answer Anyway\"), call.direction === 'outbound' ? (0, _languageHandler._t)(\"Call\") : (0, _languageHandler._t)(\"Answer\"));\n }\n }\n });\n } else {\n if (_MatrixClientPeg2.default.get().getTurnServers().length === 0 && _SettingsStore2.default.getValue(\"fallbackICEServerAllowed\") === null) {\n _showICEFallbackPrompt();\n return;\n }\n\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Failed', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Call Failed'),\n description: err.message\n });\n }\n });\n call.on(\"hangup\", function () {\n _setCallState(undefined, call.roomId, \"ended\");\n });\n // map web rtc states to dummy UI state\n // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing\n call.on(\"state\", function (newState, oldState) {\n if (newState === \"ringing\") {\n _setCallState(call, call.roomId, \"ringing\");\n pause(\"ringbackAudio\");\n } else if (newState === \"invite_sent\") {\n _setCallState(call, call.roomId, \"ringback\");\n play(\"ringbackAudio\");\n } else if (newState === \"ended\" && oldState === \"connected\") {\n _setCallState(undefined, call.roomId, \"ended\");\n pause(\"ringbackAudio\");\n play(\"callendAudio\");\n } else if (newState === \"ended\" && oldState === \"invite_sent\" && (call.hangupParty === \"remote\" || call.hangupParty === \"local\" && call.hangupReason === \"invite_timeout\")) {\n _setCallState(call, call.roomId, \"busy\");\n pause(\"ringbackAudio\");\n play(\"busyAudio\");\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Call Timeout', ErrorDialog, {\n title: (0, _languageHandler._t)('Call Timeout'),\n description: (0, _languageHandler._t)('The remote side failed to pick up') + '.'\n });\n } else if (oldState === \"invite_sent\") {\n _setCallState(call, call.roomId, \"stop_ringback\");\n pause(\"ringbackAudio\");\n } else if (oldState === \"ringing\") {\n _setCallState(call, call.roomId, \"stop_ringing\");\n pause(\"ringbackAudio\");\n } else if (newState === \"connected\") {\n _setCallState(call, call.roomId, \"connected\");\n pause(\"ringbackAudio\");\n }\n });\n}\n\nfunction _setCallState(call, roomId, status) {\n console.log(\"Call state in %s changed to %s (%s)\", roomId, status, call ? call.call_state : \"-\");\n calls[roomId] = call;\n\n if (status === \"ringing\") {\n play(\"ringAudio\");\n } else if (call && call.call_state === \"ringing\") {\n pause(\"ringAudio\");\n }\n\n if (call) {\n call.call_state = status;\n }\n _dispatcher2.default.dispatch({\n action: 'call_state',\n room_id: roomId,\n state: status\n });\n}\n\nfunction _showICEFallbackPrompt() {\n var cli = _MatrixClientPeg2.default.get();\n var QuestionDialog = _index2.default.getComponent(\"dialogs.QuestionDialog\");\n var code = function code(sub) {\n return React.createElement(\n 'code',\n null,\n sub\n );\n };\n _Modal2.default.createTrackedDialog('No TURN servers', '', QuestionDialog, {\n title: (0, _languageHandler._t)(\"Call failed due to misconfigured server\"),\n description: React.createElement(\n 'div',\n null,\n React.createElement(\n 'p',\n null,\n (0, _languageHandler._t)(\"Please ask the administrator of your homeserver \" + \"(%(homeserverDomain)s
) to configure a TURN server in \" + \"order for calls to work reliably.\", { homeserverDomain: cli.getDomain() }, { code: code })\n ),\n React.createElement(\n 'p',\n null,\n (0, _languageHandler._t)(\"Alternatively, you can try to use the public server at \" + \"turn.matrix.org
, but this will not be as reliable, and \" + \"it will share your IP address with that server. You can also manage \" + \"this in Settings.\", null, { code: code })\n )\n ),\n button: (0, _languageHandler._t)('Try using turn.matrix.org'),\n cancelButton: (0, _languageHandler._t)('OK'),\n onFinished: function onFinished(allow) {\n _SettingsStore2.default.setValue(\"fallbackICEServerAllowed\", null, _SettingsStore.SettingLevel.DEVICE, allow);\n cli.setFallbackICEServerAllowed(allow);\n }\n }, null, true);\n}\n\nfunction _onAction(payload) {\n function placeCall(newCall) {\n _setCallListeners(newCall);\n if (payload.type === 'voice') {\n newCall.placeVoiceCall();\n } else if (payload.type === 'video') {\n newCall.placeVideoCall(payload.remote_element, payload.local_element);\n } else if (payload.type === 'screensharing') {\n var screenCapErrorString = _PlatformPeg2.default.get().screenCaptureErrorString();\n if (screenCapErrorString) {\n _setCallState(undefined, newCall.roomId, \"ended\");\n console.log(\"Can't capture screen: \" + screenCapErrorString);\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Unable to capture screen', ErrorDialog, {\n title: (0, _languageHandler._t)('Unable to capture screen'),\n description: screenCapErrorString\n });\n return;\n }\n newCall.placeScreenSharingCall(payload.remote_element, payload.local_element);\n } else {\n console.error(\"Unknown conf call type: %s\", payload.type);\n }\n }\n\n switch (payload.action) {\n case 'place_call':\n {\n if (module.exports.getAnyActiveCall()) {\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Existing Call', ErrorDialog, {\n title: (0, _languageHandler._t)('Existing Call'),\n description: (0, _languageHandler._t)('You are already in a call.')\n });\n return; // don't allow >1 call to be placed.\n }\n\n // if the runtime env doesn't do VoIP, whine.\n if (!_MatrixClientPeg2.default.get().supportsVoip()) {\n var _ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'VoIP is unsupported', _ErrorDialog, {\n title: (0, _languageHandler._t)('VoIP is unsupported'),\n description: (0, _languageHandler._t)('You cannot place VoIP calls in this browser.')\n });\n return;\n }\n\n var room = _MatrixClientPeg2.default.get().getRoom(payload.room_id);\n if (!room) {\n console.error(\"Room %s does not exist.\", payload.room_id);\n return;\n }\n\n var members = room.getJoinedMembers();\n if (members.length <= 1) {\n var _ErrorDialog2 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Cannot place call with self', _ErrorDialog2, {\n description: (0, _languageHandler._t)('You cannot place a call with yourself.')\n });\n return;\n } else if (members.length === 2) {\n console.log(\"Place %s call in %s\", payload.type, payload.room_id);\n var call = _matrixJsSdk2.default.createNewMatrixCall(_MatrixClientPeg2.default.get(), payload.room_id);\n placeCall(call);\n } else {\n // > 2\n _dispatcher2.default.dispatch({\n action: \"place_conference_call\",\n room_id: payload.room_id,\n type: payload.type,\n remote_element: payload.remote_element,\n local_element: payload.local_element\n });\n }\n }\n break;\n case 'place_conference_call':\n console.log(\"Place conference call in %s\", payload.room_id);\n _startCallApp(payload.room_id, payload.type);\n break;\n case 'incoming_call':\n {\n if (module.exports.getAnyActiveCall()) {\n // ignore multiple incoming calls. in future, we may want a line-1/line-2 setup.\n // we avoid rejecting with \"busy\" in case the user wants to answer it on a different device.\n // in future we could signal a \"local busy\" as a warning to the caller.\n // see https://github.com/vector-im/vector-web/issues/1964\n return;\n }\n\n // if the runtime env doesn't do VoIP, stop here.\n if (!_MatrixClientPeg2.default.get().supportsVoip()) {\n return;\n }\n\n var _call = payload.call;\n _setCallListeners(_call);\n _setCallState(_call, _call.roomId, \"ringing\");\n }\n break;\n case 'hangup':\n if (!calls[payload.room_id]) {\n return; // no call to hangup\n }\n calls[payload.room_id].hangup();\n _setCallState(null, payload.room_id, \"ended\");\n break;\n case 'answer':\n if (!calls[payload.room_id]) {\n return; // no call to answer\n }\n calls[payload.room_id].answer();\n _setCallState(calls[payload.room_id], payload.room_id, \"connected\");\n _dispatcher2.default.dispatch({\n action: \"view_room\",\n room_id: payload.room_id\n });\n break;\n }\n}\n\nif (!global.mxCallHandler) {\n _dispatcher2.default.register(_onAction);\n}\n\nvar callHandler = {\n getCallForRoom: function getCallForRoom(roomId) {\n var call = module.exports.getCall(roomId);\n if (call) return call;\n\n if (ConferenceHandler) {\n call = ConferenceHandler.getConferenceCallForRoom(roomId);\n }\n if (call) return call;\n\n return null;\n },\n\n getCall: function getCall(roomId) {\n return calls[roomId] || null;\n },\n\n getAnyActiveCall: function getAnyActiveCall() {\n var roomsWithCalls = (0, _keys2.default)(calls);\n for (var i = 0; i < roomsWithCalls.length; i++) {\n if (calls[roomsWithCalls[i]] && calls[roomsWithCalls[i]].call_state !== \"ended\") {\n return calls[roomsWithCalls[i]];\n }\n }\n return null;\n },\n\n /**\n * The conference handler is a module that deals with implementation-specific\n * multi-party calling implementations. Riot passes in its own which creates\n * a one-to-one call with a freeswitch conference bridge. As of July 2018,\n * the de-facto way of conference calling is a Jitsi widget, so this is\n * deprecated. It reamins here for two reasons:\n * 1. So Riot still supports joining existing freeswitch conference calls\n * (but doesn't support creating them). After a transition period, we can\n * remove support for joining them too.\n * 2. To hide the one-to-one rooms that old-style conferencing creates. This\n * is much harder to remove: probably either we make Riot leave & forget these\n * rooms after we remove support for joining freeswitch conferences, or we\n * accept that random rooms with cryptic users will suddently appear for\n * anyone who's ever used conference calling, or we are stuck with this\n * code forever.\n *\n * @param {object} confHandler The conference handler object\n */\n setConferenceHandler: function setConferenceHandler(confHandler) {\n ConferenceHandler = confHandler;\n },\n\n getConferenceHandler: function getConferenceHandler() {\n return ConferenceHandler;\n }\n};\n// Only things in here which actually need to be global are the\n// calls list (done separately) and making sure we only register\n// with the dispatcher once (which uses this mechanism but checks\n// separately). This could be tidied up.\nif (global.mxCallHandler === undefined) {\n global.mxCallHandler = callHandler;\n}\n\nmodule.exports = global.mxCallHandler;\n//# sourceMappingURL=CallHandler.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _uniq2 = require('lodash/uniq');\n\nvar _uniq3 = _interopRequireDefault(_uniq2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Class that takes a Matrix Client and flips the m.direct map\n * so the operation of mapping a room ID to which user it's a DM\n * with can be performed efficiently.\n *\n * With 'start', this can also keep itself up to date over time.\n */\n/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar DMRoomMap = function () {\n function DMRoomMap(matrixClient) {\n (0, _classCallCheck3.default)(this, DMRoomMap);\n\n this.matrixClient = matrixClient;\n this.roomToUser = null;\n // see _onAccountData\n this._hasSentOutPatchDirectAccountDataPatch = false;\n\n // XXX: Force-bind the event handler method because it\n // doesn't call it with our object as the 'this'\n // (use a static property arrow function for this when we can)\n this._onAccountData = this._onAccountData.bind(this);\n\n var mDirectEvent = matrixClient.getAccountData('m.direct');\n this.mDirectEvent = mDirectEvent ? mDirectEvent.getContent() : {};\n this.userToRooms = null;\n }\n\n /**\n * Makes and returns a new shared instance that can then be accessed\n * with shared(). This returned instance is not automatically started.\n */\n\n\n (0, _createClass3.default)(DMRoomMap, [{\n key: 'start',\n value: function start() {\n this._populateRoomToUser();\n this.matrixClient.on(\"accountData\", this._onAccountData);\n }\n }, {\n key: 'stop',\n value: function stop() {\n this.matrixClient.removeListener(\"accountData\", this._onAccountData);\n }\n }, {\n key: '_onAccountData',\n value: function _onAccountData(ev) {\n if (ev.getType() == 'm.direct') {\n this.mDirectEvent = this.matrixClient.getAccountData('m.direct').getContent() || {};\n this.userToRooms = null;\n this.roomToUser = null;\n }\n }\n /**\n * some client bug somewhere is causing some DMs to be marked\n * with ourself, not the other user. Fix it by guessing the other user and\n * modifying userToRooms\n */\n\n }, {\n key: '_patchUpSelfDMs',\n value: function _patchUpSelfDMs(userToRooms) {\n var _this = this;\n\n var myUserId = this.matrixClient.getUserId();\n var selfRoomIds = userToRooms[myUserId];\n if (selfRoomIds) {\n // any self-chats that should not be self-chats?\n var guessedUserIdsThatChanged = selfRoomIds.map(function (roomId) {\n var room = _this.matrixClient.getRoom(roomId);\n if (room) {\n var userId = room.guessDMUserId();\n if (userId && userId !== myUserId) {\n return { userId: userId, roomId: roomId };\n }\n }\n }).filter(function (ids) {\n return !!ids;\n }); //filter out\n // these are actually all legit self-chats\n // bail out\n if (!guessedUserIdsThatChanged.length) {\n return false;\n }\n userToRooms[myUserId] = selfRoomIds.filter(function (roomId) {\n return !guessedUserIdsThatChanged.some(function (ids) {\n return ids.roomId === roomId;\n });\n });\n guessedUserIdsThatChanged.forEach(function (_ref) {\n var userId = _ref.userId,\n roomId = _ref.roomId;\n\n var roomIds = userToRooms[userId];\n if (!roomIds) {\n userToRooms[userId] = [roomId];\n } else {\n roomIds.push(roomId);\n userToRooms[userId] = (0, _uniq3.default)(roomIds);\n }\n });\n return true;\n }\n }\n }, {\n key: 'getDMRoomsForUserId',\n value: function getDMRoomsForUserId(userId) {\n // Here, we return the empty list if there are no rooms,\n // since the number of conversations you have with this user is zero.\n return this._getUserToRooms()[userId] || [];\n }\n }, {\n key: 'getUserIdForRoomId',\n value: function getUserIdForRoomId(roomId) {\n if (this.roomToUser == null) {\n // we lazily populate roomToUser so you can use\n // this class just to call getDMRoomsForUserId\n // which doesn't do very much, but is a fairly\n // convenient wrapper and there's no point\n // iterating through the map if getUserIdForRoomId()\n // is never called.\n this._populateRoomToUser();\n }\n // Here, we return undefined if the room is not in the map:\n // the room ID you gave is not a DM room for any user.\n if (this.roomToUser[roomId] === undefined) {\n // no entry? if the room is an invite, look for the is_direct hint.\n var room = this.matrixClient.getRoom(roomId);\n if (room) {\n return room.getDMInviter();\n }\n }\n return this.roomToUser[roomId];\n }\n }, {\n key: '_getUserToRooms',\n value: function _getUserToRooms() {\n if (!this.userToRooms) {\n var userToRooms = this.mDirectEvent;\n var myUserId = this.matrixClient.getUserId();\n var selfDMs = userToRooms[myUserId];\n if (selfDMs && selfDMs.length) {\n var neededPatching = this._patchUpSelfDMs(userToRooms);\n // to avoid multiple devices fighting to correct\n // the account data, only try to send the corrected\n // version once.\n console.warn('Invalid m.direct account data detected ' + '(self-chats that shouldn\\'t be), patching it up.');\n if (neededPatching && !this._hasSentOutPatchDirectAccountDataPatch) {\n this._hasSentOutPatchDirectAccountDataPatch = true;\n this.matrixClient.setAccountData('m.direct', userToRooms);\n }\n }\n this.userToRooms = userToRooms;\n }\n return this.userToRooms;\n }\n }, {\n key: '_populateRoomToUser',\n value: function _populateRoomToUser() {\n this.roomToUser = {};\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(this._getUserToRooms())), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var user = _step.value;\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (0, _getIterator3.default)(this.userToRooms[user]), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var roomId = _step2.value;\n\n this.roomToUser[roomId] = user;\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n }\n }], [{\n key: 'makeShared',\n value: function makeShared() {\n DMRoomMap._sharedInstance = new DMRoomMap(_MatrixClientPeg2.default.get());\n return DMRoomMap._sharedInstance;\n }\n\n /**\n * Returns a shared instance of the class\n * that uses the singleton matrix client\n * The shared instance must be started before use.\n */\n\n }, {\n key: 'shared',\n value: function shared() {\n return DMRoomMap._sharedInstance;\n }\n }]);\n return DMRoomMap;\n}();\n\nexports.default = DMRoomMap;\nmodule.exports = exports['default'];\n//# sourceMappingURL=DMRoomMap.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.formatCount = formatCount;\nexports.formatCryptoKey = formatCryptoKey;\nexports.hashCode = hashCode;\nexports.getUserNameColorClass = getUserNameColorClass;\nexports.formatCommaSeparatedList = formatCommaSeparatedList;\n\nvar _languageHandler = require(\"../languageHandler\");\n\n/**\n * formats numbers to fit into ~3 characters, suitable for badge counts\n * e.g: 999, 9.9K, 99K, 0.9M, 9.9M, 99M, 0.9B, 9.9B\n */\nfunction formatCount(count) {\n if (count < 1000) return count;\n if (count < 10000) return (count / 1000).toFixed(1) + \"K\";\n if (count < 100000) return (count / 1000).toFixed(0) + \"K\";\n if (count < 10000000) return (count / 1000000).toFixed(1) + \"M\";\n if (count < 100000000) return (count / 1000000).toFixed(0) + \"M\";\n return (count / 1000000000).toFixed(1) + \"B\"; // 10B is enough for anyone, right? :S\n}\n\n/**\n * format a key into groups of 4 characters, for easier visual inspection\n *\n * @param {string} key key to format\n *\n * @return {string}\n */\n/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction formatCryptoKey(key) {\n return key.match(/.{1,4}/g).join(\" \");\n}\n/**\n * calculates a numeric hash for a given string\n *\n * @param {string} str string to hash\n *\n * @return {number}\n */\nfunction hashCode(str) {\n var hash = 0;\n var i = void 0;\n var chr = void 0;\n if (str.length === 0) {\n return hash;\n }\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return Math.abs(hash);\n}\n\nfunction getUserNameColorClass(userId) {\n var colorNumber = hashCode(userId) % 8 + 1;\n return \"mx_Username_color\" + colorNumber;\n}\n\n/**\n * Constructs a written English string representing `items`, with an optional\n * limit on the number of items included in the result. If specified and if the\n * length of `items` is greater than the limit, the string \"and n others\" will\n * be appended onto the result. If `items` is empty, returns the empty string.\n * If there is only one item, return it.\n * @param {string[]} items the items to construct a string from.\n * @param {number?} itemLimit the number by which to limit the list.\n * @returns {string} a string constructed by joining `items` with a comma\n * between each item, but with the last item appended as \" and [lastItem]\".\n */\nfunction formatCommaSeparatedList(items, itemLimit) {\n var remaining = itemLimit === undefined ? 0 : Math.max(items.length - itemLimit, 0);\n if (items.length === 0) {\n return \"\";\n } else if (items.length === 1) {\n return items[0];\n } else if (remaining > 0) {\n items = items.slice(0, itemLimit);\n return (0, _languageHandler._t)(\"%(items)s and %(count)s others\", { items: items.join(', '), count: remaining });\n } else {\n var lastItem = items.pop();\n return (0, _languageHandler._t)(\"%(items)s and %(lastItem)s\", { items: items.join(', '), lastItem: lastItem });\n }\n}\n//# sourceMappingURL=FormattingUtils.js.map","'use strict';\nif (require('./_descriptors')) {\n var LIBRARY = require('./_library');\n var global = require('./_global');\n var fails = require('./_fails');\n var $export = require('./_export');\n var $typed = require('./_typed');\n var $buffer = require('./_typed-buffer');\n var ctx = require('./_ctx');\n var anInstance = require('./_an-instance');\n var propertyDesc = require('./_property-desc');\n var hide = require('./_hide');\n var redefineAll = require('./_redefine-all');\n var toInteger = require('./_to-integer');\n var toLength = require('./_to-length');\n var toIndex = require('./_to-index');\n var toAbsoluteIndex = require('./_to-absolute-index');\n var toPrimitive = require('./_to-primitive');\n var has = require('./_has');\n var classof = require('./_classof');\n var isObject = require('./_is-object');\n var toObject = require('./_to-object');\n var isArrayIter = require('./_is-array-iter');\n var create = require('./_object-create');\n var getPrototypeOf = require('./_object-gpo');\n var gOPN = require('./_object-gopn').f;\n var getIterFn = require('./core.get-iterator-method');\n var uid = require('./_uid');\n var wks = require('./_wks');\n var createArrayMethod = require('./_array-methods');\n var createArrayIncludes = require('./_array-includes');\n var speciesConstructor = require('./_species-constructor');\n var ArrayIterators = require('./es6.array.iterator');\n var Iterators = require('./_iterators');\n var $iterDetect = require('./_iter-detect');\n var setSpecies = require('./_set-species');\n var arrayFill = require('./_array-fill');\n var arrayCopyWithin = require('./_array-copy-within');\n var $DP = require('./_object-dp');\n var $GOPD = require('./_object-gopd');\n var dP = $DP.f;\n var gOPD = $GOPD.f;\n var RangeError = global.RangeError;\n var TypeError = global.TypeError;\n var Uint8Array = global.Uint8Array;\n var ARRAY_BUFFER = 'ArrayBuffer';\n var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;\n var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';\n var PROTOTYPE = 'prototype';\n var ArrayProto = Array[PROTOTYPE];\n var $ArrayBuffer = $buffer.ArrayBuffer;\n var $DataView = $buffer.DataView;\n var arrayForEach = createArrayMethod(0);\n var arrayFilter = createArrayMethod(2);\n var arraySome = createArrayMethod(3);\n var arrayEvery = createArrayMethod(4);\n var arrayFind = createArrayMethod(5);\n var arrayFindIndex = createArrayMethod(6);\n var arrayIncludes = createArrayIncludes(true);\n var arrayIndexOf = createArrayIncludes(false);\n var arrayValues = ArrayIterators.values;\n var arrayKeys = ArrayIterators.keys;\n var arrayEntries = ArrayIterators.entries;\n var arrayLastIndexOf = ArrayProto.lastIndexOf;\n var arrayReduce = ArrayProto.reduce;\n var arrayReduceRight = ArrayProto.reduceRight;\n var arrayJoin = ArrayProto.join;\n var arraySort = ArrayProto.sort;\n var arraySlice = ArrayProto.slice;\n var arrayToString = ArrayProto.toString;\n var arrayToLocaleString = ArrayProto.toLocaleString;\n var ITERATOR = wks('iterator');\n var TAG = wks('toStringTag');\n var TYPED_CONSTRUCTOR = uid('typed_constructor');\n var DEF_CONSTRUCTOR = uid('def_constructor');\n var ALL_CONSTRUCTORS = $typed.CONSTR;\n var TYPED_ARRAY = $typed.TYPED;\n var VIEW = $typed.VIEW;\n var WRONG_LENGTH = 'Wrong length!';\n\n var $map = createArrayMethod(1, function (O, length) {\n return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);\n });\n\n var LITTLE_ENDIAN = fails(function () {\n // eslint-disable-next-line no-undef\n return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\n });\n\n var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {\n new Uint8Array(1).set({});\n });\n\n var toOffset = function (it, BYTES) {\n var offset = toInteger(it);\n if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');\n return offset;\n };\n\n var validate = function (it) {\n if (isObject(it) && TYPED_ARRAY in it) return it;\n throw TypeError(it + ' is not a typed array!');\n };\n\n var allocate = function (C, length) {\n if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {\n throw TypeError('It is not a typed array constructor!');\n } return new C(length);\n };\n\n var speciesFromList = function (O, list) {\n return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);\n };\n\n var fromList = function (C, list) {\n var index = 0;\n var length = list.length;\n var result = allocate(C, length);\n while (length > index) result[index] = list[index++];\n return result;\n };\n\n var addGetter = function (it, key, internal) {\n dP(it, key, { get: function () { return this._d[internal]; } });\n };\n\n var $from = function from(source /* , mapfn, thisArg */) {\n var O = toObject(source);\n var aLen = arguments.length;\n var mapfn = aLen > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iterFn = getIterFn(O);\n var i, length, values, result, step, iterator;\n if (iterFn != undefined && !isArrayIter(iterFn)) {\n for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {\n values.push(step.value);\n } O = values;\n }\n if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);\n for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {\n result[i] = mapping ? mapfn(O[i], i) : O[i];\n }\n return result;\n };\n\n var $of = function of(/* ...items */) {\n var index = 0;\n var length = arguments.length;\n var result = allocate(this, length);\n while (length > index) result[index] = arguments[index++];\n return result;\n };\n\n // iOS Safari 6.x fails here\n var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });\n\n var $toLocaleString = function toLocaleString() {\n return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);\n };\n\n var proto = {\n copyWithin: function copyWithin(target, start /* , end */) {\n return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);\n },\n every: function every(callbackfn /* , thisArg */) {\n return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars\n return arrayFill.apply(validate(this), arguments);\n },\n filter: function filter(callbackfn /* , thisArg */) {\n return speciesFromList(this, arrayFilter(validate(this), callbackfn,\n arguments.length > 1 ? arguments[1] : undefined));\n },\n find: function find(predicate /* , thisArg */) {\n return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n },\n findIndex: function findIndex(predicate /* , thisArg */) {\n return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n },\n forEach: function forEach(callbackfn /* , thisArg */) {\n arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n indexOf: function indexOf(searchElement /* , fromIndex */) {\n return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n },\n includes: function includes(searchElement /* , fromIndex */) {\n return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n },\n join: function join(separator) { // eslint-disable-line no-unused-vars\n return arrayJoin.apply(validate(this), arguments);\n },\n lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars\n return arrayLastIndexOf.apply(validate(this), arguments);\n },\n map: function map(mapfn /* , thisArg */) {\n return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars\n return arrayReduce.apply(validate(this), arguments);\n },\n reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars\n return arrayReduceRight.apply(validate(this), arguments);\n },\n reverse: function reverse() {\n var that = this;\n var length = validate(that).length;\n var middle = Math.floor(length / 2);\n var index = 0;\n var value;\n while (index < middle) {\n value = that[index];\n that[index++] = that[--length];\n that[length] = value;\n } return that;\n },\n some: function some(callbackfn /* , thisArg */) {\n return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n sort: function sort(comparefn) {\n return arraySort.call(validate(this), comparefn);\n },\n subarray: function subarray(begin, end) {\n var O = validate(this);\n var length = O.length;\n var $begin = toAbsoluteIndex(begin, length);\n return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(\n O.buffer,\n O.byteOffset + $begin * O.BYTES_PER_ELEMENT,\n toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)\n );\n }\n };\n\n var $slice = function slice(start, end) {\n return speciesFromList(this, arraySlice.call(validate(this), start, end));\n };\n\n var $set = function set(arrayLike /* , offset */) {\n validate(this);\n var offset = toOffset(arguments[1], 1);\n var length = this.length;\n var src = toObject(arrayLike);\n var len = toLength(src.length);\n var index = 0;\n if (len + offset > length) throw RangeError(WRONG_LENGTH);\n while (index < len) this[offset + index] = src[index++];\n };\n\n var $iterators = {\n entries: function entries() {\n return arrayEntries.call(validate(this));\n },\n keys: function keys() {\n return arrayKeys.call(validate(this));\n },\n values: function values() {\n return arrayValues.call(validate(this));\n }\n };\n\n var isTAIndex = function (target, key) {\n return isObject(target)\n && target[TYPED_ARRAY]\n && typeof key != 'symbol'\n && key in target\n && String(+key) == String(key);\n };\n var $getDesc = function getOwnPropertyDescriptor(target, key) {\n return isTAIndex(target, key = toPrimitive(key, true))\n ? propertyDesc(2, target[key])\n : gOPD(target, key);\n };\n var $setDesc = function defineProperty(target, key, desc) {\n if (isTAIndex(target, key = toPrimitive(key, true))\n && isObject(desc)\n && has(desc, 'value')\n && !has(desc, 'get')\n && !has(desc, 'set')\n // TODO: add validation descriptor w/o calling accessors\n && !desc.configurable\n && (!has(desc, 'writable') || desc.writable)\n && (!has(desc, 'enumerable') || desc.enumerable)\n ) {\n target[key] = desc.value;\n return target;\n } return dP(target, key, desc);\n };\n\n if (!ALL_CONSTRUCTORS) {\n $GOPD.f = $getDesc;\n $DP.f = $setDesc;\n }\n\n $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {\n getOwnPropertyDescriptor: $getDesc,\n defineProperty: $setDesc\n });\n\n if (fails(function () { arrayToString.call({}); })) {\n arrayToString = arrayToLocaleString = function toString() {\n return arrayJoin.call(this);\n };\n }\n\n var $TypedArrayPrototype$ = redefineAll({}, proto);\n redefineAll($TypedArrayPrototype$, $iterators);\n hide($TypedArrayPrototype$, ITERATOR, $iterators.values);\n redefineAll($TypedArrayPrototype$, {\n slice: $slice,\n set: $set,\n constructor: function () { /* noop */ },\n toString: arrayToString,\n toLocaleString: $toLocaleString\n });\n addGetter($TypedArrayPrototype$, 'buffer', 'b');\n addGetter($TypedArrayPrototype$, 'byteOffset', 'o');\n addGetter($TypedArrayPrototype$, 'byteLength', 'l');\n addGetter($TypedArrayPrototype$, 'length', 'e');\n dP($TypedArrayPrototype$, TAG, {\n get: function () { return this[TYPED_ARRAY]; }\n });\n\n // eslint-disable-next-line max-statements\n module.exports = function (KEY, BYTES, wrapper, CLAMPED) {\n CLAMPED = !!CLAMPED;\n var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';\n var GETTER = 'get' + KEY;\n var SETTER = 'set' + KEY;\n var TypedArray = global[NAME];\n var Base = TypedArray || {};\n var TAC = TypedArray && getPrototypeOf(TypedArray);\n var FORCED = !TypedArray || !$typed.ABV;\n var O = {};\n var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];\n var getter = function (that, index) {\n var data = that._d;\n return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);\n };\n var setter = function (that, index, value) {\n var data = that._d;\n if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;\n data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);\n };\n var addElement = function (that, index) {\n dP(that, index, {\n get: function () {\n return getter(this, index);\n },\n set: function (value) {\n return setter(this, index, value);\n },\n enumerable: true\n });\n };\n if (FORCED) {\n TypedArray = wrapper(function (that, data, $offset, $length) {\n anInstance(that, TypedArray, NAME, '_d');\n var index = 0;\n var offset = 0;\n var buffer, byteLength, length, klass;\n if (!isObject(data)) {\n length = toIndex(data);\n byteLength = length * BYTES;\n buffer = new $ArrayBuffer(byteLength);\n } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {\n buffer = data;\n offset = toOffset($offset, BYTES);\n var $len = data.byteLength;\n if ($length === undefined) {\n if ($len % BYTES) throw RangeError(WRONG_LENGTH);\n byteLength = $len - offset;\n if (byteLength < 0) throw RangeError(WRONG_LENGTH);\n } else {\n byteLength = toLength($length) * BYTES;\n if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);\n }\n length = byteLength / BYTES;\n } else if (TYPED_ARRAY in data) {\n return fromList(TypedArray, data);\n } else {\n return $from.call(TypedArray, data);\n }\n hide(that, '_d', {\n b: buffer,\n o: offset,\n l: byteLength,\n e: length,\n v: new $DataView(buffer)\n });\n while (index < length) addElement(that, index++);\n });\n TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);\n hide(TypedArrayPrototype, 'constructor', TypedArray);\n } else if (!fails(function () {\n TypedArray(1);\n }) || !fails(function () {\n new TypedArray(-1); // eslint-disable-line no-new\n }) || !$iterDetect(function (iter) {\n new TypedArray(); // eslint-disable-line no-new\n new TypedArray(null); // eslint-disable-line no-new\n new TypedArray(1.5); // eslint-disable-line no-new\n new TypedArray(iter); // eslint-disable-line no-new\n }, true)) {\n TypedArray = wrapper(function (that, data, $offset, $length) {\n anInstance(that, TypedArray, NAME);\n var klass;\n // `ws` module bug, temporarily remove validation length for Uint8Array\n // https://github.com/websockets/ws/pull/645\n if (!isObject(data)) return new Base(toIndex(data));\n if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {\n return $length !== undefined\n ? new Base(data, toOffset($offset, BYTES), $length)\n : $offset !== undefined\n ? new Base(data, toOffset($offset, BYTES))\n : new Base(data);\n }\n if (TYPED_ARRAY in data) return fromList(TypedArray, data);\n return $from.call(TypedArray, data);\n });\n arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {\n if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);\n });\n TypedArray[PROTOTYPE] = TypedArrayPrototype;\n if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;\n }\n var $nativeIterator = TypedArrayPrototype[ITERATOR];\n var CORRECT_ITER_NAME = !!$nativeIterator\n && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);\n var $iterator = $iterators.values;\n hide(TypedArray, TYPED_CONSTRUCTOR, true);\n hide(TypedArrayPrototype, TYPED_ARRAY, NAME);\n hide(TypedArrayPrototype, VIEW, true);\n hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);\n\n if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {\n dP(TypedArrayPrototype, TAG, {\n get: function () { return NAME; }\n });\n }\n\n O[NAME] = TypedArray;\n\n $export($export.G + $export.W + $export.F * (TypedArray != Base), O);\n\n $export($export.S, NAME, {\n BYTES_PER_ELEMENT: BYTES\n });\n\n $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {\n from: $from,\n of: $of\n });\n\n if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);\n\n $export($export.P, NAME, proto);\n\n setSpecies(NAME);\n\n $export($export.P + $export.F * FORCED_SET, NAME, { set: $set });\n\n $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);\n\n if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;\n\n $export($export.P + $export.F * fails(function () {\n new TypedArray(1).slice();\n }), NAME, { slice: $slice });\n\n $export($export.P + $export.F * (fails(function () {\n return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();\n }) || !fails(function () {\n TypedArrayPrototype.toLocaleString.call([1, 2]);\n })), NAME, { toLocaleString: $toLocaleString });\n\n Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;\n if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);\n };\n} else module.exports = function () { /* empty */ };\n","var Map = require('./es6.map');\nvar $export = require('./_export');\nvar shared = require('./_shared')('metadata');\nvar store = shared.store || (shared.store = new (require('./es6.weak-map'))());\n\nvar getOrCreateMetadataMap = function (target, targetKey, create) {\n var targetMetadata = store.get(target);\n if (!targetMetadata) {\n if (!create) return undefined;\n store.set(target, targetMetadata = new Map());\n }\n var keyMetadata = targetMetadata.get(targetKey);\n if (!keyMetadata) {\n if (!create) return undefined;\n targetMetadata.set(targetKey, keyMetadata = new Map());\n } return keyMetadata;\n};\nvar ordinaryHasOwnMetadata = function (MetadataKey, O, P) {\n var metadataMap = getOrCreateMetadataMap(O, P, false);\n return metadataMap === undefined ? false : metadataMap.has(MetadataKey);\n};\nvar ordinaryGetOwnMetadata = function (MetadataKey, O, P) {\n var metadataMap = getOrCreateMetadataMap(O, P, false);\n return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);\n};\nvar ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {\n getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);\n};\nvar ordinaryOwnMetadataKeys = function (target, targetKey) {\n var metadataMap = getOrCreateMetadataMap(target, targetKey, false);\n var keys = [];\n if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });\n return keys;\n};\nvar toMetaKey = function (it) {\n return it === undefined || typeof it == 'symbol' ? it : String(it);\n};\nvar exp = function (O) {\n $export($export.S, 'Reflect', O);\n};\n\nmodule.exports = {\n store: store,\n map: getOrCreateMetadataMap,\n has: ordinaryHasOwnMetadata,\n get: ordinaryGetOwnMetadata,\n set: ordinaryDefineOwnMetadata,\n keys: ordinaryOwnMetadataKeys,\n key: toMetaKey,\n exp: exp\n};\n","'use strict';\nvar LIBRARY = require('./_library');\nvar $export = require('./_export');\nvar redefine = require('./_redefine');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar $iterCreate = require('./_iter-create');\nvar setToStringTag = require('./_set-to-string-tag');\nvar getPrototypeOf = require('./_object-gpo');\nvar ITERATOR = require('./_wks')('iterator');\nvar BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`\nvar FF_ITERATOR = '@@iterator';\nvar KEYS = 'keys';\nvar VALUES = 'values';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {\n $iterCreate(Constructor, NAME, next);\n var getMethod = function (kind) {\n if (!BUGGY && kind in proto) return proto[kind];\n switch (kind) {\n case KEYS: return function keys() { return new Constructor(this, kind); };\n case VALUES: return function values() { return new Constructor(this, kind); };\n } return function entries() { return new Constructor(this, kind); };\n };\n var TAG = NAME + ' Iterator';\n var DEF_VALUES = DEFAULT == VALUES;\n var VALUES_BUG = false;\n var proto = Base.prototype;\n var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];\n var $default = $native || getMethod(DEFAULT);\n var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;\n var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;\n var methods, key, IteratorPrototype;\n // Fix native\n if ($anyNative) {\n IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));\n if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {\n // Set @@toStringTag to native iterators\n setToStringTag(IteratorPrototype, TAG, true);\n // fix for some old engines\n if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);\n }\n }\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEF_VALUES && $native && $native.name !== VALUES) {\n VALUES_BUG = true;\n $default = function values() { return $native.call(this); };\n }\n // Define iterator\n if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {\n hide(proto, ITERATOR, $default);\n }\n // Plug for library\n Iterators[NAME] = $default;\n Iterators[TAG] = returnThis;\n if (DEFAULT) {\n methods = {\n values: DEF_VALUES ? $default : getMethod(VALUES),\n keys: IS_SET ? $default : getMethod(KEYS),\n entries: $entries\n };\n if (FORCED) for (key in methods) {\n if (!(key in proto)) redefine(proto, key, methods[key]);\n } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);\n }\n return methods;\n};\n","var isObject = require('./_is-object');\nvar document = require('./_global').document;\n// typeof document.createElement is 'object' in old IE\nvar is = isObject(document) && isObject(document.createElement);\nmodule.exports = function (it) {\n return is ? document.createElement(it) : {};\n};\n","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","// 7.1.15 ToLength\nvar toInteger = require('./_to-integer');\nvar min = Math.min;\nmodule.exports = function (it) {\n return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991\n};\n","// getting tag from 19.1.3.6 Object.prototype.toString()\nvar cof = require('./_cof');\nvar TAG = require('./_wks')('toStringTag');\n// ES3 wrong here\nvar ARG = cof(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (e) { /* empty */ }\n};\n\nmodule.exports = function (it) {\n var O, T, B;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T\n // builtinTag case\n : ARG ? cof(O)\n // ES3 arguments fallback\n : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;\n};\n","exports.f = {}.propertyIsEnumerable;\n","\"use strict\";\n\nexports.__esModule = true;\n\nvar _getPrototypeOf = require(\"../core-js/object/get-prototype-of\");\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _getOwnPropertyDescriptor = require(\"../core-js/object/get-own-property-descriptor\");\n\nvar _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n var desc = (0, _getOwnPropertyDescriptor2.default)(object, property);\n\n if (desc === undefined) {\n var parent = (0, _getPrototypeOf2.default)(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n};","'use strict';\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _PlatformPeg = require('./PlatformPeg');\n\nvar _PlatformPeg2 = _interopRequireDefault(_PlatformPeg);\n\nvar _TextForEvent = require('./TextForEvent');\n\nvar _TextForEvent2 = _interopRequireDefault(_TextForEvent);\n\nvar _Analytics = require('./Analytics');\n\nvar _Analytics2 = _interopRequireDefault(_Analytics);\n\nvar _Avatar = require('./Avatar');\n\nvar _Avatar2 = _interopRequireDefault(_Avatar);\n\nvar _dispatcher = require('./dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _index = require('./index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('./languageHandler');\n\nvar _Modal = require('./Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _SettingsStore = require('./settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\n * Dispatches:\n * {\n * action: \"notifier_enabled\",\n * value: boolean\n * }\n */\n\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar MAX_PENDING_ENCRYPTED = 20;\n\nvar Notifier = {\n notifsByRoom: {},\n\n // A list of event IDs that we've received but need to wait until\n // they're decrypted until we decide whether to notify for them\n // or not\n pendingEncryptedEventIds: [],\n\n notificationMessageForEvent: function notificationMessageForEvent(ev) {\n return _TextForEvent2.default.textForEvent(ev);\n },\n\n _displayPopupNotification: function _displayPopupNotification(ev, room) {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) {\n return;\n }\n if (!plaf.supportsNotifications() || !plaf.maySendNotifications()) {\n return;\n }\n if (global.document.hasFocus()) {\n return;\n }\n\n var msg = this.notificationMessageForEvent(ev);\n if (!msg) return;\n\n var title = void 0;\n if (!ev.sender || room.name === ev.sender.name) {\n title = room.name;\n // notificationMessageForEvent includes sender,\n // but we already have the sender here\n if (ev.getContent().body) msg = ev.getContent().body;\n } else if (ev.getType() === 'm.room.member') {\n // context is all in the message here, we don't need\n // to display sender info\n title = room.name;\n } else if (ev.sender) {\n title = ev.sender.name + \" (\" + room.name + \")\";\n // notificationMessageForEvent includes sender,\n // but we've just out sender in the title\n if (ev.getContent().body) msg = ev.getContent().body;\n }\n\n if (!this.isBodyEnabled()) {\n msg = '';\n }\n\n var avatarUrl = null;\n if (ev.sender && !_SettingsStore2.default.getValue(\"lowBandwidth\")) {\n avatarUrl = _Avatar2.default.avatarUrlForMember(ev.sender, 40, 40, 'crop');\n }\n\n var notif = plaf.displayNotification(title, msg, avatarUrl, room);\n\n // if displayNotification returns non-null, the platform supports\n // clearing notifications later, so keep track of this.\n if (notif) {\n if (this.notifsByRoom[ev.getRoomId()] === undefined) this.notifsByRoom[ev.getRoomId()] = [];\n this.notifsByRoom[ev.getRoomId()].push(notif);\n }\n },\n\n getSoundForRoom: function () {\n var _ref = (0, _bluebird.method)(function (roomId) {\n // We do no caching here because the SDK caches setting\n // and the browser will cache the sound.\n var content = _SettingsStore2.default.getValue(\"notificationSound\", roomId);\n if (!content) {\n return null;\n }\n\n if (!content.url) {\n console.warn(roomId + ' has custom notification sound event, but no url key');\n return null;\n }\n\n if (!content.url.startsWith(\"mxc://\")) {\n console.warn(roomId + ' has custom notification sound event, but url is not a mxc url');\n return null;\n }\n\n // Ideally in here we could use MSC1310 to detect the type of file, and reject it.\n\n return {\n url: _MatrixClientPeg2.default.get().mxcUrlToHttp(content.url),\n name: content.name,\n type: content.type,\n size: content.size\n };\n });\n\n function getSoundForRoom(_x) {\n return _ref.apply(this, arguments);\n }\n\n return getSoundForRoom;\n }(),\n\n _playAudioNotification: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(ev, room) {\n var sound, selector, audioElement;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return (0, _bluebird.resolve)(this.getSoundForRoom(room.roomId));\n\n case 2:\n sound = _context.sent;\n\n console.log('Got sound ' + (sound && sound.name || \"default\") + ' for ' + room.roomId);\n\n _context.prev = 4;\n selector = document.querySelector(sound ? 'audio[src=\\'' + sound.url + '\\']' : \"#messageAudio\");\n audioElement = selector;\n\n if (selector) {\n _context.next = 14;\n break;\n }\n\n if (sound) {\n _context.next = 11;\n break;\n }\n\n console.error(\"No audio element or sound to play for notification\");\n return _context.abrupt('return');\n\n case 11:\n audioElement = new Audio(sound.url);\n if (sound.type) {\n audioElement.type = sound.type;\n }\n document.body.appendChild(audioElement);\n\n case 14:\n audioElement.play();\n _context.next = 20;\n break;\n\n case 17:\n _context.prev = 17;\n _context.t0 = _context['catch'](4);\n\n console.warn(\"Caught error when trying to fetch room notification sound:\", _context.t0);\n\n case 20:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[4, 17]]);\n }));\n\n function _playAudioNotification(_x2, _x3) {\n return _ref2.apply(this, arguments);\n }\n\n return _playAudioNotification;\n }(),\n\n start: function start() {\n this.boundOnEvent = this.onEvent.bind(this);\n this.boundOnSyncStateChange = this.onSyncStateChange.bind(this);\n this.boundOnRoomReceipt = this.onRoomReceipt.bind(this);\n this.boundOnEventDecrypted = this.onEventDecrypted.bind(this);\n _MatrixClientPeg2.default.get().on('event', this.boundOnEvent);\n _MatrixClientPeg2.default.get().on('Room.receipt', this.boundOnRoomReceipt);\n _MatrixClientPeg2.default.get().on('Event.decrypted', this.boundOnEventDecrypted);\n _MatrixClientPeg2.default.get().on(\"sync\", this.boundOnSyncStateChange);\n this.toolbarHidden = false;\n this.isSyncing = false;\n },\n\n stop: function stop() {\n if (_MatrixClientPeg2.default.get() && this.boundOnRoomTimeline) {\n _MatrixClientPeg2.default.get().removeListener('Event', this.boundOnEvent);\n _MatrixClientPeg2.default.get().removeListener('Room.receipt', this.boundOnRoomReceipt);\n _MatrixClientPeg2.default.get().removeListener('Event.decrypted', this.boundOnEventDecrypted);\n _MatrixClientPeg2.default.get().removeListener('sync', this.boundOnSyncStateChange);\n }\n this.isSyncing = false;\n },\n\n supportsDesktopNotifications: function supportsDesktopNotifications() {\n var plaf = _PlatformPeg2.default.get();\n return plaf && plaf.supportsNotifications();\n },\n\n setEnabled: function setEnabled(enable, callback) {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return;\n\n // Dev note: We don't set the \"notificationsEnabled\" setting to true here because it is a\n // calculated value. It is determined based upon whether or not the master rule is enabled\n // and other flags. Setting it here would cause a circular reference.\n\n _Analytics2.default.trackEvent('Notifier', 'Set Enabled', enable);\n\n // make sure that we persist the current setting audio_enabled setting\n // before changing anything\n if (_SettingsStore2.default.isLevelSupported(_SettingsStore.SettingLevel.DEVICE)) {\n _SettingsStore2.default.setValue(\"audioNotificationsEnabled\", null, _SettingsStore.SettingLevel.DEVICE, this.isEnabled());\n }\n\n if (enable) {\n // Attempt to get permission from user\n plaf.requestNotificationPermission().done(function (result) {\n if (result !== 'granted') {\n // The permission request was dismissed or denied\n // TODO: Support alternative branding in messaging\n var description = result === 'denied' ? (0, _languageHandler._t)('Riot does not have permission to send you notifications - ' + 'please check your browser settings') : (0, _languageHandler._t)('Riot was not given permission to send notifications - please try again');\n var ErrorDialog = _index2.default.getComponent('dialogs.ErrorDialog');\n _Modal2.default.createTrackedDialog('Unable to enable Notifications', result, ErrorDialog, {\n title: (0, _languageHandler._t)('Unable to enable Notifications'),\n description: description\n });\n return;\n }\n\n if (callback) callback();\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: true\n });\n });\n } else {\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: false\n });\n }\n // set the notifications_hidden flag, as the user has knowingly interacted\n // with the setting we shouldn't nag them any further\n this.setToolbarHidden(true);\n },\n\n isEnabled: function isEnabled() {\n return this.isPossible() && _SettingsStore2.default.getValue(\"notificationsEnabled\");\n },\n\n isPossible: function isPossible() {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return false;\n if (!plaf.supportsNotifications()) return false;\n if (!plaf.maySendNotifications()) return false;\n\n return true; // possible, but not necessarily enabled\n },\n\n isBodyEnabled: function isBodyEnabled() {\n return this.isEnabled() && _SettingsStore2.default.getValue(\"notificationBodyEnabled\");\n },\n\n isAudioEnabled: function isAudioEnabled() {\n return this.isEnabled() && _SettingsStore2.default.getValue(\"audioNotificationsEnabled\");\n },\n\n setToolbarHidden: function setToolbarHidden(hidden) {\n var persistent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n this.toolbarHidden = hidden;\n\n _Analytics2.default.trackEvent('Notifier', 'Set Toolbar Hidden', hidden);\n\n // XXX: why are we dispatching this here?\n // this is nothing to do with notifier_enabled\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: this.isEnabled()\n });\n\n // update the info to localStorage for persistent settings\n if (persistent && global.localStorage) {\n global.localStorage.setItem(\"notifications_hidden\", hidden);\n }\n },\n\n shouldShowToolbar: function shouldShowToolbar() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n return false;\n }\n var isGuest = client.isGuest();\n return !isGuest && this.supportsDesktopNotifications() && !this.isEnabled() && !this._isToolbarHidden();\n },\n\n _isToolbarHidden: function _isToolbarHidden() {\n // Check localStorage for any such meta data\n if (global.localStorage) {\n return global.localStorage.getItem(\"notifications_hidden\") === \"true\";\n }\n\n return this.toolbarHidden;\n },\n\n onSyncStateChange: function onSyncStateChange(state) {\n if (state === \"SYNCING\") {\n this.isSyncing = true;\n } else if (state === \"STOPPED\" || state === \"ERROR\") {\n this.isSyncing = false;\n }\n },\n\n onEvent: function onEvent(ev) {\n if (!this.isSyncing) return; // don't alert for any messages initially\n if (ev.sender && ev.sender.userId === _MatrixClientPeg2.default.get().credentials.userId) return;\n\n // If it's an encrypted event and the type is still 'm.room.encrypted',\n // it hasn't yet been decrypted, so wait until it is.\n if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {\n this.pendingEncryptedEventIds.push(ev.getId());\n // don't let the list fill up indefinitely\n while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {\n this.pendingEncryptedEventIds.shift();\n }\n return;\n }\n\n this._evaluateEvent(ev);\n },\n\n onEventDecrypted: function onEventDecrypted(ev) {\n // 'decrypted' means the decryption process has finished: it may have failed,\n // in which case it might decrypt soon if the keys arrive\n if (ev.isDecryptionFailure()) return;\n\n var idx = this.pendingEncryptedEventIds.indexOf(ev.getId());\n if (idx === -1) return;\n\n this.pendingEncryptedEventIds.splice(idx, 1);\n this._evaluateEvent(ev);\n },\n\n onRoomReceipt: function onRoomReceipt(ev, room) {\n if (room.getUnreadNotificationCount() === 0) {\n // ideally we would clear each notification when it was read,\n // but we have no way, given a read receipt, to know whether\n // the receipt comes before or after an event, so we can't\n // do this. Instead, clear all notifications for a room once\n // there are no notifs left in that room., which is not quite\n // as good but it's something.\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return;\n if (this.notifsByRoom[room.roomId] === undefined) return;\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(this.notifsByRoom[room.roomId]), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var notif = _step.value;\n\n plaf.clearNotification(notif);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n delete this.notifsByRoom[room.roomId];\n }\n },\n\n _evaluateEvent: function _evaluateEvent(ev) {\n var room = _MatrixClientPeg2.default.get().getRoom(ev.getRoomId());\n var actions = _MatrixClientPeg2.default.get().getPushActionsForEvent(ev);\n if (actions && actions.notify) {\n if (this.isEnabled()) {\n this._displayPopupNotification(ev, room);\n }\n if (actions.tweaks.sound && this.isAudioEnabled()) {\n _PlatformPeg2.default.get().loudNotification(ev, room);\n this._playAudioNotification(ev, room);\n }\n }\n }\n};\n\nif (!global.mxNotifier) {\n global.mxNotifier = Notifier;\n}\n\nmodule.exports = global.mxNotifier;\n//# sourceMappingURL=Notifier.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _extends2 = require('babel-runtime/helpers/extends');\n\nvar _extends3 = _interopRequireDefault(_extends2);\n\nvar _setImmediate2 = require('babel-runtime/core-js/set-immediate');\n\nvar _setImmediate3 = _interopRequireDefault(_setImmediate2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nexports.createMenu = createMenu;\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _reactDom = require('react-dom');\n\nvar _reactDom2 = _interopRequireDefault(_reactDom);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Accessibility = require('../../utils/Accessibility');\n\nvar _Keyboard = require('../../Keyboard');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// Shamelessly ripped off Modal.js. There's probably a better way\n// of doing reusable widgets like dialog boxes & menus where we go and\n// pass in a custom control as the actual body.\n\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar ContextualMenuContainerId = \"mx_ContextualMenu_Container\";\n\nfunction getOrCreateContainer() {\n var container = document.getElementById(ContextualMenuContainerId);\n\n if (!container) {\n container = document.createElement(\"div\");\n container.id = ContextualMenuContainerId;\n document.body.appendChild(container);\n }\n\n return container;\n}\n\nvar ContextualMenu = function (_React$Component) {\n (0, _inherits3.default)(ContextualMenu, _React$Component);\n\n function ContextualMenu() {\n (0, _classCallCheck3.default)(this, ContextualMenu);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (ContextualMenu.__proto__ || (0, _getPrototypeOf2.default)(ContextualMenu)).call(this));\n\n _this._onKeyDown = function (ev) {\n if (ev.keyCode === _Keyboard.KeyCode.ESCAPE) {\n ev.stopPropagation();\n ev.preventDefault();\n _this.props.closeMenu();\n }\n };\n\n _this.state = {\n contextMenuRect: null\n };\n\n _this.onContextMenu = _this.onContextMenu.bind(_this);\n _this.collectContextMenuRect = _this.collectContextMenuRect.bind(_this);\n return _this;\n }\n\n (0, _createClass3.default)(ContextualMenu, [{\n key: 'collectContextMenuRect',\n value: function collectContextMenuRect(element) {\n // We don't need to clean up when unmounting, so ignore\n if (!element) return;\n\n // For screen readers to find the thing\n (0, _Accessibility.focusCapturedRef)(element);\n\n this.setState({\n contextMenuRect: element.getBoundingClientRect()\n });\n }\n }, {\n key: 'onContextMenu',\n value: function onContextMenu(e) {\n if (this.props.closeMenu) {\n this.props.closeMenu();\n\n e.preventDefault();\n var x = e.clientX;\n var y = e.clientY;\n\n // XXX: This isn't pretty but the only way to allow opening a different context menu on right click whilst\n // a context menu and its click-guard are up without completely rewriting how the context menus work.\n (0, _setImmediate3.default)(function () {\n var clickEvent = document.createEvent('MouseEvents');\n clickEvent.initMouseEvent('contextmenu', true, true, window, 0, 0, 0, x, y, false, false, false, false, 0, null);\n document.elementFromPoint(x, y).dispatchEvent(clickEvent);\n });\n }\n }\n }, {\n key: 'render',\n value: function render() {\n var position = {};\n var chevronFace = null;\n var props = this.props;\n\n if (props.top) {\n position.top = props.top;\n } else {\n position.bottom = props.bottom;\n }\n\n if (props.left) {\n position.left = props.left;\n chevronFace = 'left';\n } else {\n position.right = props.right;\n chevronFace = 'right';\n }\n\n var contextMenuRect = this.state.contextMenuRect || null;\n var padding = 10;\n\n var chevronOffset = {};\n if (props.chevronFace) {\n chevronFace = props.chevronFace;\n }\n var hasChevron = chevronFace && chevronFace !== \"none\";\n\n if (chevronFace === 'top' || chevronFace === 'bottom') {\n chevronOffset.left = props.chevronOffset;\n } else {\n var target = position.top;\n\n // By default, no adjustment is made\n var adjusted = target;\n\n // If we know the dimensions of the context menu, adjust its position\n // such that it does not leave the (padded) window.\n if (contextMenuRect) {\n adjusted = Math.min(position.top, document.body.clientHeight - contextMenuRect.height - padding);\n }\n\n position.top = adjusted;\n chevronOffset.top = Math.max(props.chevronOffset, props.chevronOffset + target - adjusted);\n }\n\n var chevron = hasChevron ? _react2.default.createElement('div', { style: chevronOffset, className: \"mx_ContextualMenu_chevron_\" + chevronFace }) : undefined;\n var className = 'mx_ContextualMenu_wrapper';\n\n var menuClasses = (0, _classnames2.default)({\n 'mx_ContextualMenu': true,\n 'mx_HiddenFocusable': true, // hide browser outline\n 'mx_ContextualMenu_left': !hasChevron && position.left,\n 'mx_ContextualMenu_right': !hasChevron && position.right,\n 'mx_ContextualMenu_top': !hasChevron && position.top,\n 'mx_ContextualMenu_bottom': !hasChevron && position.bottom,\n 'mx_ContextualMenu_withChevron_left': chevronFace === 'left',\n 'mx_ContextualMenu_withChevron_right': chevronFace === 'right',\n 'mx_ContextualMenu_withChevron_top': chevronFace === 'top',\n 'mx_ContextualMenu_withChevron_bottom': chevronFace === 'bottom'\n });\n\n var menuStyle = {};\n if (props.menuWidth) {\n menuStyle.width = props.menuWidth;\n }\n\n if (props.menuHeight) {\n menuStyle.height = props.menuHeight;\n }\n\n if (!isNaN(Number(props.menuPaddingTop))) {\n menuStyle[\"paddingTop\"] = props.menuPaddingTop;\n }\n if (!isNaN(Number(props.menuPaddingLeft))) {\n menuStyle[\"paddingLeft\"] = props.menuPaddingLeft;\n }\n if (!isNaN(Number(props.menuPaddingBottom))) {\n menuStyle[\"paddingBottom\"] = props.menuPaddingBottom;\n }\n if (!isNaN(Number(props.menuPaddingRight))) {\n menuStyle[\"paddingRight\"] = props.menuPaddingRight;\n }\n\n var wrapperStyle = {};\n if (!isNaN(Number(props.zIndex))) {\n menuStyle[\"zIndex\"] = props.zIndex + 1;\n wrapperStyle[\"zIndex\"] = props.zIndex;\n }\n\n var ElementClass = props.elementClass;\n\n // FIXME: If a menu uses getDefaultProps it clobbers the onFinished\n // property set here so you can't close the menu from a button click!\n return _react2.default.createElement(\n 'div',\n { className: className, style: (0, _extends3.default)({}, position, wrapperStyle), onKeyDown: this._onKeyDown },\n _react2.default.createElement(\n 'div',\n { className: menuClasses, style: menuStyle, ref: this.collectContextMenuRect, tabIndex: 0 },\n chevron,\n _react2.default.createElement(ElementClass, (0, _extends3.default)({}, props, { onFinished: props.closeMenu, onResize: props.windowResize }))\n ),\n props.hasBackground && _react2.default.createElement('div', { className: 'mx_ContextualMenu_background', style: wrapperStyle,\n onClick: props.closeMenu, onContextMenu: this.onContextMenu })\n );\n }\n }]);\n return ContextualMenu;\n}(_react2.default.Component);\n\nexports.default = ContextualMenu;\nfunction createMenu(ElementClass, props) {\n var hasBackground = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n\n var closeMenu = function closeMenu() {\n _reactDom2.default.unmountComponentAtNode(getOrCreateContainer());\n\n if (props && props.onFinished) {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n props.onFinished.apply(null, args);\n }\n };\n\n // We only reference closeMenu once per call to createMenu\n var menu = _react2.default.createElement(ContextualMenu, (0, _extends3.default)({\n hasBackground: hasBackground\n }, props, {\n elementClass: ElementClass,\n closeMenu: closeMenu // eslint-disable-line react/jsx-no-bind\n , windowResize: closeMenu // eslint-disable-line react/jsx-no-bind\n }));\n\n _reactDom2.default.render(menu, getOrCreateContainer());\n\n return { close: closeMenu };\n}\n//# sourceMappingURL=ContextualMenu.js.map","\"use strict\";\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\n/**\n * Colors.\n */\n\nexports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n } // Internet Explorer and Edge do not support colors.\n\n\n if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n } // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\n\n return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773\n typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/);\n}\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\n\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);\n\n if (!this.useColors) {\n return;\n }\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit'); // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function (match) {\n if (match === '%%') {\n return;\n }\n\n index++;\n\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\n\nfunction log() {\n var _console;\n\n // This hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return (typeof console === \"undefined\" ? \"undefined\" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);\n}\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\n\nfunction save(namespaces) {\n try {\n if (namespaces) {\n exports.storage.setItem('debug', namespaces);\n } else {\n exports.storage.removeItem('debug');\n }\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\n\nfunction load() {\n var r;\n\n try {\n r = exports.storage.getItem('debug');\n } catch (error) {} // Swallow\n // XXX (@Qix-) should we be logging these?\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\n\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\n\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nmodule.exports = require('./common')(exports);\nvar formatters = module.exports.formatters;\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n try {\n return JSON.stringify(v);\n } catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n};\n\n","module.exports = false;\n","var META = require('./_uid')('meta');\nvar isObject = require('./_is-object');\nvar has = require('./_has');\nvar setDesc = require('./_object-dp').f;\nvar id = 0;\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\nvar FREEZE = !require('./_fails')(function () {\n return isExtensible(Object.preventExtensions({}));\n});\nvar setMeta = function (it) {\n setDesc(it, META, { value: {\n i: 'O' + ++id, // object ID\n w: {} // weak collections IDs\n } });\n};\nvar fastKey = function (it, create) {\n // return primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMeta(it);\n // return object ID\n } return it[META].i;\n};\nvar getWeak = function (it, create) {\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMeta(it);\n // return hash weak collections IDs\n } return it[META].w;\n};\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);\n return it;\n};\nvar meta = module.exports = {\n KEY: META,\n NEED: false,\n fastKey: fastKey,\n getWeak: getWeak,\n onFreeze: onFreeze\n};\n","// 22.1.3.31 Array.prototype[@@unscopables]\nvar UNSCOPABLES = require('./_wks')('unscopables');\nvar ArrayProto = Array.prototype;\nif (ArrayProto[UNSCOPABLES] == undefined) require('./_hide')(ArrayProto, UNSCOPABLES, {});\nmodule.exports = function (key) {\n ArrayProto[UNSCOPABLES][key] = true;\n};\n","var classof = require('./_classof');\nvar ITERATOR = require('./_wks')('iterator');\nvar Iterators = require('./_iterators');\nmodule.exports = require('./_core').getIteratorMethod = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","var META = require('./_uid')('meta');\nvar isObject = require('./_is-object');\nvar has = require('./_has');\nvar setDesc = require('./_object-dp').f;\nvar id = 0;\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\nvar FREEZE = !require('./_fails')(function () {\n return isExtensible(Object.preventExtensions({}));\n});\nvar setMeta = function (it) {\n setDesc(it, META, { value: {\n i: 'O' + ++id, // object ID\n w: {} // weak collections IDs\n } });\n};\nvar fastKey = function (it, create) {\n // return primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMeta(it);\n // return object ID\n } return it[META].i;\n};\nvar getWeak = function (it, create) {\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMeta(it);\n // return hash weak collections IDs\n } return it[META].w;\n};\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);\n return it;\n};\nvar meta = module.exports = {\n KEY: META,\n NEED: false,\n fastKey: fastKey,\n getWeak: getWeak,\n onFreeze: onFreeze\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule invariant\n */\n\n\"use strict\";\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function (condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error('Invariant Violation: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _events = require('events');\n\nvar _events2 = _interopRequireDefault(_events);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar BULK_REQUEST_DEBOUNCE_MS = 200;\n\n// Does the server support groups? Assume yes until we receive M_UNRECOGNIZED.\n// If true, flair can function and we should keep sending requests for groups and avatars.\nvar _groupSupport = true;\n\nvar USER_GROUPS_CACHE_BUST_MS = 1800000; // 30 mins\nvar GROUP_PROFILES_CACHE_BUST_MS = 1800000; // 30 mins\n\n/**\n * Stores data used by \n */\n\nvar FlairStore = function (_EventEmitter) {\n (0, _inherits3.default)(FlairStore, _EventEmitter);\n\n function FlairStore(matrixClient) {\n (0, _classCallCheck3.default)(this, FlairStore);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (FlairStore.__proto__ || (0, _getPrototypeOf2.default)(FlairStore)).call(this));\n\n _this._matrixClient = matrixClient;\n _this._userGroups = {\n // $userId: ['+group1:domain', '+group2:domain', ...]\n };\n _this._groupProfiles = {\n // $groupId: {\n // avatar_url: 'mxc://...'\n // }\n };\n _this._groupProfilesPromise = {\n // $groupId: Promise\n };\n _this._usersPending = {\n // $userId: {\n // prom: Promise\n // resolve: () => {}\n // reject: () => {}\n // }\n };\n _this._usersInFlight = {\n // This has the same schema as _usersPending\n };\n\n _this._debounceTimeoutID = null;\n return _this;\n }\n\n (0, _createClass3.default)(FlairStore, [{\n key: 'groupSupport',\n value: function groupSupport() {\n return _groupSupport;\n }\n }, {\n key: 'invalidatePublicisedGroups',\n value: function invalidatePublicisedGroups(userId) {\n delete this._userGroups[userId];\n }\n }, {\n key: 'getPublicisedGroupsCached',\n value: function getPublicisedGroupsCached(matrixClient, userId) {\n var _this2 = this;\n\n if (this._userGroups[userId]) {\n return _bluebird2.default.resolve(this._userGroups[userId]);\n }\n\n // Bulk lookup ongoing, return promise to resolve/reject\n if (this._usersPending[userId]) {\n return this._usersPending[userId].prom;\n }\n // User has been moved from pending to in-flight\n if (this._usersInFlight[userId]) {\n return this._usersInFlight[userId].prom;\n }\n\n this._usersPending[userId] = {};\n this._usersPending[userId].prom = new _bluebird2.default(function (resolve, reject) {\n _this2._usersPending[userId].resolve = resolve;\n _this2._usersPending[userId].reject = reject;\n }).then(function (groups) {\n _this2._userGroups[userId] = groups;\n setTimeout(function () {\n delete _this2._userGroups[userId];\n }, USER_GROUPS_CACHE_BUST_MS);\n return _this2._userGroups[userId];\n }).catch(function (err) {\n // Indicate whether the homeserver supports groups\n if (err.errcode === 'M_UNRECOGNIZED') {\n console.warn('Cannot display flair, server does not support groups');\n _groupSupport = false;\n // Return silently to avoid spamming for non-supporting servers\n return;\n }\n console.error('Could not get groups for user', userId, err);\n throw err;\n }).finally(function () {\n delete _this2._usersInFlight[userId];\n });\n\n // This debounce will allow consecutive requests for the public groups of users that\n // are sent in intervals of < BULK_REQUEST_DEBOUNCE_MS to be batched and only requested\n // when no more requests are received within the next BULK_REQUEST_DEBOUNCE_MS. The naive\n // implementation would do a request that only requested the groups for `userId`, leading\n // to a worst and best case of 1 user per request. This implementation's worst is still\n // 1 user per request but only if the requests are > BULK_REQUEST_DEBOUNCE_MS apart and the\n // best case is N users per request.\n //\n // This is to reduce the number of requests made whilst trading off latency when viewing\n // a Flair component.\n if (this._debounceTimeoutID) clearTimeout(this._debounceTimeoutID);\n this._debounceTimeoutID = setTimeout(function () {\n _this2._batchedGetPublicGroups(matrixClient);\n }, BULK_REQUEST_DEBOUNCE_MS);\n\n return this._usersPending[userId].prom;\n }\n }, {\n key: '_batchedGetPublicGroups',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(matrixClient) {\n var _this3 = this;\n\n var resp, updatedUserGroups;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n // Move users pending to users in flight\n this._usersInFlight = this._usersPending;\n this._usersPending = {};\n\n resp = {\n users: []\n };\n _context.prev = 3;\n _context.next = 6;\n return (0, _bluebird.resolve)(matrixClient.getPublicisedGroups((0, _keys2.default)(this._usersInFlight)));\n\n case 6:\n resp = _context.sent;\n _context.next = 13;\n break;\n\n case 9:\n _context.prev = 9;\n _context.t0 = _context['catch'](3);\n\n // Propagate the same error to all usersInFlight\n (0, _keys2.default)(this._usersInFlight).forEach(function (userId) {\n // The promise should always exist for userId, but do a null-check anyway\n if (!_this3._usersInFlight[userId]) return;\n _this3._usersInFlight[userId].reject(_context.t0);\n });\n return _context.abrupt('return');\n\n case 13:\n updatedUserGroups = resp.users;\n\n (0, _keys2.default)(this._usersInFlight).forEach(function (userId) {\n // The promise should always exist for userId, but do a null-check anyway\n if (!_this3._usersInFlight[userId]) return;\n _this3._usersInFlight[userId].resolve(updatedUserGroups[userId] || []);\n });\n\n case 15:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[3, 9]]);\n }));\n\n function _batchedGetPublicGroups(_x) {\n return _ref.apply(this, arguments);\n }\n\n return _batchedGetPublicGroups;\n }()\n }, {\n key: 'getGroupProfileCached',\n value: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(matrixClient, groupId) {\n var _this4 = this;\n\n var profile;\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n if (!this._groupProfiles[groupId]) {\n _context2.next = 2;\n break;\n }\n\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 2:\n if (!this._groupProfilesPromise[groupId]) {\n _context2.next = 12;\n break;\n }\n\n _context2.prev = 3;\n _context2.next = 6;\n return (0, _bluebird.resolve)(this._groupProfilesPromise[groupId]);\n\n case 6:\n _context2.next = 11;\n break;\n\n case 8:\n _context2.prev = 8;\n _context2.t0 = _context2['catch'](3);\n return _context2.abrupt('return', null);\n\n case 11:\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 12:\n\n // No request yet, start one\n console.log('FlairStore: Request group profile of ' + groupId);\n this._groupProfilesPromise[groupId] = matrixClient.getGroupProfile(groupId);\n\n profile = void 0;\n _context2.prev = 15;\n _context2.next = 18;\n return (0, _bluebird.resolve)(this._groupProfilesPromise[groupId]);\n\n case 18:\n profile = _context2.sent;\n _context2.next = 26;\n break;\n\n case 21:\n _context2.prev = 21;\n _context2.t1 = _context2['catch'](15);\n\n console.log('FlairStore: Failed to get group profile for ' + groupId, _context2.t1);\n // Don't retry, but allow a retry when the profile is next requested\n delete this._groupProfilesPromise[groupId];\n return _context2.abrupt('return', null);\n\n case 26:\n\n this._groupProfiles[groupId] = {\n groupId: groupId,\n avatarUrl: profile.avatar_url,\n name: profile.name,\n shortDescription: profile.short_description\n };\n delete this._groupProfilesPromise[groupId];\n\n /// XXX: This is verging on recreating a third \"Flux\"-looking Store. We really\n /// should replace FlairStore with a Flux store and some async actions.\n console.log('FlairStore: Emit updateGroupProfile for ' + groupId);\n this.emit('updateGroupProfile');\n\n setTimeout(function () {\n _this4.refreshGroupProfile(matrixClient, groupId);\n }, GROUP_PROFILES_CACHE_BUST_MS);\n\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 32:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, this, [[3, 8], [15, 21]]);\n }));\n\n function getGroupProfileCached(_x2, _x3) {\n return _ref2.apply(this, arguments);\n }\n\n return getGroupProfileCached;\n }()\n }, {\n key: 'refreshGroupProfile',\n value: function refreshGroupProfile(matrixClient, groupId) {\n // Invalidate the cache\n delete this._groupProfiles[groupId];\n // Fetch new profile data, and cache it\n return this.getGroupProfileCached(matrixClient, groupId);\n }\n }]);\n return FlairStore;\n}(_events2.default);\n\nif (global.singletonFlairStore === undefined) {\n global.singletonFlairStore = new FlairStore();\n}\nexports.default = global.singletonFlairStore;\nmodule.exports = exports['default'];\n//# sourceMappingURL=FlairStore.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nexports.getDisplayAliasForRoom = getDisplayAliasForRoom;\nexports.getOnlyOtherMember = getOnlyOtherMember;\nexports.isConfCallRoom = isConfCallRoom;\nexports.looksLikeDirectMessageRoom = looksLikeDirectMessageRoom;\nexports.guessAndSetDMRoom = guessAndSetDMRoom;\nexports.setDMRoom = setDMRoom;\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Given a room object, return the alias we should use for it,\n * if any. This could be the canonical alias if one exists, otherwise\n * an alias selected arbitrarily but deterministically from the list\n * of aliases. Otherwise return null;\n */\n/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction getDisplayAliasForRoom(room) {\n return room.getCanonicalAlias() || room.getAliases()[0];\n}\n\n/**\n * If the room contains only two members including the logged-in user,\n * return the other one. Otherwise, return null.\n */\nfunction getOnlyOtherMember(room, myUserId) {\n if (room.currentState.getJoinedMemberCount() === 2) {\n return room.getJoinedMembers().filter(function (m) {\n return m.userId !== myUserId;\n })[0];\n }\n\n return null;\n}\n\nfunction _isConfCallRoom(room, myUserId, conferenceHandler) {\n if (!conferenceHandler) return false;\n\n var myMembership = room.getMyMembership();\n if (myMembership != \"join\") {\n return false;\n }\n\n var otherMember = getOnlyOtherMember(room, myUserId);\n if (!otherMember) {\n return false;\n }\n\n if (conferenceHandler.isConferenceUser(otherMember.userId)) {\n return true;\n }\n\n return false;\n}\n\n// Cache whether a room is a conference call. Assumes that rooms will always\n// either will or will not be a conference call room.\nvar isConfCallRoomCache = {\n // $roomId: bool\n};\n\nfunction isConfCallRoom(room, myUserId, conferenceHandler) {\n if (isConfCallRoomCache[room.roomId] !== undefined) {\n return isConfCallRoomCache[room.roomId];\n }\n\n var result = _isConfCallRoom(room, myUserId, conferenceHandler);\n\n isConfCallRoomCache[room.roomId] = result;\n\n return result;\n}\n\nfunction looksLikeDirectMessageRoom(room, myUserId) {\n var myMembership = room.getMyMembership();\n var me = room.getMember(myUserId);\n\n if (myMembership == \"join\" || myMembership === \"ban\" || me && me.isKicked()) {\n // Used to split rooms via tags\n var tagNames = (0, _keys2.default)(room.tags);\n // Used for 1:1 direct chats\n // Show 1:1 chats in seperate \"Direct Messages\" section as long as they haven't\n // been moved to a different tag section\n var totalMemberCount = room.currentState.getJoinedMemberCount() + room.currentState.getInvitedMemberCount();\n if (totalMemberCount === 2 && !tagNames.length) {\n return true;\n }\n }\n return false;\n}\n\nfunction guessAndSetDMRoom(room, isDirect) {\n var newTarget = void 0;\n if (isDirect) {\n var guessedUserId = guessDMRoomTargetId(room, _MatrixClientPeg2.default.get().getUserId());\n newTarget = guessedUserId;\n } else {\n newTarget = null;\n }\n\n return setDMRoom(room.roomId, newTarget);\n}\n\n/**\n * Marks or unmarks the given room as being as a DM room.\n * @param {string} roomId The ID of the room to modify\n * @param {string} userId The user ID of the desired DM\n room target user or null to un-mark\n this room as a DM room\n * @returns {object} A promise\n */\nfunction setDMRoom(roomId, userId) {\n if (_MatrixClientPeg2.default.get().isGuest()) {\n return _bluebird2.default.resolve();\n }\n\n var mDirectEvent = _MatrixClientPeg2.default.get().getAccountData('m.direct');\n var dmRoomMap = {};\n\n if (mDirectEvent !== undefined) dmRoomMap = mDirectEvent.getContent();\n\n // remove it from the lists of any others users\n // (it can only be a DM room for one person)\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(dmRoomMap)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var thisUserId = _step.value;\n\n var _roomList = dmRoomMap[thisUserId];\n\n if (thisUserId != userId) {\n var indexOfRoom = _roomList.indexOf(roomId);\n if (indexOfRoom > -1) {\n _roomList.splice(indexOfRoom, 1);\n }\n }\n }\n\n // now add it, if it's not already there\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n if (userId) {\n var roomList = dmRoomMap[userId] || [];\n if (roomList.indexOf(roomId) == -1) {\n roomList.push(roomId);\n }\n dmRoomMap[userId] = roomList;\n }\n\n return _MatrixClientPeg2.default.get().setAccountData('m.direct', dmRoomMap);\n}\n\n/**\n * Given a room, estimate which of its members is likely to\n * be the target if the room were a DM room and return that user.\n *\n * @param {Object} room Target room\n * @param {string} myUserId User ID of the current user\n * @returns {string} User ID of the user that the room is probably a DM with\n */\nfunction guessDMRoomTargetId(room, myUserId) {\n var oldestTs = void 0;\n var oldestUser = void 0;\n\n // Pick the joined user who's been here longest (and isn't us),\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (0, _getIterator3.default)(room.getJoinedMembers()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var user = _step2.value;\n\n if (user.userId == myUserId) continue;\n\n if (oldestTs === undefined || user.events.member && user.events.member.getTs() < oldestTs) {\n oldestUser = user;\n oldestTs = user.events.member.getTs();\n }\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n if (oldestUser) return oldestUser.userId;\n\n // if there are no joined members other than us, use the oldest member\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = (0, _getIterator3.default)(room.currentState.getMembers()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var _user = _step3.value;\n\n if (_user.userId == myUserId) continue;\n\n if (oldestTs === undefined || _user.events.member && _user.events.member.getTs() < oldestTs) {\n oldestUser = _user;\n oldestTs = _user.events.member.getTs();\n }\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n if (oldestUser === undefined) return myUserId;\n return oldestUser.userId;\n}\n//# sourceMappingURL=Rooms.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getArea = require('../get-area');\n\nvar _getArea2 = _interopRequireDefault(_getArea);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function () {\n var top = window.pageYOffset;\n var left = window.pageXOffset;\n var width = window.innerWidth;\n var height = window.innerHeight;\n\n var right = left + width;\n var bottom = top + height;\n\n return (0, _getArea2.default)({\n top: top, left: left, right: right, bottom: bottom\n });\n};","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar prefix = function prefix(key) {\n return 'private-react-beautiful-dnd-key-do-not-use-' + key;\n};\n\nvar storeKey = exports.storeKey = prefix('store');\nvar droppableIdKey = exports.droppableIdKey = prefix('droppable-id');\nvar dimensionMarshalKey = exports.dimensionMarshalKey = prefix('dimension-marshal');\nvar styleContextKey = exports.styleContextKey = prefix('style-context');\nvar canLiftContextKey = exports.canLiftContextKey = prefix('can-lift');","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","var toInteger = require('./_to-integer');\nvar max = Math.max;\nvar min = Math.min;\nmodule.exports = function (index, length) {\n index = toInteger(index);\n return index < 0 ? max(index + length, 0) : min(index, length);\n};\n","// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])\nvar anObject = require('./_an-object');\nvar dPs = require('./_object-dps');\nvar enumBugKeys = require('./_enum-bug-keys');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar Empty = function () { /* empty */ };\nvar PROTOTYPE = 'prototype';\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar createDict = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = require('./_dom-create')('iframe');\n var i = enumBugKeys.length;\n var lt = '<';\n var gt = '>';\n var iframeDocument;\n iframe.style.display = 'none';\n require('./_html').appendChild(iframe);\n iframe.src = 'javascript:'; // eslint-disable-line no-script-url\n // createDict = iframe.contentWindow.Object;\n // html.removeChild(iframe);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);\n iframeDocument.close();\n createDict = iframeDocument.F;\n while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];\n return createDict();\n};\n\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n Empty[PROTOTYPE] = anObject(O);\n result = new Empty();\n Empty[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = createDict();\n return Properties === undefined ? result : dPs(result, Properties);\n};\n","// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)\nvar $keys = require('./_object-keys-internal');\nvar hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');\n\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return $keys(O, hiddenKeys);\n};\n","'use strict';\nvar global = require('./_global');\nvar dP = require('./_object-dp');\nvar DESCRIPTORS = require('./_descriptors');\nvar SPECIES = require('./_wks')('species');\n\nmodule.exports = function (KEY) {\n var C = global[KEY];\n if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n};\n","module.exports = function (it, Constructor, name, forbiddenField) {\n if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {\n throw TypeError(name + ': incorrect invocation!');\n } return it;\n};\n","var ctx = require('./_ctx');\nvar call = require('./_iter-call');\nvar isArrayIter = require('./_is-array-iter');\nvar anObject = require('./_an-object');\nvar toLength = require('./_to-length');\nvar getIterFn = require('./core.get-iterator-method');\nvar BREAK = {};\nvar RETURN = {};\nvar exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {\n var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);\n var f = ctx(fn, that, entries ? 2 : 1);\n var index = 0;\n var length, step, iterator, result;\n if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');\n // fast case for arrays with default iterator\n if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {\n result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);\n if (result === BREAK || result === RETURN) return result;\n } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {\n result = call(iterator, f, step.value, entries);\n if (result === BREAK || result === RETURN) return result;\n }\n};\nexports.BREAK = BREAK;\nexports.RETURN = RETURN;\n","var redefine = require('./_redefine');\nmodule.exports = function (target, src, safe) {\n for (var key in src) redefine(target, key, src[key], safe);\n return target;\n};\n","var isObject = require('./_is-object');\nmodule.exports = function (it, TYPE) {\n if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');\n return it;\n};\n","module.exports = !require('./_descriptors') && !require('./_fails')(function () {\n return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;\n});\n","module.exports = require('./_hide');\n","var has = require('./_has');\nvar toIObject = require('./_to-iobject');\nvar arrayIndexOf = require('./_array-includes')(false);\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\n\nmodule.exports = function (object, names) {\n var O = toIObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~arrayIndexOf(result, key) || result.push(key);\n }\n return result;\n};\n","// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar cof = require('./_cof');\n// eslint-disable-next-line no-prototype-builtins\nmodule.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {\n return cof(it) == 'String' ? it.split('') : Object(it);\n};\n","// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)\nvar has = require('./_has');\nvar toObject = require('./_to-object');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar ObjectProto = Object.prototype;\n\nmodule.exports = Object.getPrototypeOf || function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectProto : null;\n};\n","exports.f = require('./_wks');\n","var global = require('./_global');\nvar core = require('./_core');\nvar LIBRARY = require('./_library');\nvar wksExt = require('./_wks-ext');\nvar defineProperty = require('./_object-dp').f;\nmodule.exports = function (name) {\n var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});\n if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });\n};\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","/*\nCopyright 2016, 2017 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/**\n * @module models/event-timeline\n */\n\nvar _freeze = require(\"babel-runtime/core-js/object/freeze\");\n\nvar _freeze2 = _interopRequireDefault(_freeze);\n\nvar _getIterator2 = require(\"babel-runtime/core-js/get-iterator\");\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar RoomState = require(\"./room-state\");\n\n/**\n * Construct a new EventTimeline\n *\n * An EventTimeline represents a contiguous sequence of events in a room.\n *\n *
As well as keeping track of the events themselves, it stores the state of\n * the room at the beginning and end of the timeline, and pagination tokens for\n * going backwards and forwards in the timeline.\n *\n *
In order that clients can meaningfully maintain an index into a timeline,\n * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n * incremented when events are prepended to the timeline. The index of an event\n * relative to baseIndex therefore remains constant.\n *\n *
Once a timeline joins up with its neighbour, they are linked together into a\n * doubly-linked list.\n *\n * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of\n * @constructor\n */\nfunction EventTimeline(eventTimelineSet) {\n this._eventTimelineSet = eventTimelineSet;\n this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null;\n this._events = [];\n this._baseIndex = 0;\n this._startState = new RoomState(this._roomId);\n this._startState.paginationToken = null;\n this._endState = new RoomState(this._roomId);\n this._endState.paginationToken = null;\n\n this._prevTimeline = null;\n this._nextTimeline = null;\n\n // this is used by client.js\n this._paginationRequests = { 'b': null, 'f': null };\n\n this._name = this._roomId + \":\" + new Date().toISOString();\n}\n\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\nEventTimeline.BACKWARDS = \"b\";\n\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\nEventTimeline.FORWARDS = \"f\";\n\n/**\n * Initialise the start and end state with the given events\n *\n *
This can only be called before any events are added.\n *\n * @param {MatrixEvent[]} stateEvents list of state events to initialise the\n * state with.\n * @throws {Error} if an attempt is made to call this after addEvent is called.\n */\nEventTimeline.prototype.initialiseState = function (stateEvents) {\n if (this._events.length > 0) {\n throw new Error(\"Cannot initialise state after events are added\");\n }\n\n // We previously deep copied events here and used different copies in\n // the oldState and state events: this decision seems to date back\n // quite a way and was apparently made to fix a bug where modifications\n // made to the start state leaked through to the end state.\n // This really shouldn't be possible though: the events themselves should\n // not change. Duplicating the events uses a lot of extra memory,\n // so we now no longer do it. To assert that they really do never change,\n // freeze them! Note that we can't do this for events in general:\n // although it looks like the only things preventing us are the\n // 'status' flag, forwardLooking (which is only set once when adding to the\n // timeline) and possibly the sender (which seems like it should never be\n // reset but in practice causes a lot of the tests to break).\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(stateEvents), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var e = _step.value;\n\n (0, _freeze2.default)(e);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n this._startState.setStateEvents(stateEvents);\n this._endState.setStateEvents(stateEvents);\n};\n\n/**\n * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.\n * All attached listeners will keep receiving state updates from the new live timeline state.\n * The end state of this timeline gets replaced with an independent copy of the current RoomState,\n * and will need a new pagination token if it ever needs to paginate forwards.\n\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\nEventTimeline.prototype.forkLive = function (direction) {\n var forkState = this.getState(direction);\n var timeline = new EventTimeline(this._eventTimelineSet);\n timeline._startState = forkState.clone();\n // Now clobber the end state of the new live timeline with that from the\n // previous live timeline. It will be identical except that we'll keep\n // using the same RoomMember objects for the 'live' set of members with any\n // listeners still attached\n timeline._endState = forkState;\n // Firstly, we just stole the current timeline's end state, so it needs a new one.\n // Make an immutable copy of the state so back pagination will get the correct sentinels.\n this._endState = forkState.clone();\n return timeline;\n};\n\n/**\n * Creates an independent timeline, inheriting the directional state from this timeline.\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\nEventTimeline.prototype.fork = function (direction) {\n var forkState = this.getState(direction);\n var timeline = new EventTimeline(this._eventTimelineSet);\n timeline._startState = forkState.clone();\n timeline._endState = forkState.clone();\n return timeline;\n};\n\n/**\n * Get the ID of the room for this timeline\n * @return {string} room ID\n */\nEventTimeline.prototype.getRoomId = function () {\n return this._roomId;\n};\n\n/**\n * Get the filter for this timeline's timelineSet (if any)\n * @return {Filter} filter\n */\nEventTimeline.prototype.getFilter = function () {\n return this._eventTimelineSet.getFilter();\n};\n\n/**\n * Get the timelineSet for this timeline\n * @return {EventTimelineSet} timelineSet\n */\nEventTimeline.prototype.getTimelineSet = function () {\n return this._eventTimelineSet;\n};\n\n/**\n * Get the base index.\n *\n *
This is an index which is incremented when events are prepended to the\n * timeline. An individual event therefore stays at the same index in the array\n * relative to the base index (although note that a given event's index may\n * well be less than the base index, thus giving that event a negative relative\n * index).\n *\n * @return {number}\n */\nEventTimeline.prototype.getBaseIndex = function () {\n return this._baseIndex;\n};\n\n/**\n * Get the list of events in this context\n *\n * @return {MatrixEvent[]} An array of MatrixEvents\n */\nEventTimeline.prototype.getEvents = function () {\n return this._events;\n};\n\n/**\n * Get the room state at the start/end of the timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {RoomState} state at the start/end of the timeline\n */\nEventTimeline.prototype.getState = function (direction) {\n if (direction == EventTimeline.BACKWARDS) {\n return this._startState;\n } else if (direction == EventTimeline.FORWARDS) {\n return this._endState;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n};\n\n/**\n * Get a pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to get the\n * pagination token for going forwards in time.\n *\n * @return {?string} pagination token\n */\nEventTimeline.prototype.getPaginationToken = function (direction) {\n return this.getState(direction).paginationToken;\n};\n\n/**\n * Set a pagination token\n *\n * @param {?string} token pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to set the\n * pagination token for going forwards in time.\n */\nEventTimeline.prototype.setPaginationToken = function (token, direction) {\n this.getState(direction).paginationToken = token;\n};\n\n/**\n * Get the next timeline in the series\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the previous\n * timeline; EventTimeline.FORWARDS to get the next timeline.\n *\n * @return {?EventTimeline} previous or following timeline, if they have been\n * joined up.\n */\nEventTimeline.prototype.getNeighbouringTimeline = function (direction) {\n if (direction == EventTimeline.BACKWARDS) {\n return this._prevTimeline;\n } else if (direction == EventTimeline.FORWARDS) {\n return this._nextTimeline;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n};\n\n/**\n * Set the next timeline in the series\n *\n * @param {EventTimeline} neighbour previous/following timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the previous\n * timeline; EventTimeline.FORWARDS to set the next timeline.\n *\n * @throws {Error} if an attempt is made to set the neighbouring timeline when\n * it is already set.\n */\nEventTimeline.prototype.setNeighbouringTimeline = function (neighbour, direction) {\n if (this.getNeighbouringTimeline(direction)) {\n throw new Error(\"timeline already has a neighbouring timeline - \" + \"cannot reset neighbour (direction: \" + direction + \")\");\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n this._prevTimeline = neighbour;\n } else if (direction == EventTimeline.FORWARDS) {\n this._nextTimeline = neighbour;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n // make sure we don't try to paginate this timeline\n this.setPaginationToken(null, direction);\n};\n\n/**\n * Add a new event to the timeline, and update the state\n *\n * @param {MatrixEvent} event new event\n * @param {boolean} atStart true to insert new event at the start\n */\nEventTimeline.prototype.addEvent = function (event, atStart) {\n var stateContext = atStart ? this._startState : this._endState;\n\n // only call setEventMetadata on the unfiltered timelineSets\n var timelineSet = this.getTimelineSet();\n if (timelineSet.room && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n\n // modify state\n if (event.isState()) {\n stateContext.setStateEvents([event]);\n // it is possible that the act of setting the state event means we\n // can set more metadata (specifically sender/target props), so try\n // it again if the prop wasn't previously set. It may also mean that\n // the sender/target is updated (if the event set was a room member event)\n // so we want to use the *updated* member (new avatar/name) instead.\n //\n // However, we do NOT want to do this on member events if we're going\n // back in time, else we'll set the .sender value for BEFORE the given\n // member event, whereas we want to set the .sender value for the ACTUAL\n // member event itself.\n if (!event.sender || event.getType() === \"m.room.member\" && !atStart) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n }\n }\n }\n\n var insertIndex = void 0;\n\n if (atStart) {\n insertIndex = 0;\n } else {\n insertIndex = this._events.length;\n }\n\n this._events.splice(insertIndex, 0, event); // insert element\n if (atStart) {\n this._baseIndex++;\n }\n};\n\n/**\n * Static helper method to set sender and target properties\n *\n * @param {MatrixEvent} event the event whose metadata is to be set\n * @param {RoomState} stateContext the room state to be queried\n * @param {bool} toStartOfTimeline if true the event's forwardLooking flag is set false\n */\nEventTimeline.setEventMetadata = function (event, stateContext, toStartOfTimeline) {\n // set sender and target properties\n event.sender = stateContext.getSentinelMember(event.getSender());\n if (event.getType() === \"m.room.member\") {\n event.target = stateContext.getSentinelMember(event.getStateKey());\n }\n if (event.isState()) {\n // room state has no concept of 'old' or 'current', but we want the\n // room state to regress back to previous values if toStartOfTimeline\n // is set, which means inspecting prev_content if it exists. This\n // is done by toggling the forwardLooking flag.\n if (toStartOfTimeline) {\n event.forwardLooking = false;\n }\n }\n};\n\n/**\n * Remove an event from the timeline\n *\n * @param {string} eventId ID of event to be removed\n * @return {?MatrixEvent} removed event, or null if not found\n */\nEventTimeline.prototype.removeEvent = function (eventId) {\n for (var i = this._events.length - 1; i >= 0; i--) {\n var ev = this._events[i];\n if (ev.getId() == eventId) {\n this._events.splice(i, 1);\n if (i < this._baseIndex) {\n this._baseIndex--;\n }\n return ev;\n }\n }\n return null;\n};\n\n/**\n * Return a string to identify this timeline, for debugging\n *\n * @return {string} name for this timeline\n */\nEventTimeline.prototype.toString = function () {\n return this._name;\n};\n\n/**\n * The EventTimeline class\n */\nmodule.exports = EventTimeline;\n//# sourceMappingURL=event-timeline.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.UserAddressType = exports.addressTypes = undefined;\nexports.getAddressType = getAddressType;\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar emailRegex = /^\\S+@\\S+\\.\\S+$/;\n\nvar mxUserIdRegex = /^@\\S+:\\S+$/;\nvar mxRoomIdRegex = /^!\\S+:\\S+$/;\n\nvar addressTypes = exports.addressTypes = ['mx-user-id', 'mx-room-id', 'email'];\n\n// PropType definition for an object describing\n// an address that can be invited to a room (which\n// could be a third party identifier or a matrix ID)\n// along with some additional information about the\n// address / target.\nvar UserAddressType = exports.UserAddressType = _propTypes2.default.shape({\n addressType: _propTypes2.default.oneOf(addressTypes).isRequired,\n address: _propTypes2.default.string.isRequired,\n displayName: _propTypes2.default.string,\n avatarMxc: _propTypes2.default.string,\n // true if the address is known to be a valid address (eg. is a real\n // user we've seen) or false otherwise (eg. is just an address the\n // user has entered)\n isKnown: _propTypes2.default.bool\n});\n\nfunction getAddressType(inputText) {\n var isEmailAddress = emailRegex.test(inputText);\n var isUserId = mxUserIdRegex.test(inputText);\n var isRoomId = mxRoomIdRegex.test(inputText);\n\n // sanity check the input for user IDs\n if (isEmailAddress) {\n return 'email';\n } else if (isUserId) {\n return 'mx-user-id';\n } else if (isRoomId) {\n return 'mx-room-id';\n } else {\n return null;\n }\n}\n//# sourceMappingURL=UserAddress.js.map","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _DMRoomMap = require('./utils/DMRoomMap');\n\nvar _DMRoomMap2 = _interopRequireDefault(_DMRoomMap);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nmodule.exports = {\n avatarUrlForMember: function avatarUrlForMember(member, width, height, resizeMethod) {\n var url = member.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), Math.floor(width * window.devicePixelRatio), Math.floor(height * window.devicePixelRatio), resizeMethod, false, false);\n if (!url) {\n // member can be null here currently since on invites, the JS SDK\n // does not have enough info to build a RoomMember object for\n // the inviter.\n url = this.defaultAvatarUrlForString(member ? member.userId : '');\n }\n return url;\n },\n\n avatarUrlForUser: function avatarUrlForUser(user, width, height, resizeMethod) {\n var url = _matrixJsSdk.ContentRepo.getHttpUriForMxc(_MatrixClientPeg2.default.get().getHomeserverUrl(), user.avatarUrl, Math.floor(width * window.devicePixelRatio), Math.floor(height * window.devicePixelRatio), resizeMethod);\n if (!url || url.length === 0) {\n return null;\n }\n return url;\n },\n\n defaultAvatarUrlForString: function defaultAvatarUrlForString(s) {\n var images = ['03b381', '368bd6', 'ac3ba8'];\n var total = 0;\n for (var i = 0; i < s.length; ++i) {\n total += s.charCodeAt(i);\n }\n return require('../res/img/' + images[total % images.length] + '.png');\n },\n\n /**\n * returns the first (non-sigil) character of 'name',\n * converted to uppercase\n * @param {string} name\n * @return {string} the first letter\n */\n getInitialLetter: function getInitialLetter(name) {\n if (!name) {\n // XXX: We should find out what causes the name to sometimes be falsy.\n console.trace(\"`name` argument to `getInitialLetter` not supplied\");\n return undefined;\n }\n if (name.length < 1) {\n return undefined;\n }\n\n var idx = 0;\n var initial = name[0];\n if ((initial === '@' || initial === '#' || initial === '+') && name[1]) {\n idx++;\n }\n\n // string.codePointAt(0) would do this, but that isn't supported by\n // some browsers (notably PhantomJS).\n var chars = 1;\n var first = name.charCodeAt(idx);\n\n // check if it’s the start of a surrogate pair\n if (first >= 0xD800 && first <= 0xDBFF && name[idx + 1]) {\n var second = name.charCodeAt(idx + 1);\n if (second >= 0xDC00 && second <= 0xDFFF) {\n chars++;\n }\n }\n\n var firstChar = name.substring(idx, idx + chars);\n return firstChar.toUpperCase();\n },\n avatarUrlForRoom: function avatarUrlForRoom(room, width, height, resizeMethod) {\n var explicitRoomAvatar = room.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), width, height, resizeMethod, false);\n if (explicitRoomAvatar) {\n return explicitRoomAvatar;\n }\n\n var otherMember = null;\n var otherUserId = _DMRoomMap2.default.shared().getUserIdForRoomId(room.roomId);\n if (otherUserId) {\n otherMember = room.getMember(otherUserId);\n } else {\n // if the room is not marked as a 1:1, but only has max 2 members\n // then still try to show any avatar (pref. other member)\n otherMember = room.getAvatarFallbackMember();\n }\n if (otherMember) {\n return otherMember.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), width, height, resizeMethod, false);\n }\n return null;\n }\n};\n//# sourceMappingURL=Avatar.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2015 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar DEBUG = 0;\n\n// utility to turn #rrggbb or rgb(r,g,b) into [red,green,blue]\nfunction colorToRgb(color) {\n if (!color) {\n return [0, 0, 0];\n }\n\n if (color[0] === '#') {\n color = color.slice(1);\n if (color.length === 3) {\n color = color[0] + color[0] + color[1] + color[1] + color[2] + color[2];\n }\n var val = parseInt(color, 16);\n var r = val >> 16 & 255;\n var g = val >> 8 & 255;\n var b = val & 255;\n return [r, g, b];\n } else {\n var match = color.match(/rgb\\((.*?),(.*?),(.*?)\\)/);\n if (match) {\n return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];\n }\n }\n return [0, 0, 0];\n}\n\n// utility to turn [red,green,blue] into #rrggbb\nfunction rgbToColor(rgb) {\n var val = rgb[0] << 16 | rgb[1] << 8 | rgb[2];\n return '#' + (0x1000000 + val).toString(16).slice(1);\n}\n\nvar Tinter = function () {\n function Tinter() {\n (0, _classCallCheck3.default)(this, Tinter);\n\n // The default colour keys to be replaced as referred to in CSS\n // (should be overridden by .mx_theme_accentColor and .mx_theme_secondaryAccentColor)\n this.keyRgb = [\"rgb(118, 207, 166)\", // Vector Green\n \"rgb(234, 245, 240)\", // Vector Light Green\n \"rgb(211, 239, 225)\"];\n\n // Some algebra workings for calculating the tint % of Vector Green & Light Green\n // x * 118 + (1 - x) * 255 = 234\n // x * 118 + 255 - 255 * x = 234\n // x * 118 - x * 255 = 234 - 255\n // (255 - 118) x = 255 - 234\n // x = (255 - 234) / (255 - 118) = 0.16\n\n // The colour keys to be replaced as referred to in SVGs\n this.keyHex = [\"#76CFA6\", // Vector Green\n \"#EAF5F0\", // Vector Light Green\n \"#D3EFE1\", // roomsublist-label-bg-color (20% Green overlaid on Light Green)\n \"#FFFFFF\", // white highlights of the SVGs (for switching to dark theme)\n \"#000000\"];\n\n // track the replacement colours actually being used\n // defaults to our keys.\n this.colors = [this.keyHex[0], this.keyHex[1], this.keyHex[2], this.keyHex[3], this.keyHex[4]];\n\n // track the most current tint request inputs (which may differ from the\n // end result stored in this.colors\n this.currentTint = [undefined, undefined, undefined, undefined, undefined];\n\n this.cssFixups = [\n // { theme: {\n // style: a style object that should be fixed up taken from a stylesheet\n // attr: name of the attribute to be clobbered, e.g. 'color'\n // index: ordinal of primary, secondary or tertiary\n // },\n // }\n ];\n\n // CSS attributes to be fixed up\n this.cssAttrs = [\"color\", \"backgroundColor\", \"borderColor\", \"borderTopColor\", \"borderBottomColor\", \"borderLeftColor\"];\n\n this.svgAttrs = [\"fill\", \"stroke\"];\n\n // List of functions to call when the tint changes.\n this.tintables = [];\n\n // the currently loaded theme (if any)\n this.theme = undefined;\n\n // whether to force a tint (e.g. after changing theme)\n this.forceTint = false;\n }\n\n /**\n * Register a callback to fire when the tint changes.\n * This is used to rewrite the tintable SVGs with the new tint.\n *\n * It's not possible to unregister a tintable callback. So this can only be\n * used to register a static callback. If a set of tintables will change\n * over time then the best bet is to register a single callback for the\n * entire set.\n *\n * @param {Function} tintable Function to call when the tint changes.\n */\n\n\n (0, _createClass3.default)(Tinter, [{\n key: 'registerTintable',\n value: function registerTintable(tintable) {\n this.tintables.push(tintable);\n }\n }, {\n key: 'getKeyRgb',\n value: function getKeyRgb() {\n return this.keyRgb;\n }\n }, {\n key: 'tint',\n value: function tint(primaryColor, secondaryColor, tertiaryColor) {\n return;\n // eslint-disable-next-line no-unreachable\n this.currentTint[0] = primaryColor;\n this.currentTint[1] = secondaryColor;\n this.currentTint[2] = tertiaryColor;\n\n this.calcCssFixups();\n\n if (DEBUG) {\n console.log(\"Tinter.tint(\" + primaryColor + \", \" + secondaryColor + \", \" + tertiaryColor + \")\");\n }\n\n if (!primaryColor) {\n primaryColor = this.keyRgb[0];\n secondaryColor = this.keyRgb[1];\n tertiaryColor = this.keyRgb[2];\n }\n\n if (!secondaryColor) {\n var x = 0.16; // average weighting factor calculated from vector green & light green\n var rgb = colorToRgb(primaryColor);\n rgb[0] = x * rgb[0] + (1 - x) * 255;\n rgb[1] = x * rgb[1] + (1 - x) * 255;\n rgb[2] = x * rgb[2] + (1 - x) * 255;\n secondaryColor = rgbToColor(rgb);\n }\n\n if (!tertiaryColor) {\n var _x = 0.19;\n var rgb1 = colorToRgb(primaryColor);\n var rgb2 = colorToRgb(secondaryColor);\n rgb1[0] = _x * rgb1[0] + (1 - _x) * rgb2[0];\n rgb1[1] = _x * rgb1[1] + (1 - _x) * rgb2[1];\n rgb1[2] = _x * rgb1[2] + (1 - _x) * rgb2[2];\n tertiaryColor = rgbToColor(rgb1);\n }\n\n if (this.forceTint == false && this.colors[0] === primaryColor && this.colors[1] === secondaryColor && this.colors[2] === tertiaryColor) {\n return;\n }\n\n this.forceTint = false;\n\n this.colors[0] = primaryColor;\n this.colors[1] = secondaryColor;\n this.colors[2] = tertiaryColor;\n\n if (DEBUG) {\n console.log(\"Tinter.tint final: (\" + primaryColor + \", \" + secondaryColor + \", \" + tertiaryColor + \")\");\n }\n\n // go through manually fixing up the stylesheets.\n this.applyCssFixups();\n\n // tell all the SVGs to go fix themselves up\n // we don't do this as a dispatch otherwise it will visually lag\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'tintSvgWhite',\n value: function tintSvgWhite(whiteColor) {\n this.currentTint[3] = whiteColor;\n\n if (!whiteColor) {\n whiteColor = this.colors[3];\n }\n if (this.colors[3] === whiteColor) {\n return;\n }\n this.colors[3] = whiteColor;\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'tintSvgBlack',\n value: function tintSvgBlack(blackColor) {\n this.currentTint[4] = blackColor;\n\n if (!blackColor) {\n blackColor = this.colors[4];\n }\n if (this.colors[4] === blackColor) {\n return;\n }\n this.colors[4] = blackColor;\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'setTheme',\n value: function setTheme(theme) {\n this.theme = theme;\n\n // update keyRgb from the current theme CSS itself, if it defines it\n if (document.getElementById('mx_theme_accentColor')) {\n this.keyRgb[0] = window.getComputedStyle(document.getElementById('mx_theme_accentColor')).color;\n }\n if (document.getElementById('mx_theme_secondaryAccentColor')) {\n this.keyRgb[1] = window.getComputedStyle(document.getElementById('mx_theme_secondaryAccentColor')).color;\n }\n if (document.getElementById('mx_theme_tertiaryAccentColor')) {\n this.keyRgb[2] = window.getComputedStyle(document.getElementById('mx_theme_tertiaryAccentColor')).color;\n }\n\n this.calcCssFixups();\n this.forceTint = true;\n\n this.tint(this.currentTint[0], this.currentTint[1], this.currentTint[2]);\n\n if (theme === 'dark') {\n // abuse the tinter to change all the SVG's #fff to #2d2d2d\n // XXX: obviously this shouldn't be hardcoded here.\n this.tintSvgWhite('#2d2d2d');\n this.tintSvgBlack('#dddddd');\n } else {\n this.tintSvgWhite('#ffffff');\n this.tintSvgBlack('#000000');\n }\n }\n }, {\n key: 'calcCssFixups',\n value: function calcCssFixups() {\n // cache our fixups\n if (this.cssFixups[this.theme]) return;\n\n if (DEBUG) {\n console.debug(\"calcCssFixups start for \" + this.theme + \" (checking \" + document.styleSheets.length + \" stylesheets)\");\n }\n\n this.cssFixups[this.theme] = [];\n\n for (var i = 0; i < document.styleSheets.length; i++) {\n var ss = document.styleSheets[i];\n try {\n if (!ss) continue; // well done safari >:(\n // Chromium apparently sometimes returns null here; unsure why.\n // see $14534907369972FRXBx:matrix.org in HQ\n // ...ah, it's because there's a third party extension like\n // privacybadger inserting its own stylesheet in there with a\n // resource:// URI or something which results in a XSS error.\n // See also #vector:matrix.org/$145357669685386ebCfr:matrix.org\n // ...except some browsers apparently return stylesheets without\n // hrefs, which we have no choice but ignore right now\n\n // XXX seriously? we are hardcoding the name of vector's CSS file in\n // here?\n //\n // Why do we need to limit it to vector's CSS file anyway - if there\n // are other CSS files affecting the doc don't we want to apply the\n // same transformations to them?\n //\n // Iterating through the CSS looking for matches to hack on feels\n // pretty horrible anyway. And what if the application skin doesn't use\n // Vector Green as its primary color?\n // --richvdh\n\n // Yes, tinting assumes that you are using the Riot skin for now.\n // The right solution will be to move the CSS over to react-sdk.\n // And yes, the default assets for the base skin might as well use\n // Vector Green as any other colour.\n // --matthew\n\n // stylesheets we don't have permission to access (eg. ones from extensions) have a null\n // href and will throw exceptions if we try to access their rules.\n if (!ss.href || !ss.href.match(new RegExp('/theme-' + this.theme + '.css$'))) continue;\n if (ss.disabled) continue;\n if (!ss.cssRules) continue;\n\n if (DEBUG) console.debug(\"calcCssFixups checking \" + ss.cssRules.length + \" rules for \" + ss.href);\n\n for (var j = 0; j < ss.cssRules.length; j++) {\n var rule = ss.cssRules[j];\n if (!rule.style) continue;\n if (rule.selectorText && rule.selectorText.match(/#mx_theme/)) continue;\n for (var k = 0; k < this.cssAttrs.length; k++) {\n var attr = this.cssAttrs[k];\n for (var l = 0; l < this.keyRgb.length; l++) {\n if (rule.style[attr] === this.keyRgb[l]) {\n this.cssFixups[this.theme].push({\n style: rule.style,\n attr: attr,\n index: l\n });\n }\n }\n }\n }\n } catch (e) {\n // Catch any random exceptions that happen here: all sorts of things can go\n // wrong with this (nulls, SecurityErrors) and mostly it's for other\n // stylesheets that we don't want to proces anyway. We should not propagate an\n // exception out since this will cause the app to fail to start.\n console.log(\"Failed to calculate CSS fixups for a stylesheet: \" + ss.href, e);\n }\n }\n if (DEBUG) {\n console.log(\"calcCssFixups end (\" + this.cssFixups[this.theme].length + \" fixups)\");\n }\n }\n }, {\n key: 'applyCssFixups',\n value: function applyCssFixups() {\n if (DEBUG) {\n console.log(\"applyCssFixups start (\" + this.cssFixups[this.theme].length + \" fixups)\");\n }\n for (var i = 0; i < this.cssFixups[this.theme].length; i++) {\n var cssFixup = this.cssFixups[this.theme][i];\n try {\n cssFixup.style[cssFixup.attr] = this.colors[cssFixup.index];\n } catch (e) {\n // Firefox Quantum explodes if you manually edit the CSS in the\n // inspector and then try to do a tint, as apparently all the\n // fixups are then stale.\n console.error(\"Failed to apply cssFixup in Tinter! \", e.name);\n }\n }\n if (DEBUG) console.log(\"applyCssFixups end\");\n }\n\n // XXX: we could just move this all into TintableSvg, but as it's so similar\n // to the CSS fixup stuff in Tinter (just that the fixups are stored in TintableSvg)\n // keeping it here for now.\n\n }, {\n key: 'calcSvgFixups',\n value: function calcSvgFixups(svgs) {\n // go through manually fixing up SVG colours.\n // we could do this by stylesheets, but keeping the stylesheets\n // updated would be a PITA, so just brute-force search for the\n // key colour; cache the element and apply.\n\n if (DEBUG) console.log(\"calcSvgFixups start for \" + svgs);\n var fixups = [];\n for (var i = 0; i < svgs.length; i++) {\n var svgDoc = void 0;\n try {\n svgDoc = svgs[i].contentDocument;\n } catch (e) {\n var msg = 'Failed to get svg.contentDocument of ' + svgs[i].toString();\n if (e.message) {\n msg += e.message;\n }\n if (e.stack) {\n msg += ' | stack: ' + e.stack;\n }\n console.error(msg);\n }\n if (!svgDoc) continue;\n var tags = svgDoc.getElementsByTagName(\"*\");\n for (var j = 0; j < tags.length; j++) {\n var tag = tags[j];\n for (var k = 0; k < this.svgAttrs.length; k++) {\n var attr = this.svgAttrs[k];\n for (var l = 0; l < this.keyHex.length; l++) {\n if (tag.getAttribute(attr) && tag.getAttribute(attr).toUpperCase() === this.keyHex[l]) {\n fixups.push({\n node: tag,\n attr: attr,\n index: l\n });\n }\n }\n }\n }\n }\n if (DEBUG) console.log(\"calcSvgFixups end\");\n\n return fixups;\n }\n }, {\n key: 'applySvgFixups',\n value: function applySvgFixups(fixups) {\n if (DEBUG) console.log(\"applySvgFixups start for \" + fixups);\n for (var i = 0; i < fixups.length; i++) {\n var svgFixup = fixups[i];\n svgFixup.node.setAttribute(svgFixup.attr, this.colors[svgFixup.index]);\n }\n if (DEBUG) console.log(\"applySvgFixups end\");\n }\n }]);\n return Tinter;\n}();\n\nif (global.singletonTinter === undefined) {\n global.singletonTinter = new Tinter();\n}\nexports.default = global.singletonTinter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=Tinter.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _Terms = require('./Terms');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar IdentityAuthClient = function () {\n /**\n * Creates a new identity auth client\n * @param {string} identityUrl The URL to contact the identity server with.\n * When provided, this class will operate solely within memory, refusing to\n * persist any information such as tokens. Default null (not provided).\n */\n function IdentityAuthClient() {\n var identityUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n (0, _classCallCheck3.default)(this, IdentityAuthClient);\n\n this.accessToken = null;\n this.authEnabled = true;\n\n if (identityUrl) {\n // XXX: We shouldn't have to create a whole new MatrixClient just to\n // do identity server auth. The functions don't take an identity URL\n // though, and making all of them take one could lead to developer\n // confusion about what the idBaseUrl does on a client. Therefore, we\n // just make a new client and live with it.\n this.tempClient = (0, _matrixJsSdk.createClient)({\n baseUrl: \"\", // invalid by design\n idBaseUrl: identityUrl\n });\n } else {\n // Indicates that we're using the real client, not some workaround.\n this.tempClient = null;\n }\n }\n\n (0, _createClass3.default)(IdentityAuthClient, [{\n key: '_writeToken',\n value: function _writeToken() {\n if (this.tempClient) return; // temporary client: ignore\n window.localStorage.setItem(\"mx_is_access_token\", this.accessToken);\n }\n }, {\n key: '_readToken',\n value: function _readToken() {\n if (this.tempClient) return null; // temporary client: ignore\n return window.localStorage.getItem(\"mx_is_access_token\");\n }\n }, {\n key: 'hasCredentials',\n value: function hasCredentials() {\n return this.accessToken != null; // undef or null\n }\n\n // Returns a promise that resolves to the access_token string from the IS\n\n }, {\n key: 'getAccessToken',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {\n var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref2$check = _ref2.check,\n check = _ref2$check === undefined ? true : _ref2$check;\n\n var token;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (this.authEnabled) {\n _context.next = 2;\n break;\n }\n\n return _context.abrupt('return', null);\n\n case 2:\n token = this.accessToken;\n\n if (!token) {\n token = this._readToken();\n }\n\n if (token) {\n _context.next = 10;\n break;\n }\n\n _context.next = 7;\n return (0, _bluebird.resolve)(this.registerForToken(check));\n\n case 7:\n token = _context.sent;\n\n if (token) {\n this.accessToken = token;\n this._writeToken();\n }\n return _context.abrupt('return', token);\n\n case 10:\n if (!check) {\n _context.next = 24;\n break;\n }\n\n _context.prev = 11;\n _context.next = 14;\n return (0, _bluebird.resolve)(this._checkToken(token));\n\n case 14:\n _context.next = 24;\n break;\n\n case 16:\n _context.prev = 16;\n _context.t0 = _context['catch'](11);\n\n if (!(_context.t0 instanceof _Terms.TermsNotSignedError)) {\n _context.next = 20;\n break;\n }\n\n throw _context.t0;\n\n case 20:\n _context.next = 22;\n return (0, _bluebird.resolve)(this.registerForToken());\n\n case 22:\n token = _context.sent;\n\n if (token) {\n this.accessToken = token;\n this._writeToken();\n }\n\n case 24:\n return _context.abrupt('return', token);\n\n case 25:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[11, 16]]);\n }));\n\n function getAccessToken(_x2) {\n return _ref.apply(this, arguments);\n }\n\n return getAccessToken;\n }()\n }, {\n key: '_checkToken',\n value: function () {\n var _ref3 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(token) {\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.prev = 0;\n _context2.next = 3;\n return (0, _bluebird.resolve)(this._matrixClient.getIdentityAccount(token));\n\n case 3:\n _context2.next = 13;\n break;\n\n case 5:\n _context2.prev = 5;\n _context2.t0 = _context2['catch'](0);\n\n if (!(_context2.t0.errcode === \"M_TERMS_NOT_SIGNED\")) {\n _context2.next = 12;\n break;\n }\n\n console.log(\"Identity Server requires new terms to be agreed to\");\n _context2.next = 11;\n return (0, _bluebird.resolve)((0, _Terms.startTermsFlow)([new _Terms.Service(_matrixJsSdk.SERVICE_TYPES.IS, this._matrixClient.getIdentityServerUrl(), token)]));\n\n case 11:\n return _context2.abrupt('return');\n\n case 12:\n throw _context2.t0;\n\n case 13:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, this, [[0, 5]]);\n }));\n\n function _checkToken(_x4) {\n return _ref3.apply(this, arguments);\n }\n\n return _checkToken;\n }()\n }, {\n key: 'registerForToken',\n value: function () {\n var _ref4 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() {\n var check = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n\n var hsOpenIdToken, _ref5, identityAccessToken;\n\n return _regenerator2.default.wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n _context3.prev = 0;\n _context3.next = 3;\n return (0, _bluebird.resolve)(_MatrixClientPeg2.default.get().getOpenIdToken());\n\n case 3:\n hsOpenIdToken = _context3.sent;\n _context3.next = 6;\n return (0, _bluebird.resolve)(this._matrixClient.registerWithIdentityServer(hsOpenIdToken));\n\n case 6:\n _ref5 = _context3.sent;\n identityAccessToken = _ref5.access_token;\n\n if (!check) {\n _context3.next = 11;\n break;\n }\n\n _context3.next = 11;\n return (0, _bluebird.resolve)(this._checkToken(identityAccessToken));\n\n case 11:\n return _context3.abrupt('return', identityAccessToken);\n\n case 14:\n _context3.prev = 14;\n _context3.t0 = _context3['catch'](0);\n\n if (!(_context3.t0.cors === \"rejected\" || _context3.t0.httpStatus === 404)) {\n _context3.next = 20;\n break;\n }\n\n // Assume IS only supports deprecated v1 API for now\n // TODO: Remove this path once v2 is only supported version\n // See https://github.com/vector-im/riot-web/issues/10443\n console.warn(\"IS doesn't support v2 auth\");\n this.authEnabled = false;\n return _context3.abrupt('return');\n\n case 20:\n throw _context3.t0;\n\n case 21:\n case 'end':\n return _context3.stop();\n }\n }\n }, _callee3, this, [[0, 14]]);\n }));\n\n function registerForToken(_x5) {\n return _ref4.apply(this, arguments);\n }\n\n return registerForToken;\n }()\n }, {\n key: '_matrixClient',\n get: function get() {\n return this.tempClient ? this.tempClient : _MatrixClientPeg2.default.get();\n }\n }]);\n return IdentityAuthClient;\n}(); /*\n Copyright 2019 The Matrix.org Foundation C.I.C.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nexports.default = IdentityAuthClient;\nmodule.exports = exports['default'];\n//# sourceMappingURL=IdentityAuthClient.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _promise = require(\"babel-runtime/core-js/promise\");\n\nvar _promise2 = _interopRequireDefault(_promise);\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\nA countdown timer, exposing a promise api.\nA timer starts in a non-started state,\nand needs to be started by calling `start()`` on it first.\n\nTimers can be `abort()`-ed which makes the promise reject prematurely.\n\nOnce a timer is finished or aborted, it can't be started again\n(because the promise should not be replaced). Instead, create\na new one through `clone()` or `cloneIfRun()`.\n*/\nvar Timer = function () {\n function Timer(timeout) {\n (0, _classCallCheck3.default)(this, Timer);\n\n this._timeout = timeout;\n this._onTimeout = this._onTimeout.bind(this);\n this._setNotStarted();\n }\n\n (0, _createClass3.default)(Timer, [{\n key: \"_setNotStarted\",\n value: function _setNotStarted() {\n var _this = this;\n\n this._timerHandle = null;\n this._startTs = null;\n this._promise = new _promise2.default(function (resolve, reject) {\n _this._resolve = resolve;\n _this._reject = reject;\n }).finally(function () {\n _this._timerHandle = null;\n });\n }\n }, {\n key: \"_onTimeout\",\n value: function _onTimeout() {\n var now = Date.now();\n var elapsed = now - this._startTs;\n if (elapsed >= this._timeout) {\n this._resolve();\n this._setNotStarted();\n } else {\n var delta = this._timeout - elapsed;\n this._timerHandle = setTimeout(this._onTimeout, delta);\n }\n }\n }, {\n key: \"changeTimeout\",\n value: function changeTimeout(timeout) {\n if (timeout === this._timeout) {\n return;\n }\n var isSmallerTimeout = timeout < this._timeout;\n this._timeout = timeout;\n if (this.isRunning() && isSmallerTimeout) {\n clearTimeout(this._timerHandle);\n this._onTimeout();\n }\n }\n\n /**\n * if not started before, starts the timer.\n * @returns {Timer} the same timer\n */\n\n }, {\n key: \"start\",\n value: function start() {\n if (!this.isRunning()) {\n this._startTs = Date.now();\n this._timerHandle = setTimeout(this._onTimeout, this._timeout);\n }\n return this;\n }\n\n /**\n * (re)start the timer. If it's running, reset the timeout. If not, start it.\n * @returns {Timer} the same timer\n */\n\n }, {\n key: \"restart\",\n value: function restart() {\n if (this.isRunning()) {\n // don't clearTimeout here as this method\n // can be called in fast succession,\n // instead just take note and compare\n // when the already running timeout expires\n this._startTs = Date.now();\n return this;\n } else {\n return this.start();\n }\n }\n\n /**\n * if the timer is running, abort it,\n * and reject the promise for this timer.\n * @returns {Timer} the same timer\n */\n\n }, {\n key: \"abort\",\n value: function abort() {\n if (this.isRunning()) {\n clearTimeout(this._timerHandle);\n this._reject(new Error(\"Timer was aborted.\"));\n this._setNotStarted();\n }\n return this;\n }\n\n /**\n *promise that will resolve when the timer elapses,\n *or is rejected when abort is called\n *@return {Promise}\n */\n\n }, {\n key: \"finished\",\n value: function finished() {\n return this._promise;\n }\n }, {\n key: \"isRunning\",\n value: function isRunning() {\n return this._timerHandle !== null;\n }\n }]);\n return Timer;\n}();\n\nexports.default = Timer;\nmodule.exports = exports[\"default\"];\n//# sourceMappingURL=Timer.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.MENTION_BADGE_STATES = exports.BADGE_STATES = exports.MUTE = exports.MENTIONS_ONLY = exports.ALL_MESSAGES = exports.ALL_MESSAGES_LOUD = undefined;\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nexports.shouldShowNotifBadge = shouldShowNotifBadge;\nexports.shouldShowMentionBadge = shouldShowMentionBadge;\nexports.countRoomsWithNotif = countRoomsWithNotif;\nexports.aggregateNotificationCount = aggregateNotificationCount;\nexports.getRoomHasBadge = getRoomHasBadge;\nexports.getRoomNotifsState = getRoomNotifsState;\nexports.setRoomNotifsState = setRoomNotifsState;\nexports.getUnreadNotificationCount = getUnreadNotificationCount;\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _pushprocessor = require('matrix-js-sdk/lib/pushprocessor');\n\nvar _pushprocessor2 = _interopRequireDefault(_pushprocessor);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar ALL_MESSAGES_LOUD = exports.ALL_MESSAGES_LOUD = 'all_messages_loud'; /*\n Copyright 2016 OpenMarket Ltd\n Copyright 2019 The Matrix.org Foundation C.I.C.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nvar ALL_MESSAGES = exports.ALL_MESSAGES = 'all_messages';\nvar MENTIONS_ONLY = exports.MENTIONS_ONLY = 'mentions_only';\nvar MUTE = exports.MUTE = 'mute';\n\nvar BADGE_STATES = exports.BADGE_STATES = [ALL_MESSAGES, ALL_MESSAGES_LOUD];\nvar MENTION_BADGE_STATES = exports.MENTION_BADGE_STATES = [].concat(BADGE_STATES, [MENTIONS_ONLY]);\n\nfunction shouldShowNotifBadge(roomNotifState) {\n return BADGE_STATES.includes(roomNotifState);\n}\n\nfunction shouldShowMentionBadge(roomNotifState) {\n return MENTION_BADGE_STATES.includes(roomNotifState);\n}\n\nfunction countRoomsWithNotif(rooms) {\n return rooms.reduce(function (result, room, index) {\n var roomNotifState = getRoomNotifsState(room.roomId);\n var highlight = room.getUnreadNotificationCount('highlight') > 0;\n var notificationCount = room.getUnreadNotificationCount();\n\n var notifBadges = notificationCount > 0 && shouldShowNotifBadge(roomNotifState);\n var mentionBadges = highlight && shouldShowMentionBadge(roomNotifState);\n var isInvite = room.hasMembershipState(_MatrixClientPeg2.default.get().credentials.userId, 'invite');\n var badges = notifBadges || mentionBadges || isInvite;\n\n if (badges) {\n result.count++;\n if (highlight) {\n result.highlight = true;\n }\n }\n return result;\n }, { count: 0, highlight: false });\n}\n\nfunction aggregateNotificationCount(rooms) {\n return rooms.reduce(function (result, room, index) {\n var roomNotifState = getRoomNotifsState(room.roomId);\n var highlight = room.getUnreadNotificationCount('highlight') > 0;\n var notificationCount = room.getUnreadNotificationCount();\n\n var notifBadges = notificationCount > 0 && shouldShowNotifBadge(roomNotifState);\n var mentionBadges = highlight && shouldShowMentionBadge(roomNotifState);\n var badges = notifBadges || mentionBadges;\n\n if (badges) {\n result.count += notificationCount;\n if (highlight) {\n result.highlight = true;\n }\n }\n return result;\n }, { count: 0, highlight: false });\n}\n\nfunction getRoomHasBadge(room) {\n var roomNotifState = getRoomNotifsState(room.roomId);\n var highlight = room.getUnreadNotificationCount('highlight') > 0;\n var notificationCount = room.getUnreadNotificationCount();\n\n var notifBadges = notificationCount > 0 && shouldShowNotifBadge(roomNotifState);\n var mentionBadges = highlight && shouldShowMentionBadge(roomNotifState);\n\n return notifBadges || mentionBadges;\n}\n\nfunction getRoomNotifsState(roomId) {\n if (_MatrixClientPeg2.default.get().isGuest()) return ALL_MESSAGES;\n\n // look through the override rules for a rule affecting this room:\n // if one exists, it will take precedence.\n var muteRule = findOverrideMuteRule(roomId);\n if (muteRule) {\n return MUTE;\n }\n\n // for everything else, look at the room rule.\n var roomRule = null;\n try {\n roomRule = _MatrixClientPeg2.default.get().getRoomPushRule('global', roomId);\n } catch (err) {\n // Possible that the client doesn't have pushRules yet. If so, it\n // hasn't started eiher, so indicate that this room is not notifying.\n return null;\n }\n\n // XXX: We have to assume the default is to notify for all messages\n // (in particular this will be 'wrong' for one to one rooms because\n // they will notify loudly for all messages)\n if (!roomRule || !roomRule.enabled) return ALL_MESSAGES;\n\n // a mute at the room level will still allow mentions\n // to notify\n if (isMuteRule(roomRule)) return MENTIONS_ONLY;\n\n var actionsObject = _pushprocessor2.default.actionListToActionsObject(roomRule.actions);\n if (actionsObject.tweaks.sound) return ALL_MESSAGES_LOUD;\n\n return null;\n}\n\nfunction setRoomNotifsState(roomId, newState) {\n if (newState === MUTE) {\n return setRoomNotifsStateMuted(roomId);\n } else {\n return setRoomNotifsStateUnmuted(roomId, newState);\n }\n}\n\nfunction getUnreadNotificationCount(room) {\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n\n var notificationCount = room.getUnreadNotificationCount(type);\n\n // Check notification counts in the old room just in case there's some lost\n // there. We only go one level down to avoid performance issues, and theory\n // is that 1st generation rooms will have already been read by the 3rd generation.\n var createEvent = room.currentState.getStateEvents(\"m.room.create\", \"\");\n if (createEvent && createEvent.getContent()['predecessor']) {\n var oldRoomId = createEvent.getContent()['predecessor']['room_id'];\n var oldRoom = _MatrixClientPeg2.default.get().getRoom(oldRoomId);\n if (oldRoom) {\n // We only ever care if there's highlights in the old room. No point in\n // notifying the user for unread messages because they would have extreme\n // difficulty changing their notification preferences away from \"All Messages\"\n // and \"Noisy\".\n notificationCount += oldRoom.getUnreadNotificationCount(\"highlight\");\n }\n }\n\n return notificationCount;\n}\n\nfunction setRoomNotifsStateMuted(roomId) {\n var cli = _MatrixClientPeg2.default.get();\n var promises = [];\n\n // delete the room rule\n var roomRule = cli.getRoomPushRule('global', roomId);\n if (roomRule) {\n promises.push(cli.deletePushRule('global', 'room', roomRule.rule_id));\n }\n\n // add/replace an override rule to squelch everything in this room\n // NB. We use the room ID as the name of this rule too, although this\n // is an override rule, not a room rule: it still pertains to this room\n // though, so using the room ID as the rule ID is logical and prevents\n // duplicate copies of the rule.\n promises.push(cli.addPushRule('global', 'override', roomId, {\n conditions: [{\n kind: 'event_match',\n key: 'room_id',\n pattern: roomId\n }],\n actions: ['dont_notify']\n }));\n\n return _bluebird2.default.all(promises);\n}\n\nfunction setRoomNotifsStateUnmuted(roomId, newState) {\n var cli = _MatrixClientPeg2.default.get();\n var promises = [];\n\n var overrideMuteRule = findOverrideMuteRule(roomId);\n if (overrideMuteRule) {\n promises.push(cli.deletePushRule('global', 'override', overrideMuteRule.rule_id));\n }\n\n if (newState === 'all_messages') {\n var roomRule = cli.getRoomPushRule('global', roomId);\n if (roomRule) {\n promises.push(cli.deletePushRule('global', 'room', roomRule.rule_id));\n }\n } else if (newState === 'mentions_only') {\n promises.push(cli.addPushRule('global', 'room', roomId, {\n actions: ['dont_notify']\n }));\n // https://matrix.org/jira/browse/SPEC-400\n promises.push(cli.setPushRuleEnabled('global', 'room', roomId, true));\n } else if ('all_messages_loud') {\n promises.push(cli.addPushRule('global', 'room', roomId, {\n actions: ['notify', {\n set_tweak: 'sound',\n value: 'default'\n }]\n }));\n // https://matrix.org/jira/browse/SPEC-400\n promises.push(cli.setPushRuleEnabled('global', 'room', roomId, true));\n }\n\n return _bluebird2.default.all(promises);\n}\n\nfunction findOverrideMuteRule(roomId) {\n if (!_MatrixClientPeg2.default.get().pushRules || !_MatrixClientPeg2.default.get().pushRules['global'] || !_MatrixClientPeg2.default.get().pushRules['global'].override) {\n return null;\n }\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(_MatrixClientPeg2.default.get().pushRules['global'].override), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var rule = _step.value;\n\n if (isRuleForRoom(roomId, rule)) {\n if (isMuteRule(rule) && rule.enabled) {\n return rule;\n }\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return null;\n}\n\nfunction isRuleForRoom(roomId, rule) {\n if (rule.conditions.length !== 1) {\n return false;\n }\n var cond = rule.conditions[0];\n return cond.kind === 'event_match' && cond.key === 'room_id' && cond.pattern === roomId;\n}\n\nfunction isMuteRule(rule) {\n return rule.actions.length === 1 && rule.actions[0] === 'dont_notify';\n}\n//# sourceMappingURL=RoomNotifs.js.map","/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.UploadCanceledError = undefined;\n\nvar _create = require('babel-runtime/core-js/object/create');\n\nvar _create2 = _interopRequireDefault(_create);\n\nvar _setPrototypeOf = require('babel-runtime/core-js/object/set-prototype-of');\n\nvar _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);\n\nvar _from = require('babel-runtime/core-js/array/from');\n\nvar _from2 = _interopRequireDefault(_from);\n\nvar _construct = require('babel-runtime/core-js/reflect/construct');\n\nvar _construct2 = _interopRequireDefault(_construct);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');\n\nvar _slicedToArray3 = _interopRequireDefault(_slicedToArray2);\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\n/**\n * Load a file into a newly created image element.\n *\n * @param {File} imageFile The file to load in an image element.\n * @return {Promise} A promise that resolves with the html image element.\n */\nvar loadImageElement = function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(imageFile) {\n var img, objectUrl, imgPromise, parsePromise, headers, _ref2, _ref3, hidpi, width, height;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n // Load the file into an html element\n img = document.createElement(\"img\");\n objectUrl = URL.createObjectURL(imageFile);\n imgPromise = new _bluebird2.default(function (resolve, reject) {\n img.onload = function () {\n URL.revokeObjectURL(objectUrl);\n resolve(img);\n };\n img.onerror = function (e) {\n reject(e);\n };\n });\n\n img.src = objectUrl;\n\n // check for hi-dpi PNGs and fudge display resolution as needed.\n // this is mainly needed for macOS screencaps\n parsePromise = void 0;\n\n if (imageFile.type === \"image/png\") {\n // in practice macOS happens to order the chunks so they fall in\n // the first 0x1000 bytes (thanks to a massive ICC header).\n // Thus we could slice the file down to only sniff the first 0x1000\n // bytes (but this makes extractPngChunks choke on the corrupt file)\n headers = imageFile; //.slice(0, 0x1000);\n\n parsePromise = readFileAsArrayBuffer(headers).then(function (arrayBuffer) {\n var buffer = new Uint8Array(arrayBuffer);\n var chunks = (0, _pngChunksExtract2.default)(buffer);\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(chunks), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var chunk = _step.value;\n\n if (chunk.name === 'pHYs') {\n if (chunk.data.byteLength !== PHYS_HIDPI.length) return;\n var _hidpi = chunk.data.every(function (val, i) {\n return val === PHYS_HIDPI[i];\n });\n return _hidpi;\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return false;\n });\n }\n\n _context.next = 8;\n return (0, _bluebird.resolve)(_bluebird2.default.all([parsePromise, imgPromise]));\n\n case 8:\n _ref2 = _context.sent;\n _ref3 = (0, _slicedToArray3.default)(_ref2, 1);\n hidpi = _ref3[0];\n width = hidpi ? img.width >> 1 : img.width;\n height = hidpi ? img.height >> 1 : img.height;\n return _context.abrupt('return', { width: width, height: height, img: img });\n\n case 14:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n return function loadImageElement(_x) {\n return _ref.apply(this, arguments);\n };\n}();\n\n/**\n * Read the metadata for an image file and create and upload a thumbnail of the image.\n *\n * @param {MatrixClient} matrixClient A matrixClient to upload the thumbnail with.\n * @param {String} roomId The ID of the room the image will be uploaded in.\n * @param {File} imageFile The image to read and thumbnail.\n * @return {Promise} A promise that resolves with the attachment info.\n */\n\n\nvar _extend = require('./extend');\n\nvar _extend2 = _interopRequireDefault(_extend);\n\nvar _dispatcher = require('./dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _index = require('./index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('./languageHandler');\n\nvar _Modal = require('./Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _RoomViewStore = require('./stores/RoomViewStore');\n\nvar _RoomViewStore2 = _interopRequireDefault(_RoomViewStore);\n\nvar _browserEncryptAttachment = require('browser-encrypt-attachment');\n\nvar _browserEncryptAttachment2 = _interopRequireDefault(_browserEncryptAttachment);\n\nvar _pngChunksExtract = require('png-chunks-extract');\n\nvar _pngChunksExtract2 = _interopRequireDefault(_pngChunksExtract);\n\nrequire('blueimp-canvas-to-blob');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _extendableBuiltin(cls) {\n function ExtendableBuiltin() {\n var instance = (0, _construct2.default)(cls, (0, _from2.default)(arguments));\n (0, _setPrototypeOf2.default)(instance, (0, _getPrototypeOf2.default)(this));\n return instance;\n }\n\n ExtendableBuiltin.prototype = (0, _create2.default)(cls.prototype, {\n constructor: {\n value: cls,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n\n if (_setPrototypeOf2.default) {\n (0, _setPrototypeOf2.default)(ExtendableBuiltin, cls);\n } else {\n ExtendableBuiltin.__proto__ = cls;\n }\n\n return ExtendableBuiltin;\n}\n\n// Polyfill for Canvas.toBlob API using Canvas.toDataURL\n\n\nvar MAX_WIDTH = 800;\nvar MAX_HEIGHT = 600;\n\n// scraped out of a macOS hidpi (5660ppm) screenshot png\n// 5669 px (x-axis) , 5669 px (y-axis) , per metre\nvar PHYS_HIDPI = [0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01];\n\nvar UploadCanceledError = exports.UploadCanceledError = function (_extendableBuiltin2) {\n (0, _inherits3.default)(UploadCanceledError, _extendableBuiltin2);\n\n function UploadCanceledError() {\n (0, _classCallCheck3.default)(this, UploadCanceledError);\n return (0, _possibleConstructorReturn3.default)(this, (UploadCanceledError.__proto__ || (0, _getPrototypeOf2.default)(UploadCanceledError)).apply(this, arguments));\n }\n\n return UploadCanceledError;\n}(_extendableBuiltin(Error));\n\n/**\n * Create a thumbnail for a image DOM element.\n * The image will be smaller than MAX_WIDTH and MAX_HEIGHT.\n * The thumbnail will have the same aspect ratio as the original.\n * Draws the element into a canvas using CanvasRenderingContext2D.drawImage\n * Then calls Canvas.toBlob to get a blob object for the image data.\n *\n * Since it needs to calculate the dimensions of the source image and the\n * thumbnailed image it returns an info object filled out with information\n * about the original image and the thumbnail.\n *\n * @param {HTMLElement} element The element to thumbnail.\n * @param {integer} inputWidth The width of the image in the input element.\n * @param {integer} inputHeight the width of the image in the input element.\n * @param {String} mimeType The mimeType to save the blob as.\n * @return {Promise} A promise that resolves with an object with an info key\n * and a thumbnail key.\n */\n\n\nfunction createThumbnail(element, inputWidth, inputHeight, mimeType) {\n var deferred = _bluebird2.default.defer();\n\n var targetWidth = inputWidth;\n var targetHeight = inputHeight;\n if (targetHeight > MAX_HEIGHT) {\n targetWidth = Math.floor(targetWidth * (MAX_HEIGHT / targetHeight));\n targetHeight = MAX_HEIGHT;\n }\n if (targetWidth > MAX_WIDTH) {\n targetHeight = Math.floor(targetHeight * (MAX_WIDTH / targetWidth));\n targetWidth = MAX_WIDTH;\n }\n\n var canvas = document.createElement(\"canvas\");\n canvas.width = targetWidth;\n canvas.height = targetHeight;\n canvas.getContext(\"2d\").drawImage(element, 0, 0, targetWidth, targetHeight);\n canvas.toBlob(function (thumbnail) {\n deferred.resolve({\n info: {\n thumbnail_info: {\n w: targetWidth,\n h: targetHeight,\n mimetype: thumbnail.type,\n size: thumbnail.size\n },\n w: inputWidth,\n h: inputHeight\n },\n thumbnail: thumbnail\n });\n }, mimeType);\n\n return deferred.promise;\n}function infoForImageFile(matrixClient, roomId, imageFile) {\n var thumbnailType = \"image/png\";\n if (imageFile.type == \"image/jpeg\") {\n thumbnailType = \"image/jpeg\";\n }\n\n var imageInfo = void 0;\n return loadImageElement(imageFile).then(function (r) {\n return createThumbnail(r.img, r.width, r.height, thumbnailType);\n }).then(function (result) {\n imageInfo = result.info;\n return uploadFile(matrixClient, roomId, result.thumbnail);\n }).then(function (result) {\n imageInfo.thumbnail_url = result.url;\n imageInfo.thumbnail_file = result.file;\n return imageInfo;\n });\n}\n\n/**\n * Load a file into a newly created video element.\n *\n * @param {File} videoFile The file to load in an video element.\n * @return {Promise} A promise that resolves with the video image element.\n */\nfunction loadVideoElement(videoFile) {\n var deferred = _bluebird2.default.defer();\n\n // Load the file into an html element\n var video = document.createElement(\"video\");\n\n var reader = new FileReader();\n reader.onload = function (e) {\n video.src = e.target.result;\n\n // Once ready, returns its size\n // Wait until we have enough data to thumbnail the first frame.\n video.onloadeddata = function () {\n deferred.resolve(video);\n };\n video.onerror = function (e) {\n deferred.reject(e);\n };\n };\n reader.onerror = function (e) {\n deferred.reject(e);\n };\n reader.readAsDataURL(videoFile);\n\n return deferred.promise;\n}\n\n/**\n * Read the metadata for a video file and create and upload a thumbnail of the video.\n *\n * @param {MatrixClient} matrixClient A matrixClient to upload the thumbnail with.\n * @param {String} roomId The ID of the room the video will be uploaded to.\n * @param {File} videoFile The video to read and thumbnail.\n * @return {Promise} A promise that resolves with the attachment info.\n */\nfunction infoForVideoFile(matrixClient, roomId, videoFile) {\n var thumbnailType = \"image/jpeg\";\n\n var videoInfo = void 0;\n return loadVideoElement(videoFile).then(function (video) {\n return createThumbnail(video, video.videoWidth, video.videoHeight, thumbnailType);\n }).then(function (result) {\n videoInfo = result.info;\n return uploadFile(matrixClient, roomId, result.thumbnail);\n }).then(function (result) {\n videoInfo.thumbnail_url = result.url;\n videoInfo.thumbnail_file = result.file;\n return videoInfo;\n });\n}\n\n/**\n * Read the file as an ArrayBuffer.\n * @param {File} file The file to read\n * @return {Promise} A promise that resolves with an ArrayBuffer when the file\n * is read.\n */\nfunction readFileAsArrayBuffer(file) {\n var deferred = _bluebird2.default.defer();\n var reader = new FileReader();\n reader.onload = function (e) {\n deferred.resolve(e.target.result);\n };\n reader.onerror = function (e) {\n deferred.reject(e);\n };\n reader.readAsArrayBuffer(file);\n return deferred.promise;\n}\n\n/**\n * Upload the file to the content repository.\n * If the room is encrypted then encrypt the file before uploading.\n *\n * @param {MatrixClient} matrixClient The matrix client to upload the file with.\n * @param {String} roomId The ID of the room being uploaded to.\n * @param {File} file The file to upload.\n * @param {Function?} progressHandler optional callback to be called when a chunk of\n * data is uploaded.\n * @return {Promise} A promise that resolves with an object.\n * If the file is unencrypted then the object will have a \"url\" key.\n * If the file is encrypted then the object will have a \"file\" key.\n */\nfunction uploadFile(matrixClient, roomId, file, progressHandler) {\n if (matrixClient.isRoomEncrypted(roomId)) {\n // If the room is encrypted then encrypt the file before uploading it.\n // First read the file into memory.\n var canceled = false;\n var uploadPromise = void 0;\n var encryptInfo = void 0;\n var prom = readFileAsArrayBuffer(file).then(function (data) {\n if (canceled) throw new UploadCanceledError();\n // Then encrypt the file.\n return _browserEncryptAttachment2.default.encryptAttachment(data);\n }).then(function (encryptResult) {\n if (canceled) throw new UploadCanceledError();\n // Record the information needed to decrypt the attachment.\n encryptInfo = encryptResult.info;\n // Pass the encrypted data as a Blob to the uploader.\n var blob = new Blob([encryptResult.data]);\n uploadPromise = matrixClient.uploadContent(blob, {\n progressHandler: progressHandler,\n includeFilename: false\n });\n\n return uploadPromise;\n }).then(function (url) {\n // If the attachment is encrypted then bundle the URL along\n // with the information needed to decrypt the attachment and\n // add it under a file key.\n encryptInfo.url = url;\n if (file.type) {\n encryptInfo.mimetype = file.type;\n }\n return { \"file\": encryptInfo };\n });\n prom.abort = function () {\n canceled = true;\n if (uploadPromise) _MatrixClientPeg2.default.get().cancelUpload(uploadPromise);\n };\n return prom;\n } else {\n var basePromise = matrixClient.uploadContent(file, {\n progressHandler: progressHandler\n });\n var promise1 = basePromise.then(function (url) {\n // If the attachment isn't encrypted then include the URL directly.\n return { \"url\": url };\n });\n // XXX: copy over the abort method to the new promise\n promise1.abort = basePromise.abort;\n return promise1;\n }\n}\n\nvar ContentMessages = function () {\n function ContentMessages() {\n (0, _classCallCheck3.default)(this, ContentMessages);\n\n this.inprogress = [];\n this.nextId = 0;\n this._mediaConfig = null;\n }\n\n (0, _createClass3.default)(ContentMessages, [{\n key: '_isFileSizeAcceptable',\n value: function _isFileSizeAcceptable(file) {\n if (this._mediaConfig !== null && this._mediaConfig[\"m.upload.size\"] !== undefined && file.size > this._mediaConfig[\"m.upload.size\"]) {\n return false;\n }\n return true;\n }\n }, {\n key: '_ensureMediaConfigFetched',\n value: function _ensureMediaConfigFetched() {\n var _this2 = this;\n\n if (this._mediaConfig !== null) return;\n\n console.log(\"[Media Config] Fetching\");\n return _MatrixClientPeg2.default.get().getMediaConfig().then(function (config) {\n console.log(\"[Media Config] Fetched config:\", config);\n return config;\n }).catch(function () {\n // Media repo can't or won't report limits, so provide an empty object (no limits).\n console.log(\"[Media Config] Could not fetch config, so not limiting uploads.\");\n return {};\n }).then(function (config) {\n _this2._mediaConfig = config;\n });\n }\n }, {\n key: 'sendStickerContentToRoom',\n value: function sendStickerContentToRoom(url, roomId, info, text, matrixClient) {\n return _MatrixClientPeg2.default.get().sendStickerMessage(roomId, url, info, text).catch(function (e) {\n console.warn('Failed to send content with URL ' + url + ' to room ' + roomId, e);\n throw e;\n });\n }\n }, {\n key: 'getUploadLimit',\n value: function getUploadLimit() {\n if (this._mediaConfig !== null && this._mediaConfig[\"m.upload.size\"] !== undefined) {\n return this._mediaConfig[\"m.upload.size\"];\n } else {\n return null;\n }\n }\n }, {\n key: 'sendContentListToRoom',\n value: function () {\n var _ref4 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(files, roomId, matrixClient) {\n var _this3 = this;\n\n var isQuoting, QuestionDialog, shouldUpload, tooBigFiles, okFiles, i, UploadFailureDialog, uploadFailureDialogPromise, shouldContinue, UploadConfirmDialog, uploadAll, _loop, _i, _ret;\n\n return _regenerator2.default.wrap(function _callee2$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n if (!matrixClient.isGuest()) {\n _context3.next = 3;\n break;\n }\n\n _dispatcher2.default.dispatch({ action: 'require_registration' });\n return _context3.abrupt('return');\n\n case 3:\n isQuoting = Boolean(_RoomViewStore2.default.getQuotingEvent());\n\n if (!isQuoting) {\n _context3.next = 11;\n break;\n }\n\n QuestionDialog = _index2.default.getComponent(\"dialogs.QuestionDialog\");\n _context3.next = 8;\n return (0, _bluebird.resolve)(new _bluebird2.default(function (resolve) {\n _Modal2.default.createTrackedDialog('Upload Reply Warning', '', QuestionDialog, {\n title: (0, _languageHandler._t)('Replying With Files'),\n description: React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)('At this time it is not possible to reply with a file. ' + 'Would you like to upload this file without replying?')\n ),\n hasCancelButton: true,\n button: (0, _languageHandler._t)(\"Continue\"),\n onFinished: function onFinished(shouldUpload) {\n resolve(shouldUpload);\n }\n });\n }));\n\n case 8:\n shouldUpload = _context3.sent;\n\n if (shouldUpload) {\n _context3.next = 11;\n break;\n }\n\n return _context3.abrupt('return');\n\n case 11:\n _context3.next = 13;\n return (0, _bluebird.resolve)(this._ensureMediaConfigFetched());\n\n case 13:\n tooBigFiles = [];\n okFiles = [];\n\n\n for (i = 0; i < files.length; ++i) {\n if (this._isFileSizeAcceptable(files[i])) {\n okFiles.push(files[i]);\n } else {\n tooBigFiles.push(files[i]);\n }\n }\n\n if (!(tooBigFiles.length > 0)) {\n _context3.next = 24;\n break;\n }\n\n UploadFailureDialog = _index2.default.getComponent(\"dialogs.UploadFailureDialog\");\n uploadFailureDialogPromise = new _bluebird2.default(function (resolve) {\n _Modal2.default.createTrackedDialog('Upload Failure', '', UploadFailureDialog, {\n badFiles: tooBigFiles,\n totalFiles: files.length,\n contentMessages: _this3,\n onFinished: function onFinished(shouldContinue) {\n resolve(shouldContinue);\n }\n });\n });\n _context3.next = 21;\n return (0, _bluebird.resolve)(uploadFailureDialogPromise);\n\n case 21:\n shouldContinue = _context3.sent;\n\n if (shouldContinue) {\n _context3.next = 24;\n break;\n }\n\n return _context3.abrupt('return');\n\n case 24:\n UploadConfirmDialog = _index2.default.getComponent(\"dialogs.UploadConfirmDialog\");\n uploadAll = false;\n _loop = /*#__PURE__*/_regenerator2.default.mark(function _loop(_i) {\n var file, _shouldContinue;\n\n return _regenerator2.default.wrap(function _loop$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n file = okFiles[_i];\n\n if (uploadAll) {\n _context2.next = 7;\n break;\n }\n\n _context2.next = 4;\n return (0, _bluebird.resolve)(new _bluebird2.default(function (resolve) {\n _Modal2.default.createTrackedDialog('Upload Files confirmation', '', UploadConfirmDialog, {\n file: file,\n currentIndex: _i,\n totalFiles: okFiles.length,\n onFinished: function onFinished(shouldContinue, shouldUploadAll) {\n if (shouldUploadAll) {\n uploadAll = true;\n }\n resolve(shouldContinue);\n }\n });\n }));\n\n case 4:\n _shouldContinue = _context2.sent;\n\n if (_shouldContinue) {\n _context2.next = 7;\n break;\n }\n\n return _context2.abrupt('return', 'break');\n\n case 7:\n _this3._sendContentToRoom(file, roomId, matrixClient);\n\n case 8:\n case 'end':\n return _context2.stop();\n }\n }\n }, _loop, _this3);\n });\n _i = 0;\n\n case 28:\n if (!(_i < okFiles.length)) {\n _context3.next = 36;\n break;\n }\n\n return _context3.delegateYield(_loop(_i), 't0', 30);\n\n case 30:\n _ret = _context3.t0;\n\n if (!(_ret === 'break')) {\n _context3.next = 33;\n break;\n }\n\n return _context3.abrupt('break', 36);\n\n case 33:\n ++_i;\n _context3.next = 28;\n break;\n\n case 36:\n case 'end':\n return _context3.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function sendContentListToRoom(_x2, _x3, _x4) {\n return _ref4.apply(this, arguments);\n }\n\n return sendContentListToRoom;\n }()\n }, {\n key: '_sendContentToRoom',\n value: function _sendContentToRoom(file, roomId, matrixClient) {\n var _this4 = this;\n\n var content = {\n body: file.name || 'Attachment',\n info: {\n size: file.size\n }\n };\n\n // if we have a mime type for the file, add it to the message metadata\n if (file.type) {\n content.info.mimetype = file.type;\n }\n\n var def = _bluebird2.default.defer();\n if (file.type.indexOf('image/') == 0) {\n content.msgtype = 'm.image';\n infoForImageFile(matrixClient, roomId, file).then(function (imageInfo) {\n (0, _extend2.default)(content.info, imageInfo);\n def.resolve();\n }, function (error) {\n console.error(error);\n content.msgtype = 'm.file';\n def.resolve();\n });\n } else if (file.type.indexOf('audio/') == 0) {\n content.msgtype = 'm.audio';\n def.resolve();\n } else if (file.type.indexOf('video/') == 0) {\n content.msgtype = 'm.video';\n infoForVideoFile(matrixClient, roomId, file).then(function (videoInfo) {\n (0, _extend2.default)(content.info, videoInfo);\n def.resolve();\n }, function (error) {\n content.msgtype = 'm.file';\n def.resolve();\n });\n } else {\n content.msgtype = 'm.file';\n def.resolve();\n }\n\n var upload = {\n fileName: file.name || 'Attachment',\n roomId: roomId,\n total: 0,\n loaded: 0\n };\n this.inprogress.push(upload);\n _dispatcher2.default.dispatch({ action: 'upload_started' });\n\n // Focus the composer view\n _dispatcher2.default.dispatch({ action: 'focus_composer' });\n\n var error = void 0;\n\n function onProgress(ev) {\n upload.total = ev.total;\n upload.loaded = ev.loaded;\n _dispatcher2.default.dispatch({ action: 'upload_progress', upload: upload });\n }\n\n return def.promise.then(function () {\n // XXX: upload.promise must be the promise that\n // is returned by uploadFile as it has an abort()\n // method hacked onto it.\n upload.promise = uploadFile(matrixClient, roomId, file, onProgress);\n return upload.promise.then(function (result) {\n content.file = result.file;\n content.url = result.url;\n });\n }).then(function (url) {\n return matrixClient.sendMessage(roomId, content);\n }, function (err) {\n error = err;\n if (!upload.canceled) {\n var desc = (0, _languageHandler._t)(\"The file '%(fileName)s' failed to upload.\", { fileName: upload.fileName });\n if (err.http_status == 413) {\n desc = (0, _languageHandler._t)(\"The file '%(fileName)s' exceeds this homeserver's size limit for uploads\", { fileName: upload.fileName });\n }\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Upload failed', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Upload Failed'),\n description: desc\n });\n }\n }).finally(function () {\n var inprogressKeys = (0, _keys2.default)(_this4.inprogress);\n for (var i = 0; i < _this4.inprogress.length; ++i) {\n var k = inprogressKeys[i];\n if (_this4.inprogress[k].promise === upload.promise) {\n _this4.inprogress.splice(k, 1);\n break;\n }\n }\n if (error) {\n // 413: File was too big or upset the server in some way:\n // clear the media size limit so we fetch it again next time\n // we try to upload\n if (error && error.http_status === 413) {\n _this4._mediaConfig = null;\n }\n _dispatcher2.default.dispatch({ action: 'upload_failed', upload: upload, error: error });\n } else {\n _dispatcher2.default.dispatch({ action: 'upload_finished', upload: upload });\n _dispatcher2.default.dispatch({ action: 'message_sent' });\n }\n });\n }\n }, {\n key: 'getCurrentUploads',\n value: function getCurrentUploads() {\n return this.inprogress.filter(function (u) {\n return !u.canceled;\n });\n }\n }, {\n key: 'cancelUpload',\n value: function cancelUpload(promise) {\n var inprogressKeys = (0, _keys2.default)(this.inprogress);\n var upload = void 0;\n for (var i = 0; i < this.inprogress.length; ++i) {\n var k = inprogressKeys[i];\n if (this.inprogress[k].promise === promise) {\n upload = this.inprogress[k];\n break;\n }\n }\n if (upload) {\n upload.canceled = true;\n _MatrixClientPeg2.default.get().cancelUpload(upload.promise);\n _dispatcher2.default.dispatch({ action: 'upload_canceled', upload: upload });\n }\n }\n }], [{\n key: 'sharedInstance',\n value: function sharedInstance() {\n if (global.mx_ContentMessages === undefined) {\n global.mx_ContentMessages = new ContentMessages();\n }\n return global.mx_ContentMessages;\n }\n }]);\n return ContentMessages;\n}();\n\nexports.default = ContentMessages;\n//# sourceMappingURL=ContentMessages.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require(\"babel-runtime/core-js/object/get-prototype-of\");\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require(\"babel-runtime/helpers/possibleConstructorReturn\");\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require(\"babel-runtime/helpers/inherits\");\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require(\"react\");\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require(\"prop-types\");\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _ToggleSwitch = require(\"./ToggleSwitch\");\n\nvar _ToggleSwitch2 = _interopRequireDefault(_ToggleSwitch);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar LabelledToggleSwitch = function (_React$Component) {\n (0, _inherits3.default)(LabelledToggleSwitch, _React$Component);\n\n function LabelledToggleSwitch() {\n (0, _classCallCheck3.default)(this, LabelledToggleSwitch);\n return (0, _possibleConstructorReturn3.default)(this, (LabelledToggleSwitch.__proto__ || (0, _getPrototypeOf2.default)(LabelledToggleSwitch)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(LabelledToggleSwitch, [{\n key: \"render\",\n value: function render() {\n // This is a minimal version of a SettingsFlag\n\n var firstPart = _react2.default.createElement(\n \"span\",\n { className: \"mx_SettingsFlag_label\" },\n this.props.label\n );\n var secondPart = _react2.default.createElement(_ToggleSwitch2.default, { checked: this.props.value, disabled: this.props.disabled,\n onChange: this.props.onChange, \"aria-label\": this.props.label });\n\n if (this.props.toggleInFront) {\n var temp = firstPart;\n firstPart = secondPart;\n secondPart = temp;\n }\n\n return _react2.default.createElement(\n \"div\",\n { className: \"mx_SettingsFlag\" },\n firstPart,\n secondPart\n );\n }\n }]);\n return LabelledToggleSwitch;\n}(_react2.default.Component); /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nLabelledToggleSwitch.propTypes = {\n // The value for the toggle switch\n value: _propTypes2.default.bool.isRequired,\n\n // The function to call when the value changes\n onChange: _propTypes2.default.func.isRequired,\n\n // The translated label for the switch\n label: _propTypes2.default.string.isRequired,\n\n // Whether or not to disable the toggle switch\n disabled: _propTypes2.default.bool,\n\n // True to put the toggle in front of the label\n // Default false.\n toggleInFront: _propTypes2.default.bool\n};\nexports.default = LabelledToggleSwitch;\nmodule.exports = exports[\"default\"];\n//# sourceMappingURL=LabelledToggleSwitch.js.map","module.exports = \"img/spinner.0b29ec9.gif\";","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _bluebird = require('bluebird');\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar AutocompleteProvider = function () {\n function AutocompleteProvider(commandRegex, forcedCommandRegex) {\n (0, _classCallCheck3.default)(this, AutocompleteProvider);\n\n if (commandRegex) {\n if (!commandRegex.global) {\n throw new Error('commandRegex must have global flag set');\n }\n this.commandRegex = commandRegex;\n }\n if (forcedCommandRegex) {\n if (!forcedCommandRegex.global) {\n throw new Error('forcedCommandRegex must have global flag set');\n }\n this.forcedCommandRegex = forcedCommandRegex;\n }\n }\n\n (0, _createClass3.default)(AutocompleteProvider, [{\n key: 'destroy',\n value: function destroy() {}\n // stub\n\n\n /**\n * Of the matched commands in the query, returns the first that contains or is contained by the selection, or null.\n * @param {string} query The query string\n * @param {SelectionRange} selection Selection to search\n * @param {boolean} force True if the user is forcing completion\n * @return {object} { command, range } where both objects fields are null if no match\n */\n\n }, {\n key: 'getCurrentCommand',\n value: function getCurrentCommand(query, selection) {\n var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n var commandRegex = this.commandRegex;\n\n if (force && this.shouldForceComplete()) {\n commandRegex = this.forcedCommandRegex || /\\S+/g;\n }\n\n if (commandRegex == null) {\n return null;\n }\n\n commandRegex.lastIndex = 0;\n\n var match = void 0;\n while ((match = commandRegex.exec(query)) != null) {\n var start = match.index;\n var end = start + match[0].length;\n if (selection.start <= end && selection.end >= start) {\n return {\n command: match,\n range: {\n start: start,\n end: end\n }\n };\n }\n }\n return {\n command: null,\n range: {\n start: -1,\n end: -1\n }\n };\n }\n }, {\n key: 'getCompletions',\n value: function () {\n var _ref = (0, _bluebird.method)(function (query, selection) {\n var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n return [];\n });\n\n function getCompletions(_x2, _x3, _x4) {\n return _ref.apply(this, arguments);\n }\n\n return getCompletions;\n }()\n }, {\n key: 'getName',\n value: function getName() {\n return 'Default Provider';\n }\n }, {\n key: 'renderCompletions',\n value: function renderCompletions(completions) {\n console.error('stub; should be implemented in subclasses');\n return null;\n }\n\n // Whether we should provide completions even if triggered forcefully, without a sigil.\n\n }, {\n key: 'shouldForceComplete',\n value: function shouldForceComplete() {\n return false;\n }\n }]);\n return AutocompleteProvider;\n}(); /*\n Copyright 2016 Aviral Dasgupta\n Copyright 2017 Vector Creations Ltd\n Copyright 2017, 2018 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nexports.default = AutocompleteProvider;\nmodule.exports = exports['default'];\n//# sourceMappingURL=AutocompleteProvider.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PillCompletion = exports.TextualCompletion = undefined;\n\nvar _extends2 = require('babel-runtime/helpers/extends');\n\nvar _extends3 = _interopRequireDefault(_extends2);\n\nvar _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');\n\nvar _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* These were earlier stateless functional components but had to be converted\nsince we need to use refs/findDOMNode to access the underlying DOM node to focus the correct completion,\nsomething that is not entirely possible with stateless functional components. One could\npresumably wrap them in a
before rendering but I think this is the better way to do it.\n */\n\nvar TextualCompletion = exports.TextualCompletion = function (_React$Component) {\n (0, _inherits3.default)(TextualCompletion, _React$Component);\n\n function TextualCompletion() {\n (0, _classCallCheck3.default)(this, TextualCompletion);\n return (0, _possibleConstructorReturn3.default)(this, (TextualCompletion.__proto__ || (0, _getPrototypeOf2.default)(TextualCompletion)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(TextualCompletion, [{\n key: 'render',\n value: function render() {\n var _props = this.props,\n title = _props.title,\n subtitle = _props.subtitle,\n description = _props.description,\n className = _props.className,\n restProps = (0, _objectWithoutProperties3.default)(_props, ['title', 'subtitle', 'description', 'className']);\n\n return _react2.default.createElement(\n 'div',\n (0, _extends3.default)({ className: (0, _classnames2.default)('mx_Autocomplete_Completion_block', className) }, restProps),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_title' },\n title\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_subtitle' },\n subtitle\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_description' },\n description\n )\n );\n }\n }]);\n return TextualCompletion;\n}(_react2.default.Component); /*\n Copyright 2016 Aviral Dasgupta\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nTextualCompletion.propTypes = {\n title: _propTypes2.default.string,\n subtitle: _propTypes2.default.string,\n description: _propTypes2.default.string,\n className: _propTypes2.default.string\n};\n\nvar PillCompletion = exports.PillCompletion = function (_React$Component2) {\n (0, _inherits3.default)(PillCompletion, _React$Component2);\n\n function PillCompletion() {\n (0, _classCallCheck3.default)(this, PillCompletion);\n return (0, _possibleConstructorReturn3.default)(this, (PillCompletion.__proto__ || (0, _getPrototypeOf2.default)(PillCompletion)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(PillCompletion, [{\n key: 'render',\n value: function render() {\n var _props2 = this.props,\n title = _props2.title,\n subtitle = _props2.subtitle,\n description = _props2.description,\n initialComponent = _props2.initialComponent,\n className = _props2.className,\n restProps = (0, _objectWithoutProperties3.default)(_props2, ['title', 'subtitle', 'description', 'initialComponent', 'className']);\n\n return _react2.default.createElement(\n 'div',\n (0, _extends3.default)({ className: (0, _classnames2.default)('mx_Autocomplete_Completion_pill', className), role: 'option' }, restProps),\n initialComponent,\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_title' },\n title\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_subtitle' },\n subtitle\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_description' },\n description\n )\n );\n }\n }]);\n return PillCompletion;\n}(_react2.default.Component);\n\nPillCompletion.propTypes = {\n title: _propTypes2.default.string,\n subtitle: _propTypes2.default.string,\n description: _propTypes2.default.string,\n initialComponent: _propTypes2.default.element,\n className: _propTypes2.default.string\n};\n//# sourceMappingURL=Components.js.map","var def = require('./_object-dp').f;\nvar has = require('./_has');\nvar TAG = require('./_wks')('toStringTag');\n\nmodule.exports = function (it, tag, stat) {\n if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });\n};\n","// getting tag from 19.1.3.6 Object.prototype.toString()\nvar cof = require('./_cof');\nvar TAG = require('./_wks')('toStringTag');\n// ES3 wrong here\nvar ARG = cof(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (e) { /* empty */ }\n};\n\nmodule.exports = function (it) {\n var O, T, B;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T\n // builtinTag case\n : ARG ? cof(O)\n // ES3 arguments fallback\n : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;\n};\n","var $export = require('./_export');\nvar defined = require('./_defined');\nvar fails = require('./_fails');\nvar spaces = require('./_string-ws');\nvar space = '[' + spaces + ']';\nvar non = '\\u200b\\u0085';\nvar ltrim = RegExp('^' + space + space + '*');\nvar rtrim = RegExp(space + space + '*$');\n\nvar exporter = function (KEY, exec, ALIAS) {\n var exp = {};\n var FORCE = fails(function () {\n return !!spaces[KEY]() || non[KEY]() != non;\n });\n var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];\n if (ALIAS) exp[ALIAS] = fn;\n $export($export.P + $export.F * FORCE, 'String', exp);\n};\n\n// 1 -> String#trimLeft\n// 2 -> String#trimRight\n// 3 -> String#trim\nvar trim = exporter.trim = function (string, TYPE) {\n string = String(defined(string));\n if (TYPE & 1) string = string.replace(ltrim, '');\n if (TYPE & 2) string = string.replace(rtrim, '');\n return string;\n};\n\nmodule.exports = exporter;\n","module.exports = {};\n","var dP = require('./_object-dp');\nvar anObject = require('./_an-object');\nvar getKeys = require('./_object-keys');\n\nmodule.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = getKeys(Properties);\n var length = keys.length;\n var i = 0;\n var P;\n while (length > i) dP.f(O, P = keys[i++], Properties[P]);\n return O;\n};\n","var document = require('./_global').document;\nmodule.exports = document && document.documentElement;\n","module.exports = function (done, value) {\n return { value: value, done: !!done };\n};\n","exports.f = Object.getOwnPropertySymbols;\n","'use strict';\n\nvar _typeof2 = require('babel-runtime/helpers/typeof');\n\nvar _typeof3 = _interopRequireDefault(_typeof2);\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _stringify = require('babel-runtime/core-js/json/stringify');\n\nvar _stringify2 = _interopRequireDefault(_stringify);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _utils = require('./utils');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * @module pushprocessor\n */\n\nvar RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride'];\n\n// The default override rules to apply when calculating actions for an event. These\n// defaults apply under no other circumstances to avoid confusing the client with server\n// state. We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar DEFAULT_OVERRIDE_RULES = [{\n // For homeservers which don't support MSC1930 yet\n rule_id: \".m.rule.tombstone\",\n default: true,\n enabled: true,\n conditions: [{\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.room.tombstone\"\n }, {\n kind: \"event_match\",\n key: \"state_key\",\n pattern: \"\"\n }],\n actions: [\"notify\", {\n set_tweak: \"highlight\",\n value: true\n }]\n}, {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [{\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.reaction\"\n }],\n actions: [\"dont_notify\"]\n}];\n\n/**\n * Construct a Push Processor.\n * @constructor\n * @param {Object} client The Matrix client object to use\n */\nfunction PushProcessor(client) {\n var _this = this;\n\n var cachedGlobToRegex = {\n // $glob: RegExp,\n };\n\n var matchingRuleFromKindSet = function matchingRuleFromKindSet(ev, kindset, device) {\n for (var ruleKindIndex = 0; ruleKindIndex < RULEKINDS_IN_ORDER.length; ++ruleKindIndex) {\n var kind = RULEKINDS_IN_ORDER[ruleKindIndex];\n var ruleset = kindset[kind];\n\n for (var ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {\n var rule = ruleset[ruleIndex];\n if (!rule.enabled) {\n continue;\n }\n\n var rawrule = templateRuleToRaw(kind, rule, device);\n if (!rawrule) {\n continue;\n }\n\n if (_this.ruleMatchesEvent(rawrule, ev)) {\n rule.kind = kind;\n return rule;\n }\n }\n }\n return null;\n };\n\n var templateRuleToRaw = function templateRuleToRaw(kind, tprule, device) {\n var rawrule = {\n 'rule_id': tprule.rule_id,\n 'actions': tprule.actions,\n 'conditions': []\n };\n switch (kind) {\n case 'underride':\n case 'override':\n rawrule.conditions = tprule.conditions;\n break;\n case 'room':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'room_id',\n 'value': tprule.rule_id\n });\n break;\n case 'sender':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'user_id',\n 'value': tprule.rule_id\n });\n break;\n case 'content':\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'content.body',\n 'pattern': tprule.pattern\n });\n break;\n }\n if (device) {\n rawrule.conditions.push({\n 'kind': 'device',\n 'profile_tag': device\n });\n }\n return rawrule;\n };\n\n var eventFulfillsCondition = function eventFulfillsCondition(cond, ev) {\n var condition_functions = {\n \"event_match\": eventFulfillsEventMatchCondition,\n \"device\": eventFulfillsDeviceCondition,\n \"contains_display_name\": eventFulfillsDisplayNameCondition,\n \"room_member_count\": eventFulfillsRoomMemberCountCondition,\n \"sender_notification_permission\": eventFulfillsSenderNotifPermCondition\n };\n if (condition_functions[cond.kind]) {\n return condition_functions[cond.kind](cond, ev);\n }\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n };\n\n var eventFulfillsSenderNotifPermCondition = function eventFulfillsSenderNotifPermCondition(cond, ev) {\n var notifLevelKey = cond['key'];\n if (!notifLevelKey) {\n return false;\n }\n\n var room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender());\n };\n\n var eventFulfillsRoomMemberCountCondition = function eventFulfillsRoomMemberCountCondition(cond, ev) {\n if (!cond.is) {\n return false;\n }\n\n var room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n var memberCount = room.currentState.getJoinedMemberCount();\n\n var m = cond.is.match(/^([=<>]*)([0-9]*)$/);\n if (!m) {\n return false;\n }\n var ineq = m[1];\n var rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case '':\n case '==':\n return memberCount == rhs;\n case '<':\n return memberCount < rhs;\n case '>':\n return memberCount > rhs;\n case '<=':\n return memberCount <= rhs;\n case '>=':\n return memberCount >= rhs;\n default:\n return false;\n }\n };\n\n var eventFulfillsDisplayNameCondition = function eventFulfillsDisplayNameCondition(cond, ev) {\n var content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent();\n }\n if (!content || !content.body || typeof content.body != 'string') {\n return false;\n }\n\n var room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members || !room.currentState.getMember(client.credentials.userId)) {\n return false;\n }\n\n var displayName = room.currentState.getMember(client.credentials.userId).name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n var pat = new RegExp(\"(^|\\\\W)\" + (0, _utils.escapeRegExp)(displayName) + \"(\\\\W|$)\", 'i');\n return content.body.search(pat) > -1;\n };\n\n var eventFulfillsDeviceCondition = function eventFulfillsDeviceCondition(cond, ev) {\n return false; // XXX: Allow a profile tag to be set for the web client instance\n };\n\n var eventFulfillsEventMatchCondition = function eventFulfillsEventMatchCondition(cond, ev) {\n if (!cond.key) {\n return false;\n }\n\n var val = valueForDottedKey(cond.key, ev);\n if (!val || typeof val != 'string') {\n return false;\n }\n\n if (cond.value) {\n return cond.value === val;\n }\n\n var regex = void 0;\n\n if (cond.key == 'content.body') {\n regex = createCachedRegex('(^|\\\\W)', cond.pattern, '(\\\\W|$)');\n } else {\n regex = createCachedRegex('^', cond.pattern, '$');\n }\n\n return !!val.match(regex);\n };\n\n var createCachedRegex = function createCachedRegex(prefix, glob, suffix) {\n if (cachedGlobToRegex[glob]) {\n return cachedGlobToRegex[glob];\n }\n cachedGlobToRegex[glob] = new RegExp(prefix + (0, _utils.globToRegexp)(glob) + suffix, 'i');\n return cachedGlobToRegex[glob];\n };\n\n var valueForDottedKey = function valueForDottedKey(key, ev) {\n var parts = key.split('.');\n var val = void 0;\n\n // special-case the first component to deal with encrypted messages\n var firstPart = parts[0];\n if (firstPart == 'content') {\n val = ev.getContent();\n parts.shift();\n } else if (firstPart == 'type') {\n val = ev.getType();\n parts.shift();\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n while (parts.length > 0) {\n var thispart = parts.shift();\n if (!val[thispart]) {\n return null;\n }\n val = val[thispart];\n }\n return val;\n };\n\n var matchingRuleForEventWithRulesets = function matchingRuleForEventWithRulesets(ev, rulesets) {\n if (!rulesets || !rulesets.device) {\n return null;\n }\n if (ev.getSender() == client.credentials.userId) {\n return null;\n }\n\n var allDevNames = (0, _keys2.default)(rulesets.device);\n for (var i = 0; i < allDevNames.length; ++i) {\n var devname = allDevNames[i];\n var devrules = rulesets.device[devname];\n\n var matchingRule = matchingRuleFromKindSet(devrules, devname);\n if (matchingRule) {\n return matchingRule;\n }\n }\n return matchingRuleFromKindSet(ev, rulesets.global);\n };\n\n var pushActionsForEventAndRulesets = function pushActionsForEventAndRulesets(ev, rulesets) {\n var rule = matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n var actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == 'content';\n }\n\n return actionObj;\n };\n\n var applyRuleDefaults = function applyRuleDefaults(clientRuleset) {\n // Deep clone the object before we mutate it\n var ruleset = JSON.parse((0, _stringify2.default)(clientRuleset));\n\n if (!clientRuleset['global']) {\n clientRuleset['global'] = {};\n }\n if (!clientRuleset['global']['override']) {\n clientRuleset['global']['override'] = [];\n }\n\n // Apply default overrides\n var globalOverrides = clientRuleset['global']['override'];\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n var _loop = function _loop() {\n var override = _step.value;\n\n var existingRule = globalOverrides.find(function (r) {\n return r.rule_id === override.rule_id;\n });\n\n if (!existingRule) {\n var ruleId = override.rule_id;\n console.warn('Adding default global override for ' + ruleId);\n globalOverrides.push(override);\n }\n };\n\n for (var _iterator = (0, _getIterator3.default)(DEFAULT_OVERRIDE_RULES), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n _loop();\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return ruleset;\n };\n\n this.ruleMatchesEvent = function (rule, ev) {\n var ret = true;\n for (var i = 0; i < rule.conditions.length; ++i) {\n var cond = rule.conditions[i];\n ret &= eventFulfillsCondition(cond, ev);\n }\n //console.log(\"Rule \"+rule.rule_id+(ret ? \" matches\" : \" doesn't match\"));\n return ret;\n };\n\n /**\n * Get the user's push actions for the given event\n *\n * @param {module:models/event.MatrixEvent} ev\n *\n * @return {PushAction}\n */\n this.actionsForEvent = function (ev) {\n var rules = applyRuleDefaults(client.pushRules);\n return pushActionsForEventAndRulesets(ev, rules);\n };\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param {string} ruleId The ID of the rule to search for\n * @return {object} The push rule, or null if no such rule was found\n */\n this.getPushRuleById = function (ruleId) {\n var _arr = ['device', 'global'];\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var scope = _arr[_i];\n if (client.pushRules[scope] === undefined) continue;\n\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (0, _getIterator3.default)(RULEKINDS_IN_ORDER), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var kind = _step2.value;\n\n if (client.pushRules[scope][kind] === undefined) continue;\n\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = (0, _getIterator3.default)(client.pushRules[scope][kind]), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var rule = _step3.value;\n\n if (rule.rule_id === ruleId) return rule;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n return null;\n };\n}\n\n/**\n * Convert a list of actions into a object with the actions as keys and their values\n * eg. [ 'notify', { set_tweak: 'sound', value: 'default' } ]\n * becomes { notify: true, tweaks: { sound: 'default' } }\n * @param {array} actionlist The actions list\n *\n * @return {object} A object with key 'notify' (true or false) and an object of actions\n */\nPushProcessor.actionListToActionsObject = function (actionlist) {\n var actionobj = { 'notify': false, 'tweaks': {} };\n for (var i = 0; i < actionlist.length; ++i) {\n var action = actionlist[i];\n if (action === 'notify') {\n actionobj.notify = true;\n } else if ((typeof action === 'undefined' ? 'undefined' : (0, _typeof3.default)(action)) === 'object') {\n if (action.value === undefined) {\n action.value = true;\n }\n actionobj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionobj;\n};\n\n/**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param {object} incomingRules The client's existing push rules\n * @returns {object} The rewritten rules\n */\nPushProcessor.rewriteDefaultRules = function (incomingRules) {\n var newRules = JSON.parse((0, _stringify2.default)(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {};\n if (!newRules.global) newRules.global = {};\n if (!newRules.global.override) newRules.global.override = [];\n\n // Fix default override rules\n newRules.global.override = newRules.global.override.map(function (r) {\n var defaultRule = DEFAULT_OVERRIDE_RULES.find(function (d) {\n return d.rule_id === r.rule_id;\n });\n if (!defaultRule) return r;\n\n // Copy over the actions, default, and conditions. Don't touch the user's\n // preference.\n r.default = defaultRule.default;\n r.conditions = defaultRule.conditions;\n r.actions = defaultRule.actions;\n return r;\n });\n\n return newRules;\n};\n\n/**\n * @typedef {Object} PushAction\n * @type {Object}\n * @property {boolean} notify Whether this event should notify the user or not.\n * @property {Object} tweaks How this event should be notified.\n * @property {boolean} tweaks.highlight Whether this event should be highlighted\n * on the UI.\n * @property {boolean} tweaks.sound Whether this notification should produce a\n * noise.\n */\n\n/** The PushProcessor class. */\nmodule.exports = PushProcessor;\n//# sourceMappingURL=pushprocessor.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _bluebird = require(\"bluebird\");\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Represents the base class for all level handlers. This class performs no logic\n * and should be overridden.\n */\nvar SettingsHandler = function () {\n function SettingsHandler() {\n (0, _classCallCheck3.default)(this, SettingsHandler);\n }\n\n (0, _createClass3.default)(SettingsHandler, [{\n key: \"getValue\",\n\n /**\n * Gets the value for a particular setting at this level for a particular room.\n * If no room is applicable, the roomId may be null. The roomId may not be\n * applicable to this level and may be ignored by the handler.\n * @param {string} settingName The name of the setting.\n * @param {String} roomId The room ID to read from, may be null.\n * @returns {*} The setting value, or null if not found.\n */\n value: function getValue(settingName, roomId) {\n console.error(\"Invalid operation: getValue was not overridden\");\n return null;\n }\n\n /**\n * Sets the value for a particular setting at this level for a particular room.\n * If no room is applicable, the roomId may be null. The roomId may not be\n * applicable to this level and may be ignored by the handler. Setting a value\n * to null will cause the level to remove the value. The current user should be\n * able to set the value prior to calling this.\n * @param {string} settingName The name of the setting to change.\n * @param {String} roomId The room ID to set the value in, may be null.\n * @param {*} newValue The new value for the setting, may be null.\n * @returns {Promise} Resolves when the setting has been saved.\n */\n\n }, {\n key: \"setValue\",\n value: function setValue(settingName, roomId, newValue) {\n console.error(\"Invalid operation: setValue was not overridden\");\n return _bluebird2.default.reject();\n }\n\n /**\n * Determines if the current user is able to set the value of the given setting\n * in the given room at this level.\n * @param {string} settingName The name of the setting to check.\n * @param {String} roomId The room ID to check in, may be null\n * @returns {boolean} True if the setting can be set by the user, false otherwise.\n */\n\n }, {\n key: \"canSetValue\",\n value: function canSetValue(settingName, roomId) {\n return false;\n }\n\n /**\n * Determines if this level is supported on this device.\n * @returns {boolean} True if this level is supported on the current device.\n */\n\n }, {\n key: \"isSupported\",\n value: function isSupported() {\n return false;\n }\n }]);\n return SettingsHandler;\n}(); /*\n Copyright 2017 Travis Ralston\n Copyright 2019 New Vector Ltd.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nexports.default = SettingsHandler;\nmodule.exports = exports[\"default\"];\n//# sourceMappingURL=SettingsHandler.js.map","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _events = require('events');\n\nvar _events2 = _interopRequireDefault(_events);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Stores information about the widgets active in the app right now:\n * * What widget is set to remain always-on-screen, if any\n * Only one widget may be 'always on screen' at any one time.\n * * Negotiated capabilities for active apps\n */\n/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar ActiveWidgetStore = function (_EventEmitter) {\n (0, _inherits3.default)(ActiveWidgetStore, _EventEmitter);\n\n function ActiveWidgetStore() {\n (0, _classCallCheck3.default)(this, ActiveWidgetStore);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (ActiveWidgetStore.__proto__ || (0, _getPrototypeOf2.default)(ActiveWidgetStore)).call(this));\n\n _this._persistentWidgetId = null;\n\n // A list of negotiated capabilities for each widget, by ID\n // {\n // widgetId: [caps...],\n // }\n _this._capsByWidgetId = {};\n\n // A WidgetMessaging instance for each widget ID\n _this._widgetMessagingByWidgetId = {};\n\n // What room ID each widget is associated with (if it's a room widget)\n _this._roomIdByWidgetId = {};\n\n _this.onRoomStateEvents = _this.onRoomStateEvents.bind(_this);\n\n _this.dispatcherRef = null;\n return _this;\n }\n\n (0, _createClass3.default)(ActiveWidgetStore, [{\n key: 'start',\n value: function start() {\n _MatrixClientPeg2.default.get().on('RoomState.events', this.onRoomStateEvents);\n }\n }, {\n key: 'stop',\n value: function stop() {\n if (_MatrixClientPeg2.default.get()) {\n _MatrixClientPeg2.default.get().removeListener('RoomState.events', this.onRoomStateEvents);\n }\n this._capsByWidgetId = {};\n this._widgetMessagingByWidgetId = {};\n this._roomIdByWidgetId = {};\n }\n }, {\n key: 'onRoomStateEvents',\n value: function onRoomStateEvents(ev, state) {\n // XXX: This listens for state events in order to remove the active widget.\n // Everything else relies on views listening for events and calling setters\n // on this class which is terrible. This store should just listen for events\n // and keep itself up to date.\n if (ev.getType() !== 'im.vector.modular.widgets') return;\n\n if (ev.getStateKey() === this._persistentWidgetId) {\n this.destroyPersistentWidget(this._persistentWidgetId);\n }\n }\n }, {\n key: 'destroyPersistentWidget',\n value: function destroyPersistentWidget(id) {\n if (id !== this._persistentWidgetId) return;\n var toDeleteId = this._persistentWidgetId;\n\n this.setWidgetPersistence(toDeleteId, false);\n this.delWidgetMessaging(toDeleteId);\n this.delWidgetCapabilities(toDeleteId);\n this.delRoomId(toDeleteId);\n }\n }, {\n key: 'setWidgetPersistence',\n value: function setWidgetPersistence(widgetId, val) {\n if (this._persistentWidgetId === widgetId && !val) {\n this._persistentWidgetId = null;\n } else if (this._persistentWidgetId !== widgetId && val) {\n this._persistentWidgetId = widgetId;\n }\n this.emit('update');\n }\n }, {\n key: 'getWidgetPersistence',\n value: function getWidgetPersistence(widgetId) {\n return this._persistentWidgetId === widgetId;\n }\n }, {\n key: 'getPersistentWidgetId',\n value: function getPersistentWidgetId() {\n return this._persistentWidgetId;\n }\n }, {\n key: 'setWidgetCapabilities',\n value: function setWidgetCapabilities(widgetId, caps) {\n this._capsByWidgetId[widgetId] = caps;\n this.emit('update');\n }\n }, {\n key: 'widgetHasCapability',\n value: function widgetHasCapability(widgetId, cap) {\n return this._capsByWidgetId[widgetId] && this._capsByWidgetId[widgetId].includes(cap);\n }\n }, {\n key: 'delWidgetCapabilities',\n value: function delWidgetCapabilities(widgetId) {\n delete this._capsByWidgetId[widgetId];\n this.emit('update');\n }\n }, {\n key: 'setWidgetMessaging',\n value: function setWidgetMessaging(widgetId, wm) {\n // Stop any existing widget messaging first\n this.delWidgetMessaging(widgetId);\n this._widgetMessagingByWidgetId[widgetId] = wm;\n this.emit('update');\n }\n }, {\n key: 'getWidgetMessaging',\n value: function getWidgetMessaging(widgetId) {\n return this._widgetMessagingByWidgetId[widgetId];\n }\n }, {\n key: 'delWidgetMessaging',\n value: function delWidgetMessaging(widgetId) {\n if (this._widgetMessagingByWidgetId[widgetId]) {\n try {\n this._widgetMessagingByWidgetId[widgetId].stop();\n } catch (e) {\n console.error('Failed to stop listening for widgetMessaging events', e.message);\n }\n delete this._widgetMessagingByWidgetId[widgetId];\n this.emit('update');\n }\n }\n }, {\n key: 'getRoomId',\n value: function getRoomId(widgetId) {\n return this._roomIdByWidgetId[widgetId];\n }\n }, {\n key: 'setRoomId',\n value: function setRoomId(widgetId, roomId) {\n this._roomIdByWidgetId[widgetId] = roomId;\n this.emit('update');\n }\n }, {\n key: 'delRoomId',\n value: function delRoomId(widgetId) {\n delete this._roomIdByWidgetId[widgetId];\n this.emit('update');\n }\n }]);\n return ActiveWidgetStore;\n}(_events2.default);\n\nif (global.singletonActiveWidgetStore === undefined) {\n global.singletonActiveWidgetStore = new ActiveWidgetStore();\n}\nexports.default = global.singletonActiveWidgetStore;\nmodule.exports = exports['default'];\n//# sourceMappingURL=ActiveWidgetStore.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// derived from code from github.com/noeldelgado/gemini-scrollbar\n// Copyright (c) Noel Delgado
(pixelia.me)\nfunction getScrollbarWidth(alternativeOverflow) {\n var div = document.createElement('div');\n div.className = 'mx_AutoHideScrollbar'; //to get width of css scrollbar\n div.style.position = 'absolute';\n div.style.top = '-9999px';\n div.style.width = '100px';\n div.style.height = '100px';\n div.style.overflow = \"scroll\";\n if (alternativeOverflow) {\n div.style.overflow = alternativeOverflow;\n }\n div.style.msOverflowStyle = '-ms-autohiding-scrollbar';\n document.body.appendChild(div);\n var scrollbarWidth = div.offsetWidth - div.clientWidth;\n document.body.removeChild(div);\n return scrollbarWidth;\n} /*\n Copyright 2018 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nfunction install() {\n var scrollbarWidth = getScrollbarWidth();\n if (scrollbarWidth !== 0) {\n var hasForcedOverlayScrollbar = getScrollbarWidth('overlay') === 0;\n // overflow: overlay on webkit doesn't auto hide the scrollbar\n if (hasForcedOverlayScrollbar) {\n document.body.classList.add(\"mx_scrollbar_overlay_noautohide\");\n } else {\n document.body.classList.add(\"mx_scrollbar_nooverlay\");\n var style = document.createElement('style');\n style.type = 'text/css';\n style.innerText = 'body.mx_scrollbar_nooverlay { --scrollbar-width: ' + scrollbarWidth + 'px; }';\n document.head.appendChild(style);\n }\n }\n}\n\nvar installBodyClassesIfNeeded = function () {\n var installed = false;\n return function () {\n if (!installed) {\n install();\n installed = true;\n }\n };\n}();\n\nvar AutoHideScrollbar = function (_React$Component) {\n (0, _inherits3.default)(AutoHideScrollbar, _React$Component);\n\n function AutoHideScrollbar(props) {\n (0, _classCallCheck3.default)(this, AutoHideScrollbar);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (AutoHideScrollbar.__proto__ || (0, _getPrototypeOf2.default)(AutoHideScrollbar)).call(this, props));\n\n _this.onOverflow = _this.onOverflow.bind(_this);\n _this.onUnderflow = _this.onUnderflow.bind(_this);\n _this._collectContainerRef = _this._collectContainerRef.bind(_this);\n _this._needsOverflowListener = null;\n return _this;\n }\n\n (0, _createClass3.default)(AutoHideScrollbar, [{\n key: 'onOverflow',\n value: function onOverflow() {\n this.containerRef.classList.add(\"mx_AutoHideScrollbar_overflow\");\n this.containerRef.classList.remove(\"mx_AutoHideScrollbar_underflow\");\n }\n }, {\n key: 'onUnderflow',\n value: function onUnderflow() {\n this.containerRef.classList.remove(\"mx_AutoHideScrollbar_overflow\");\n this.containerRef.classList.add(\"mx_AutoHideScrollbar_underflow\");\n }\n }, {\n key: 'checkOverflow',\n value: function checkOverflow() {\n if (!this._needsOverflowListener) {\n return;\n }\n if (this.containerRef.scrollHeight > this.containerRef.clientHeight) {\n this.onOverflow();\n } else {\n this.onUnderflow();\n }\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this.checkOverflow();\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n installBodyClassesIfNeeded();\n this._needsOverflowListener = document.body.classList.contains(\"mx_scrollbar_nooverlay\");\n this.checkOverflow();\n }\n }, {\n key: '_collectContainerRef',\n value: function _collectContainerRef(ref) {\n if (ref && !this.containerRef) {\n this.containerRef = ref;\n }\n if (this.props.wrappedRef) {\n this.props.wrappedRef(ref);\n }\n }\n }, {\n key: 'getScrollTop',\n value: function getScrollTop() {\n return this.containerRef.scrollTop;\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2.default.createElement(\n 'div',\n {\n ref: this._collectContainerRef,\n style: this.props.style,\n className: [\"mx_AutoHideScrollbar\", this.props.className].join(\" \"),\n onScroll: this.props.onScroll,\n onWheel: this.props.onWheel\n },\n _react2.default.createElement(\n 'div',\n { className: 'mx_AutoHideScrollbar_offset' },\n this.props.children\n )\n );\n }\n }]);\n return AutoHideScrollbar;\n}(_react2.default.Component);\n\nexports.default = AutoHideScrollbar;\nmodule.exports = exports['default'];\n//# sourceMappingURL=AutoHideScrollbar.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');\n\nvar _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _index = require('../../../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('../../../languageHandler');\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _dispatcher = require('../../../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _DateUtils = require('../../../DateUtils');\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _Permalinks = require('../../../utils/permalinks/Permalinks');\n\nvar _SettingsStore = require('../../../settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// This component does no cycle detection, simply because the only way to make such a cycle would be to\n// craft event_id's, using a homeserver that generates predictable event IDs; even then the impact would\n// be low as each event being loaded (after the first) is triggered by an explicit user action.\nvar ReplyThread = function (_React$Component) {\n (0, _inherits3.default)(ReplyThread, _React$Component);\n\n function ReplyThread(props, context) {\n (0, _classCallCheck3.default)(this, ReplyThread);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (ReplyThread.__proto__ || (0, _getPrototypeOf2.default)(ReplyThread)).call(this, props, context));\n\n _this.onRoomRedaction = function (ev, room) {\n if (_this.unmounted) return;\n\n // If one of the events we are rendering gets redacted, force a re-render\n if (_this.state.events.some(function (event) {\n return event.getId() === ev.getId();\n })) {\n _this.forceUpdate();\n }\n };\n\n _this.state = {\n // The loaded events to be rendered as linear-replies\n events: [],\n\n // The latest loaded event which has not yet been shown\n loadedEv: null,\n // Whether the component is still loading more events\n loading: true,\n\n // Whether as error was encountered fetching a replied to event.\n err: false\n };\n\n _this.onQuoteClick = _this.onQuoteClick.bind(_this);\n _this.canCollapse = _this.canCollapse.bind(_this);\n _this.collapse = _this.collapse.bind(_this);\n return _this;\n }\n\n (0, _createClass3.default)(ReplyThread, [{\n key: 'componentWillMount',\n value: function componentWillMount() {\n this.unmounted = false;\n this.room = this.context.matrixClient.getRoom(this.props.parentEv.getRoomId());\n this.room.on(\"Room.redaction\", this.onRoomRedaction);\n // same event handler as Room.redaction as for both we just do forceUpdate\n this.room.on(\"Room.redactionCancelled\", this.onRoomRedaction);\n this.initialize();\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this.props.onHeightChanged();\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n this.unmounted = true;\n if (this.room) {\n this.room.removeListener(\"Room.redaction\", this.onRoomRedaction);\n this.room.removeListener(\"Room.redactionCancelled\", this.onRoomRedaction);\n }\n }\n }, {\n key: 'initialize',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {\n var parentEv, ev;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n parentEv = this.props.parentEv;\n // at time of making this component we checked that props.parentEv has a parentEventId\n\n _context.next = 3;\n return (0, _bluebird.resolve)(this.getEvent(ReplyThread.getParentEventId(parentEv)));\n\n case 3:\n ev = _context.sent;\n\n if (!this.unmounted) {\n _context.next = 6;\n break;\n }\n\n return _context.abrupt('return');\n\n case 6:\n\n if (ev) {\n this.setState({\n events: [ev]\n }, this.loadNextEvent);\n } else {\n this.setState({ err: true });\n }\n\n case 7:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function initialize() {\n return _ref.apply(this, arguments);\n }\n\n return initialize;\n }()\n }, {\n key: 'loadNextEvent',\n value: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {\n var ev, inReplyToEventId, loadedEv;\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n if (!this.unmounted) {\n _context2.next = 2;\n break;\n }\n\n return _context2.abrupt('return');\n\n case 2:\n ev = this.state.events[0];\n inReplyToEventId = ReplyThread.getParentEventId(ev);\n\n if (inReplyToEventId) {\n _context2.next = 7;\n break;\n }\n\n this.setState({\n loading: false\n });\n return _context2.abrupt('return');\n\n case 7:\n _context2.next = 9;\n return (0, _bluebird.resolve)(this.getEvent(inReplyToEventId));\n\n case 9:\n loadedEv = _context2.sent;\n\n if (!this.unmounted) {\n _context2.next = 12;\n break;\n }\n\n return _context2.abrupt('return');\n\n case 12:\n\n if (loadedEv) {\n this.setState({ loadedEv: loadedEv });\n } else {\n this.setState({ err: true });\n }\n\n case 13:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function loadNextEvent() {\n return _ref2.apply(this, arguments);\n }\n\n return loadNextEvent;\n }()\n }, {\n key: 'getEvent',\n value: function () {\n var _ref3 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(eventId) {\n var event;\n return _regenerator2.default.wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n event = this.room.findEventById(eventId);\n\n if (!event) {\n _context3.next = 3;\n break;\n }\n\n return _context3.abrupt('return', event);\n\n case 3:\n _context3.prev = 3;\n _context3.next = 6;\n return (0, _bluebird.resolve)(this.context.matrixClient.getEventTimeline(this.room.getUnfilteredTimelineSet(), eventId));\n\n case 6:\n _context3.next = 11;\n break;\n\n case 8:\n _context3.prev = 8;\n _context3.t0 = _context3['catch'](3);\n return _context3.abrupt('return', null);\n\n case 11:\n return _context3.abrupt('return', this.room.findEventById(eventId));\n\n case 12:\n case 'end':\n return _context3.stop();\n }\n }\n }, _callee3, this, [[3, 8]]);\n }));\n\n function getEvent(_x) {\n return _ref3.apply(this, arguments);\n }\n\n return getEvent;\n }()\n }, {\n key: 'canCollapse',\n value: function canCollapse() {\n return this.state.events.length > 1;\n }\n }, {\n key: 'collapse',\n value: function collapse() {\n this.initialize();\n }\n }, {\n key: 'onQuoteClick',\n value: function onQuoteClick() {\n var events = [this.state.loadedEv].concat((0, _toConsumableArray3.default)(this.state.events));\n\n this.setState({\n loadedEv: null,\n events: events\n }, this.loadNextEvent);\n\n _dispatcher2.default.dispatch({ action: 'focus_composer' });\n }\n }, {\n key: 'render',\n value: function render() {\n var _this2 = this;\n\n var header = null;\n\n if (this.state.err) {\n header = _react2.default.createElement(\n 'blockquote',\n { className: 'mx_ReplyThread mx_ReplyThread_error' },\n (0, _languageHandler._t)('Unable to load event that was replied to, ' + 'it either does not exist or you do not have permission to view it.')\n );\n } else if (this.state.loadedEv) {\n var ev = this.state.loadedEv;\n var Pill = _index2.default.getComponent('elements.Pill');\n var room = this.context.matrixClient.getRoom(ev.getRoomId());\n header = _react2.default.createElement(\n 'blockquote',\n { className: 'mx_ReplyThread' },\n (0, _languageHandler._t)('In reply to ', {}, {\n 'a': function a(sub) {\n return _react2.default.createElement(\n 'a',\n { onClick: _this2.onQuoteClick, className: 'mx_ReplyThread_show' },\n sub\n );\n },\n 'pill': _react2.default.createElement(Pill, { type: Pill.TYPE_USER_MENTION, room: room,\n url: (0, _Permalinks.makeUserPermalink)(ev.getSender()), shouldShowPillAvatar: true })\n })\n );\n } else if (this.state.loading) {\n var Spinner = _index2.default.getComponent(\"elements.Spinner\");\n header = _react2.default.createElement(Spinner, { w: 16, h: 16 });\n }\n\n var EventTile = _index2.default.getComponent('views.rooms.EventTile');\n var DateSeparator = _index2.default.getComponent('messages.DateSeparator');\n var evTiles = this.state.events.map(function (ev) {\n var dateSep = null;\n\n if ((0, _DateUtils.wantsDateSeparator)(_this2.props.parentEv.getDate(), ev.getDate())) {\n dateSep = _react2.default.createElement(\n 'a',\n { href: _this2.props.url },\n _react2.default.createElement(DateSeparator, { ts: ev.getTs() })\n );\n }\n\n return _react2.default.createElement(\n 'blockquote',\n { className: 'mx_ReplyThread', key: ev.getId() },\n dateSep,\n _react2.default.createElement(EventTile, {\n mxEvent: ev,\n tileShape: 'reply',\n onHeightChanged: _this2.props.onHeightChanged,\n permalinkCreator: _this2.props.permalinkCreator,\n isRedacted: ev.isRedacted(),\n isTwelveHour: _SettingsStore2.default.getValue(\"showTwelveHourTimestamps\") })\n );\n });\n\n return _react2.default.createElement(\n 'div',\n null,\n _react2.default.createElement(\n 'div',\n null,\n header\n ),\n _react2.default.createElement(\n 'div',\n null,\n evTiles\n )\n );\n }\n }], [{\n key: 'getParentEventId',\n value: function getParentEventId(ev) {\n if (!ev || ev.isRedacted()) return;\n\n // XXX: For newer relations (annotations, replacements, etc.), we now\n // have a `getRelation` helper on the event, and you might assume it\n // could be used here for replies as well... However, the helper\n // currently assumes the relation has a `rel_type`, which older replies\n // do not, so this block is left as-is for now.\n var mRelatesTo = ev.getWireContent()['m.relates_to'];\n if (mRelatesTo && mRelatesTo['m.in_reply_to']) {\n var mInReplyTo = mRelatesTo['m.in_reply_to'];\n if (mInReplyTo && mInReplyTo['event_id']) return mInReplyTo['event_id'];\n }\n }\n\n // Part of Replies fallback support\n\n }, {\n key: 'stripPlainReply',\n value: function stripPlainReply(body) {\n // Removes lines beginning with `> ` until you reach one that doesn't.\n var lines = body.split('\\n');\n while (lines.length && lines[0].startsWith('> ')) {\n lines.shift();\n } // Reply fallback has a blank line after it, so remove it to prevent leading newline\n if (lines[0] === '') lines.shift();\n return lines.join('\\n');\n }\n\n // Part of Replies fallback support\n\n }, {\n key: 'stripHTMLReply',\n value: function stripHTMLReply(html) {\n return html.replace(/^[\\s\\S]+?<\\/mx-reply>/, '');\n }\n\n // Part of Replies fallback support\n\n }, {\n key: 'getNestedReplyText',\n value: function getNestedReplyText(ev, permalinkCreator) {\n if (!ev) return null;\n\n var _ev$getContent = ev.getContent(),\n body = _ev$getContent.body,\n html = _ev$getContent.formatted_body;\n\n if (this.getParentEventId(ev)) {\n if (body) body = this.stripPlainReply(body);\n if (html) html = this.stripHTMLReply(html);\n }\n\n var evLink = permalinkCreator.forEvent(ev.getId());\n var userLink = (0, _Permalinks.makeUserPermalink)(ev.getSender());\n var mxid = ev.getSender();\n\n // This fallback contains text that is explicitly EN.\n switch (ev.getContent().msgtype) {\n case 'm.text':\n case 'm.notice':\n {\n html = 'In reply to ' + mxid + '' + ('
' + (html || body) + '
');\n var lines = body.trim().split('\\n');\n if (lines.length > 0) {\n lines[0] = '<' + mxid + '> ' + lines[0];\n body = lines.map(function (line) {\n return '> ' + line;\n }).join('\\n') + '\\n\\n';\n }\n break;\n }\n case 'm.image':\n html = 'In reply to ' + mxid + '' + '
sent an image.
';\n body = '> <' + mxid + '> sent an image.\\n\\n';\n break;\n case 'm.video':\n html = 'In reply to ' + mxid + '' + '
sent a video.
';\n body = '> <' + mxid + '> sent a video.\\n\\n';\n break;\n case 'm.audio':\n html = 'In reply to ' + mxid + '' + '
sent an audio file.
';\n body = '> <' + mxid + '> sent an audio file.\\n\\n';\n break;\n case 'm.file':\n html = 'In reply to ' + mxid + '' + '
sent a file.
';\n body = '> <' + mxid + '> sent a file.\\n\\n';\n break;\n case 'm.emote':\n {\n html = 'In reply to * ' + ('' + mxid + '
' + (html || body) + '
');\n var _lines = body.trim().split('\\n');\n if (_lines.length > 0) {\n _lines[0] = '* <' + mxid + '> ' + _lines[0];\n body = _lines.map(function (line) {\n return '> ' + line;\n }).join('\\n') + '\\n\\n';\n }\n break;\n }\n default:\n return null;\n }\n\n return { body: body, html: html };\n }\n }, {\n key: 'makeReplyMixIn',\n value: function makeReplyMixIn(ev) {\n if (!ev) return {};\n return {\n 'm.relates_to': {\n 'm.in_reply_to': {\n 'event_id': ev.getId()\n }\n }\n };\n }\n }, {\n key: 'makeThread',\n value: function makeThread(parentEv, onHeightChanged, permalinkCreator, ref) {\n if (!ReplyThread.getParentEventId(parentEv)) {\n return _react2.default.createElement('div', null);\n }\n return _react2.default.createElement(ReplyThread, { parentEv: parentEv, onHeightChanged: onHeightChanged,\n ref: ref, permalinkCreator: permalinkCreator });\n }\n }]);\n return ReplyThread;\n}(_react2.default.Component); /*\n Copyright 2017 New Vector Ltd\n Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n\nReplyThread.propTypes = {\n // the latest event in this chain of replies\n parentEv: _propTypes2.default.instanceOf(_matrixJsSdk.MatrixEvent),\n // called when the ReplyThread contents has changed, including EventTiles thereof\n onHeightChanged: _propTypes2.default.func.isRequired,\n permalinkCreator: _propTypes2.default.instanceOf(_Permalinks.RoomPermalinkCreator).isRequired\n};\nReplyThread.contextTypes = {\n matrixClient: _propTypes2.default.instanceOf(_matrixJsSdk.MatrixClient).isRequired\n};\nexports.default = ReplyThread;\nmodule.exports = exports['default'];\n//# sourceMappingURL=ReplyThread.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _freeze = require('babel-runtime/core-js/object/freeze');\n\nvar _freeze2 = _interopRequireDefault(_freeze);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _index = require('../../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _dispatcher = require('../../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _ratelimitedfunc = require('../../ratelimitedfunc');\n\nvar _ratelimitedfunc2 = _interopRequireDefault(_ratelimitedfunc);\n\nvar _GroupAddressPicker = require('../../GroupAddressPicker');\n\nvar _GroupStore = require('../../stores/GroupStore');\n\nvar _GroupStore2 = _interopRequireDefault(_GroupStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar RightPanel = function (_React$Component) {\n (0, _inherits3.default)(RightPanel, _React$Component);\n (0, _createClass3.default)(RightPanel, null, [{\n key: 'propTypes',\n get: function get() {\n return {\n roomId: _propTypes2.default.string, // if showing panels for a given room, this is set\n groupId: _propTypes2.default.string, // if showing panels for a given group, this is set\n user: _propTypes2.default.object\n };\n }\n }, {\n key: 'contextTypes',\n get: function get() {\n return {\n matrixClient: _propTypes2.default.instanceOf(_matrixJsSdk.MatrixClient)\n };\n }\n }]);\n\n function RightPanel(props, context) {\n (0, _classCallCheck3.default)(this, RightPanel);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (RightPanel.__proto__ || (0, _getPrototypeOf2.default)(RightPanel)).call(this, props, context));\n\n _this.state = {\n phase: _this._getPhaseFromProps(),\n isUserPrivilegedInGroup: null\n };\n _this.onAction = _this.onAction.bind(_this);\n _this.onRoomStateMember = _this.onRoomStateMember.bind(_this);\n _this.onGroupStoreUpdated = _this.onGroupStoreUpdated.bind(_this);\n _this.onInviteToGroupButtonClick = _this.onInviteToGroupButtonClick.bind(_this);\n _this.onAddRoomToGroupButtonClick = _this.onAddRoomToGroupButtonClick.bind(_this);\n\n _this._delayedUpdate = new _ratelimitedfunc2.default(function () {\n _this.forceUpdate();\n }, 500);\n return _this;\n }\n\n (0, _createClass3.default)(RightPanel, [{\n key: '_getPhaseFromProps',\n value: function _getPhaseFromProps() {\n if (this.props.groupId) {\n return RightPanel.Phase.GroupMemberList;\n } else if (this.props.user) {\n return RightPanel.Phase.RoomMemberInfo;\n } else {\n return RightPanel.Phase.RoomMemberList;\n }\n }\n }, {\n key: 'componentWillMount',\n value: function componentWillMount() {\n this.dispatcherRef = _dispatcher2.default.register(this.onAction);\n var cli = this.context.matrixClient;\n cli.on(\"RoomState.members\", this.onRoomStateMember);\n this._initGroupStore(this.props.groupId);\n if (this.props.user) {\n this.setState({ member: this.props.user });\n }\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n _dispatcher2.default.unregister(this.dispatcherRef);\n if (this.context.matrixClient) {\n this.context.matrixClient.removeListener(\"RoomState.members\", this.onRoomStateMember);\n }\n this._unregisterGroupStore(this.props.groupId);\n }\n }, {\n key: 'componentWillReceiveProps',\n value: function componentWillReceiveProps(newProps) {\n if (newProps.groupId !== this.props.groupId) {\n this._unregisterGroupStore(this.props.groupId);\n this._initGroupStore(newProps.groupId);\n }\n }\n }, {\n key: '_initGroupStore',\n value: function _initGroupStore(groupId) {\n if (!groupId) return;\n _GroupStore2.default.registerListener(groupId, this.onGroupStoreUpdated);\n }\n }, {\n key: '_unregisterGroupStore',\n value: function _unregisterGroupStore() {\n _GroupStore2.default.unregisterListener(this.onGroupStoreUpdated);\n }\n }, {\n key: 'onGroupStoreUpdated',\n value: function onGroupStoreUpdated() {\n this.setState({\n isUserPrivilegedInGroup: _GroupStore2.default.isUserPrivileged(this.props.groupId)\n });\n }\n }, {\n key: 'onInviteToGroupButtonClick',\n value: function onInviteToGroupButtonClick() {\n var _this2 = this;\n\n (0, _GroupAddressPicker.showGroupInviteDialog)(this.props.groupId).then(function () {\n _this2.setState({\n phase: RightPanel.Phase.GroupMemberList\n });\n });\n }\n }, {\n key: 'onAddRoomToGroupButtonClick',\n value: function onAddRoomToGroupButtonClick() {\n var _this3 = this;\n\n (0, _GroupAddressPicker.showGroupAddRoomDialog)(this.props.groupId).then(function () {\n _this3.forceUpdate();\n });\n }\n }, {\n key: 'onRoomStateMember',\n value: function onRoomStateMember(ev, state, member) {\n if (member.roomId !== this.props.roomId) {\n return;\n }\n // redraw the badge on the membership list\n if (this.state.phase === RightPanel.Phase.RoomMemberList && member.roomId === this.props.roomId) {\n this._delayedUpdate();\n } else if (this.state.phase === RightPanel.Phase.RoomMemberInfo && member.roomId === this.props.roomId && member.userId === this.state.member.userId) {\n // refresh the member info (e.g. new power level)\n this._delayedUpdate();\n }\n }\n }, {\n key: 'onAction',\n value: function onAction(payload) {\n if (payload.action === \"view_right_panel_phase\") {\n this.setState({\n phase: payload.phase,\n groupRoomId: payload.groupRoomId,\n groupId: payload.groupId,\n member: payload.member,\n event: payload.event\n });\n }\n }\n }, {\n key: 'render',\n value: function render() {\n var MemberList = _index2.default.getComponent('rooms.MemberList');\n var MemberInfo = _index2.default.getComponent('rooms.MemberInfo');\n var ThirdPartyMemberInfo = _index2.default.getComponent('rooms.ThirdPartyMemberInfo');\n var NotificationPanel = _index2.default.getComponent('structures.NotificationPanel');\n var FilePanel = _index2.default.getComponent('structures.FilePanel');\n\n var GroupMemberList = _index2.default.getComponent('groups.GroupMemberList');\n var GroupMemberInfo = _index2.default.getComponent('groups.GroupMemberInfo');\n var GroupRoomList = _index2.default.getComponent('groups.GroupRoomList');\n var GroupRoomInfo = _index2.default.getComponent('groups.GroupRoomInfo');\n\n var panel = _react2.default.createElement('div', null);\n\n if (this.props.roomId && this.state.phase === RightPanel.Phase.RoomMemberList) {\n panel = _react2.default.createElement(MemberList, { roomId: this.props.roomId, key: this.props.roomId });\n } else if (this.props.groupId && this.state.phase === RightPanel.Phase.GroupMemberList) {\n panel = _react2.default.createElement(GroupMemberList, { groupId: this.props.groupId, key: this.props.groupId });\n } else if (this.state.phase === RightPanel.Phase.GroupRoomList) {\n panel = _react2.default.createElement(GroupRoomList, { groupId: this.props.groupId, key: this.props.groupId });\n } else if (this.state.phase === RightPanel.Phase.RoomMemberInfo) {\n panel = _react2.default.createElement(MemberInfo, { member: this.state.member, key: this.props.roomId || this.state.member.userId });\n } else if (this.state.phase === RightPanel.Phase.Room3pidMemberInfo) {\n panel = _react2.default.createElement(ThirdPartyMemberInfo, { event: this.state.event, key: this.props.roomId });\n } else if (this.state.phase === RightPanel.Phase.GroupMemberInfo) {\n panel = _react2.default.createElement(GroupMemberInfo, {\n groupMember: this.state.member,\n groupId: this.props.groupId,\n key: this.state.member.user_id });\n } else if (this.state.phase === RightPanel.Phase.GroupRoomInfo) {\n panel = _react2.default.createElement(GroupRoomInfo, {\n groupRoomId: this.state.groupRoomId,\n groupId: this.props.groupId,\n key: this.state.groupRoomId });\n } else if (this.state.phase === RightPanel.Phase.NotificationPanel) {\n panel = _react2.default.createElement(NotificationPanel, null);\n } else if (this.state.phase === RightPanel.Phase.FilePanel) {\n panel = _react2.default.createElement(FilePanel, { roomId: this.props.roomId, resizeNotifier: this.props.resizeNotifier });\n }\n\n var classes = (0, _classnames2.default)(\"mx_RightPanel\", \"mx_fadable\", {\n \"collapsed\": this.props.collapsed,\n \"mx_fadable_faded\": this.props.disabled,\n \"dark-panel\": true\n });\n\n return _react2.default.createElement(\n 'aside',\n { className: classes },\n panel\n );\n }\n }]);\n return RightPanel;\n}(_react2.default.Component); /*\n Copyright 2015, 2016 OpenMarket Ltd\n Copyright 2017 Vector Creations Ltd\n Copyright 2017 New Vector Ltd\n Copyright 2018 New Vector Ltd\n Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nRightPanel.Phase = (0, _freeze2.default)({\n RoomMemberList: 'RoomMemberList',\n GroupMemberList: 'GroupMemberList',\n GroupRoomList: 'GroupRoomList',\n GroupRoomInfo: 'GroupRoomInfo',\n FilePanel: 'FilePanel',\n NotificationPanel: 'NotificationPanel',\n RoomMemberInfo: 'RoomMemberInfo',\n Room3pidMemberInfo: 'Room3pidMemberInfo',\n GroupMemberInfo: 'GroupMemberInfo'\n});\nexports.default = RightPanel;\nmodule.exports = exports['default'];\n//# sourceMappingURL=RightPanel.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = ratelimitedfunc;\n\nvar _lodash = require(\"lodash\");\n\nfunction ratelimitedfunc(fn, time) {\n var throttledFn = (0, _lodash.throttle)(fn, time, {\n leading: true,\n trailing: true\n });\n var _bind = throttledFn.bind;\n throttledFn.bind = function () {\n var boundFn = _bind.apply(throttledFn, arguments);\n boundFn.cancelPendingCall = throttledFn.cancelPendingCall;\n return boundFn;\n };\n\n throttledFn.cancelPendingCall = function () {\n throttledFn.cancel();\n };\n return throttledFn;\n} /*\n Copyright 2016 OpenMarket Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n/**\n * 'debounces' a function to only execute every n milliseconds.\n * Useful when react-sdk gets many, many events but only wants\n * to update the interface once for all of them.\n *\n * Note that the function must not take arguments, since the args\n * could be different for each invocation of the function.\n *\n * The returned function has a 'cancelPendingCall' property which can be called\n * on unmount or similar to cancel any pending update.\n */\n\nmodule.exports = exports[\"default\"];\n//# sourceMappingURL=ratelimitedfunc.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nexports.default = function (_ref) {\n var top = _ref.top,\n right = _ref.right,\n bottom = _ref.bottom,\n left = _ref.left;\n return {\n top: top,\n right: right,\n bottom: bottom,\n left: left,\n width: right - left,\n height: bottom - top,\n center: {\n x: (right + left) / 2,\n y: (bottom + top) / 2\n }\n };\n};","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _memoizeOne = require('memoize-one');\n\nvar _memoizeOne2 = _interopRequireDefault(_memoizeOne);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = (0, _memoizeOne2.default)(function (droppable, draggables) {\n return (0, _keys2.default)(draggables).map(function (id) {\n return draggables[id];\n }).filter(function (draggable) {\n return droppable.descriptor.id === draggable.descriptor.droppableId;\n }).sort(function (a, b) {\n return a.descriptor.index - b.descriptor.index;\n });\n});","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getDisplacementMap = require('./get-displacement-map');\n\nvar _getDisplacementMap2 = _interopRequireDefault(_getDisplacementMap);\n\nvar _isPartiallyVisible = require('./visibility/is-partially-visible');\n\nvar _isPartiallyVisible2 = _interopRequireDefault(_isPartiallyVisible);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function (_ref) {\n var draggable = _ref.draggable,\n destination = _ref.destination,\n previousImpact = _ref.previousImpact,\n viewport = _ref.viewport;\n\n var id = draggable.descriptor.id;\n var map = (0, _getDisplacementMap2.default)(previousImpact.movement.displaced);\n\n var isVisible = (0, _isPartiallyVisible2.default)({\n target: draggable.page.withMargin,\n destination: destination,\n viewport: viewport\n });\n\n var shouldAnimate = function () {\n if (!isVisible) {\n return false;\n }\n\n var previous = map[id];\n\n if (!previous) {\n return true;\n }\n\n return previous.shouldAnimate;\n }();\n\n var displacement = {\n draggableId: id,\n isVisible: isVisible,\n shouldAnimate: shouldAnimate\n };\n\n return displacement;\n};","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isContentActionable = isContentActionable;\nexports.canEditContent = canEditContent;\nexports.canEditOwnEvent = canEditOwnEvent;\nexports.findEditableEvent = findEditableEvent;\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _shouldHideEvent = require('../shouldHideEvent');\n\nvar _shouldHideEvent2 = _interopRequireDefault(_shouldHideEvent);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Returns whether an event should allow actions like reply, reactions, edit, etc.\n * which effectively checks whether it's a regular message that has been sent and that we\n * can display.\n *\n * @param {MatrixEvent} mxEvent The event to check\n * @returns {boolean} true if actionable\n */\nfunction isContentActionable(mxEvent) {\n var eventStatus = mxEvent.status;\n\n // status is SENT before remote-echo, null after\n\n var isSent = !eventStatus || eventStatus === _matrixJsSdk.EventStatus.SENT;\n\n if (isSent && mxEvent.getType() === 'm.room.message') {\n var content = mxEvent.getContent();\n if (content.msgtype && content.msgtype !== 'm.bad.encrypted' && content.hasOwnProperty('body')) {\n return true;\n }\n }\n\n return false;\n} /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nfunction canEditContent(mxEvent) {\n if (mxEvent.status === _matrixJsSdk.EventStatus.CANCELLED || mxEvent.getType() !== \"m.room.message\") {\n return false;\n }\n var content = mxEvent.getOriginalContent();\n var msgtype = content.msgtype;\n\n return (msgtype === \"m.text\" || msgtype === \"m.emote\") && mxEvent.getSender() === _MatrixClientPeg2.default.get().getUserId();\n}\n\nfunction canEditOwnEvent(mxEvent) {\n // for now we only allow editing\n // your own events. So this just call through\n // In the future though, moderators will be able to\n // edit other people's messages as well but we don't\n // want findEditableEvent to return other people's events\n // hence this method.\n return canEditContent(mxEvent);\n}\n\nvar MAX_JUMP_DISTANCE = 100;\nfunction findEditableEvent(room, isForward) {\n var fromEventId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;\n\n var liveTimeline = room.getLiveTimeline();\n var events = liveTimeline.getEvents().concat(room.getPendingEvents());\n var maxIdx = events.length - 1;\n var inc = isForward ? 1 : -1;\n var beginIdx = isForward ? 0 : maxIdx;\n var endIdx = isForward ? maxIdx : 0;\n if (!fromEventId) {\n endIdx = Math.min(Math.max(0, beginIdx + inc * MAX_JUMP_DISTANCE), maxIdx);\n }\n var foundFromEventId = !fromEventId;\n for (var i = beginIdx; i !== endIdx + inc; i += inc) {\n var e = events[i];\n // find start event first\n if (!foundFromEventId && e.getId() === fromEventId) {\n foundFromEventId = true;\n // don't look further than MAX_JUMP_DISTANCE events from `fromEventId`\n // to not iterate potentially 1000nds of events on key up/down\n endIdx = Math.min(Math.max(0, i + inc * MAX_JUMP_DISTANCE), maxIdx);\n } else if (foundFromEventId && !(0, _shouldHideEvent2.default)(e) && canEditOwnEvent(e)) {\n // otherwise look for editable event\n return e;\n }\n }\n}\n//# sourceMappingURL=EventUtils.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _createReactClass = require('create-react-class');\n\nvar _createReactClass2 = _interopRequireDefault(_createReactClass);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _index = require('../../../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('../../../languageHandler');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = (0, _createReactClass2.default)({\n displayName: 'QuestionDialog',\n propTypes: {\n title: _propTypes2.default.string,\n description: _propTypes2.default.node,\n extraButtons: _propTypes2.default.node,\n button: _propTypes2.default.string,\n danger: _propTypes2.default.bool,\n focus: _propTypes2.default.bool,\n onFinished: _propTypes2.default.func.isRequired\n },\n\n getDefaultProps: function getDefaultProps() {\n return {\n title: \"\",\n description: \"\",\n extraButtons: null,\n focus: true,\n hasCancelButton: true,\n danger: false\n };\n },\n\n onOk: function onOk() {\n this.props.onFinished(true);\n },\n\n onCancel: function onCancel() {\n this.props.onFinished(false);\n },\n\n render: function render() {\n var BaseDialog = _index2.default.getComponent('views.dialogs.BaseDialog');\n var DialogButtons = _index2.default.getComponent('views.elements.DialogButtons');\n var primaryButtonClass = \"\";\n if (this.props.danger) {\n primaryButtonClass = \"danger\";\n }\n return _react2.default.createElement(\n BaseDialog,\n { className: 'mx_QuestionDialog', onFinished: this.props.onFinished,\n title: this.props.title,\n contentId: 'mx_Dialog_content',\n hasCancel: this.props.hasCancelButton\n },\n _react2.default.createElement(\n 'div',\n { className: 'mx_Dialog_content', id: 'mx_Dialog_content' },\n this.props.description\n ),\n _react2.default.createElement(\n DialogButtons,\n { primaryButton: this.props.button || (0, _languageHandler._t)('OK'),\n primaryButtonClass: primaryButtonClass,\n cancelButton: this.props.cancelButton,\n hasCancel: this.props.hasCancelButton,\n onPrimaryButtonClick: this.onOk,\n focus: this.props.focus,\n onCancel: this.onCancel\n },\n this.props.extraButtons\n )\n );\n }\n}); /*\n Copyright 2015, 2016 OpenMarket Ltd\n Copyright 2017 New Vector Ltd.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nmodule.exports = exports['default'];\n//# sourceMappingURL=QuestionDialog.js.map","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","\"use strict\";\n\nvar encode = require('mdurl/encode');\nvar decode = require('mdurl/decode');\n\nvar C_BACKSLASH = 92;\n\nvar decodeHTML = require('entities').decodeHTML;\n\nvar ENTITY = \"&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});\";\n\nvar TAGNAME = '[A-Za-z][A-Za-z0-9-]*';\nvar ATTRIBUTENAME = '[a-zA-Z_:][a-zA-Z0-9:._-]*';\nvar UNQUOTEDVALUE = \"[^\\\"'=<>`\\\\x00-\\\\x20]+\";\nvar SINGLEQUOTEDVALUE = \"'[^']*'\";\nvar DOUBLEQUOTEDVALUE = '\"[^\"]*\"';\nvar ATTRIBUTEVALUE = \"(?:\" + UNQUOTEDVALUE + \"|\" + SINGLEQUOTEDVALUE + \"|\" + DOUBLEQUOTEDVALUE + \")\";\nvar ATTRIBUTEVALUESPEC = \"(?:\" + \"\\\\s*=\" + \"\\\\s*\" + ATTRIBUTEVALUE + \")\";\nvar ATTRIBUTE = \"(?:\" + \"\\\\s+\" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + \"?)\";\nvar OPENTAG = \"<\" + TAGNAME + ATTRIBUTE + \"*\" + \"\\\\s*/?>\";\nvar CLOSETAG = \"\" + TAGNAME + \"\\\\s*[>]\";\nvar HTMLCOMMENT = \"|\";\nvar PROCESSINGINSTRUCTION = \"[<][?].*?[?][>]\";\nvar DECLARATION = \"]*>\";\nvar CDATA = \"\";\nvar HTMLTAG = \"(?:\" + OPENTAG + \"|\" + CLOSETAG + \"|\" + HTMLCOMMENT + \"|\" +\n PROCESSINGINSTRUCTION + \"|\" + DECLARATION + \"|\" + CDATA + \")\";\nvar reHtmlTag = new RegExp('^' + HTMLTAG, 'i');\n\nvar reBackslashOrAmp = /[\\\\&]/;\n\nvar ESCAPABLE = '[!\"#$%&\\'()*+,./:;<=>?@[\\\\\\\\\\\\]^_`{|}~-]';\n\nvar reEntityOrEscapedChar = new RegExp('\\\\\\\\' + ESCAPABLE + '|' + ENTITY, 'gi');\n\nvar XMLSPECIAL = '[&<>\"]';\n\nvar reXmlSpecial = new RegExp(XMLSPECIAL, 'g');\n\nvar reXmlSpecialOrEntity = new RegExp(ENTITY + '|' + XMLSPECIAL, 'gi');\n\nvar unescapeChar = function(s) {\n if (s.charCodeAt(0) === C_BACKSLASH) {\n return s.charAt(1);\n } else {\n return decodeHTML(s);\n }\n};\n\n// Replace entities and backslash escapes with literal characters.\nvar unescapeString = function(s) {\n if (reBackslashOrAmp.test(s)) {\n return s.replace(reEntityOrEscapedChar, unescapeChar);\n } else {\n return s;\n }\n};\n\nvar normalizeURI = function(uri) {\n try {\n return encode(decode(uri));\n }\n catch(err) {\n return uri;\n }\n};\n\nvar replaceUnsafeChar = function(s) {\n switch (s) {\n case '&':\n return '&';\n case '<':\n return '<';\n case '>':\n return '>';\n case '\"':\n return '"';\n default:\n return s;\n }\n};\n\nvar escapeXml = function(s, preserve_entities) {\n if (reXmlSpecial.test(s)) {\n if (preserve_entities) {\n return s.replace(reXmlSpecialOrEntity, replaceUnsafeChar);\n } else {\n return s.replace(reXmlSpecial, replaceUnsafeChar);\n }\n } else {\n return s;\n }\n};\n\nmodule.exports = { unescapeString: unescapeString,\n normalizeURI: normalizeURI,\n escapeXml: escapeXml,\n reHtmlTag: reHtmlTag,\n OPENTAG: OPENTAG,\n CLOSETAG: CLOSETAG,\n ENTITY: ENTITY,\n ESCAPABLE: ESCAPABLE\n };\n","var basePick = require('./_basePick'),\n flatRest = require('./_flatRest');\n\n/**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\nvar pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n});\n\nmodule.exports = pick;\n","\"use strict\";\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\n/**\n * Colors.\n */\n\nexports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n } // Internet Explorer and Edge do not support colors.\n\n\n if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n } // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\n\n return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773\n typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/);\n}\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\n\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);\n\n if (!this.useColors) {\n return;\n }\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit'); // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function (match) {\n if (match === '%%') {\n return;\n }\n\n index++;\n\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\n\nfunction log() {\n var _console;\n\n // This hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return (typeof console === \"undefined\" ? \"undefined\" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);\n}\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\n\nfunction save(namespaces) {\n try {\n if (namespaces) {\n exports.storage.setItem('debug', namespaces);\n } else {\n exports.storage.removeItem('debug');\n }\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\n\nfunction load() {\n var r;\n\n try {\n r = exports.storage.getItem('debug');\n } catch (error) {} // Swallow\n // XXX (@Qix-) should we be logging these?\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\n\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\n\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nmodule.exports = require('./common')(exports);\nvar formatters = module.exports.formatters;\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n try {\n return JSON.stringify(v);\n } catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n};\n\n","var core = require('./_core');\nvar global = require('./_global');\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || (global[SHARED] = {});\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: core.version,\n mode: require('./_library') ? 'pure' : 'global',\n copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n});\n","// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar cof = require('./_cof');\n// eslint-disable-next-line no-prototype-builtins\nmodule.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {\n return cof(it) == 'String' ? it.split('') : Object(it);\n};\n","exports.f = {}.propertyIsEnumerable;\n","'use strict';\n// 21.2.5.3 get RegExp.prototype.flags\nvar anObject = require('./_an-object');\nmodule.exports = function () {\n var that = anObject(this);\n var result = '';\n if (that.global) result += 'g';\n if (that.ignoreCase) result += 'i';\n if (that.multiline) result += 'm';\n if (that.unicode) result += 'u';\n if (that.sticky) result += 'y';\n return result;\n};\n","// 7.3.20 SpeciesConstructor(O, defaultConstructor)\nvar anObject = require('./_an-object');\nvar aFunction = require('./_a-function');\nvar SPECIES = require('./_wks')('species');\nmodule.exports = function (O, D) {\n var C = anObject(O).constructor;\n var S;\n return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);\n};\n","var toInteger = require('./_to-integer');\nvar defined = require('./_defined');\n// true -> String#at\n// false -> String#codePointAt\nmodule.exports = function (TO_STRING) {\n return function (that, pos) {\n var s = String(defined(that));\n var i = toInteger(pos);\n var l = s.length;\n var a, b;\n if (i < 0 || i >= l) return TO_STRING ? '' : undefined;\n a = s.charCodeAt(i);\n return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff\n ? TO_STRING ? s.charAt(i) : a\n : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;\n };\n};\n","'use strict';\nvar create = require('./_object-create');\nvar descriptor = require('./_property-desc');\nvar setToStringTag = require('./_set-to-string-tag');\nvar IteratorPrototype = {};\n\n// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()\nrequire('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function () { return this; });\n\nmodule.exports = function (Constructor, NAME, next) {\n Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });\n setToStringTag(Constructor, NAME + ' Iterator');\n};\n","// false -> Array#indexOf\n// true -> Array#includes\nvar toIObject = require('./_to-iobject');\nvar toLength = require('./_to-length');\nvar toAbsoluteIndex = require('./_to-absolute-index');\nmodule.exports = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) if (IS_INCLUDES || index in O) {\n if (O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n","var toInteger = require('./_to-integer');\nvar max = Math.max;\nvar min = Math.min;\nmodule.exports = function (index, length) {\n index = toInteger(index);\n return index < 0 ? max(index + length, 0) : min(index, length);\n};\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n// This method of obtaining a reference to the global object needs to be\n// kept identical to the way it is obtained in runtime.js\nvar g = (function() { return this })() || Function(\"return this\")();\n\n// Use `getOwnPropertyNames` because not all browsers support calling\n// `hasOwnProperty` on the global `self` object in a worker. See #183.\nvar hadRuntime = g.regeneratorRuntime &&\n Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n// Save the old regeneratorRuntime in case it needs to be restored later.\nvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n// Force reevalutation of runtime.js.\ng.regeneratorRuntime = undefined;\n\nmodule.exports = require(\"./runtime\");\n\nif (hadRuntime) {\n // Restore the original runtime.\n g.regeneratorRuntime = oldRuntime;\n} else {\n // Remove the global property added by runtime.js.\n try {\n delete g.regeneratorRuntime;\n } catch(e) {\n g.regeneratorRuntime = undefined;\n }\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n!(function(global) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n var inModule = typeof module === \"object\";\n var runtime = global.regeneratorRuntime;\n if (runtime) {\n if (inModule) {\n // If regeneratorRuntime is defined globally and we're in a module,\n // make the exports object identical to regeneratorRuntime.\n module.exports = runtime;\n }\n // Don't bother evaluating the rest of this file if the runtime was\n // already defined globally.\n return;\n }\n\n // Define the runtime globally (as expected by generated code) as either\n // module.exports (if we're in a module) or a new, empty object.\n runtime = global.regeneratorRuntime = inModule ? module.exports : {};\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n runtime.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunctionPrototype[toStringTagSymbol] =\n GeneratorFunction.displayName = \"GeneratorFunction\";\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n }\n\n runtime.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n runtime.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n runtime.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return Promise.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return Promise.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration. If the Promise is rejected, however, the\n // result for this iteration will be rejected with the same\n // reason. Note that rejections of yielded Promises are not\n // thrown back into the generator function, as is the case\n // when an awaited Promise is rejected. This difference in\n // behavior between yield and await is important, because it\n // allows the consumer to decide what to do with the yielded\n // rejection (swallow it and continue, manually .throw it back\n // into the generator, abandon iteration, whatever). With\n // await, by contrast, there is no opportunity to examine the\n // rejection reason outside the generator function, so the\n // only option is to throw it from the await expression, and\n // let the generator function handle the exception.\n result.value = unwrapped;\n resolve(result);\n }, reject);\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new Promise(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n runtime.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList)\n );\n\n return runtime.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n if (delegate.iterator.return) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n Gp[toStringTagSymbol] = \"Generator\";\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n runtime.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n runtime.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n})(\n // In sloppy mode, unbound `this` refers to the global object, fallback to\n // Function constructor if we're in global strict mode. That is sadly a form\n // of indirect eval which violates Content Security Policy.\n (function() { return this })() || Function(\"return this\")()\n);\n","var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a