summaryrefslogtreecommitdiffstats
path: root/comm/chat/protocols/matrix/lib/matrix-widget-api
diff options
context:
space:
mode:
Diffstat (limited to 'comm/chat/protocols/matrix/lib/matrix-widget-api')
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/ClientWidgetApi.js1126
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/LICENSE201
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/Symbols.js27
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/WidgetApi.js808
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/driver/WidgetDriver.js239
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/index.js512
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ApiVersion.js45
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/Capabilities.js69
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/CapabilitiesAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ContentLoadedAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/GetOpenIDAction.js29
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ICustomWidgetData.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IJitsiWidgetData.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IRoomEvent.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IStickerpickerWidgetData.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidget.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiErrorResponse.js30
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiRequest.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiResponse.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalButtonKind.js31
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalWidgetActions.js30
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/NavigateAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/OpenIDCredentialsAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadEventAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadRelationsAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ScreenshotAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendEventAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendToDeviceAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SetModalButtonEnabledAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickerAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickyAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SupportedVersionsAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/TurnServerActions.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/UserDirectorySearchAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/VisibilityAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiAction.js59
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiDirection.js38
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetConfigAction.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetKind.js29
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetType.js29
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/models/Widget.js142
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetEventCapability.js237
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetParser.js152
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/url.js39
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/utils.js28
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/templating/url-template.js59
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/transport/ITransport.js6
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/transport/PostmessageTransport.js222
-rw-r--r--comm/chat/protocols/matrix/lib/matrix-widget-api/util/SimpleObservable.js68
49 files changed, 4399 insertions, 0 deletions
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/ClientWidgetApi.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/ClientWidgetApi.js
new file mode 100644
index 0000000000..4bd84b410f
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/ClientWidgetApi.js
@@ -0,0 +1,1126 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.ClientWidgetApi = void 0;
+var _events = require("events");
+var _PostmessageTransport = require("./transport/PostmessageTransport");
+var _WidgetApiDirection = require("./interfaces/WidgetApiDirection");
+var _WidgetApiAction = require("./interfaces/WidgetApiAction");
+var _Capabilities = require("./interfaces/Capabilities");
+var _ApiVersion = require("./interfaces/ApiVersion");
+var _WidgetEventCapability = require("./models/WidgetEventCapability");
+var _GetOpenIDAction = require("./interfaces/GetOpenIDAction");
+var _SimpleObservable = require("./util/SimpleObservable");
+var _Symbols = require("./Symbols");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
+function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
+function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+function _asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
+function AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(value) { var ret = this.s["return"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, "throw": function _throw(value) { var thr = this.s["return"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); } /*
+ * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * API handler for the client side of widgets. This raises events
+ * for each action received as `action:${action}` (eg: "action:screenshot").
+ * Default handling can be prevented by using preventDefault() on the
+ * raised event. The default handling varies for each action: ones
+ * which the SDK can handle safely are acknowledged appropriately and
+ * ones which are unhandled (custom or require the client to do something)
+ * are rejected with an error.
+ *
+ * Events which are preventDefault()ed must reply using the transport.
+ * The events raised will have a default of an IWidgetApiRequest
+ * interface.
+ *
+ * When the ClientWidgetApi is ready to start sending requests, it will
+ * raise a "ready" CustomEvent. After the ready event fires, actions can
+ * be sent and the transport will be ready.
+ *
+ * When the widget has indicated it has loaded, this class raises a
+ * "preparing" CustomEvent. The preparing event does not indicate that
+ * the widget is ready to receive communications - that is signified by
+ * the ready event exclusively.
+ *
+ * This class only handles one widget at a time.
+ */
+var ClientWidgetApi = /*#__PURE__*/function (_EventEmitter) {
+ _inherits(ClientWidgetApi, _EventEmitter);
+ var _super = _createSuper(ClientWidgetApi);
+ /**
+ * Creates a new client widget API. This will instantiate the transport
+ * and start everything. When the iframe is loaded under the widget's
+ * conditions, a "ready" event will be raised.
+ * @param {Widget} widget The widget to communicate with.
+ * @param {HTMLIFrameElement} iframe The iframe the widget is in.
+ * @param {WidgetDriver} driver The driver for this widget/client.
+ */
+ function ClientWidgetApi(widget, iframe, driver) {
+ var _this;
+ _classCallCheck(this, ClientWidgetApi);
+ _this = _super.call(this);
+ _this.widget = widget;
+ _this.iframe = iframe;
+ _this.driver = driver;
+ _defineProperty(_assertThisInitialized(_this), "transport", void 0);
+ // contentLoadedActionSent is used to check that only one ContentLoaded request is send.
+ _defineProperty(_assertThisInitialized(_this), "contentLoadedActionSent", false);
+ _defineProperty(_assertThisInitialized(_this), "allowedCapabilities", new Set());
+ _defineProperty(_assertThisInitialized(_this), "allowedEvents", []);
+ _defineProperty(_assertThisInitialized(_this), "isStopped", false);
+ _defineProperty(_assertThisInitialized(_this), "turnServers", null);
+ if (!(iframe !== null && iframe !== void 0 && iframe.contentWindow)) {
+ throw new Error("No iframe supplied");
+ }
+ if (!widget) {
+ throw new Error("Invalid widget");
+ }
+ if (!driver) {
+ throw new Error("Invalid driver");
+ }
+ _this.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.ToWidget, widget.id, iframe.contentWindow, window);
+ _this.transport.targetOrigin = widget.origin;
+ _this.transport.on("message", _this.handleMessage.bind(_assertThisInitialized(_this)));
+ iframe.addEventListener("load", _this.onIframeLoad.bind(_assertThisInitialized(_this)));
+ _this.transport.start();
+ return _this;
+ }
+ _createClass(ClientWidgetApi, [{
+ key: "hasCapability",
+ value: function hasCapability(capability) {
+ return this.allowedCapabilities.has(capability);
+ }
+ }, {
+ key: "canUseRoomTimeline",
+ value: function canUseRoomTimeline(roomId) {
+ return this.hasCapability("org.matrix.msc2762.timeline:".concat(_Symbols.Symbols.AnyRoom)) || this.hasCapability("org.matrix.msc2762.timeline:".concat(roomId));
+ }
+ }, {
+ key: "canSendRoomEvent",
+ value: function canSendRoomEvent(eventType) {
+ var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType, msgtype);
+ });
+ }
+ }, {
+ key: "canSendStateEvent",
+ value: function canSendStateEvent(eventType, stateKey) {
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey);
+ });
+ }
+ }, {
+ key: "canSendToDeviceEvent",
+ value: function canSendToDeviceEvent(eventType) {
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType);
+ });
+ }
+ }, {
+ key: "canReceiveRoomEvent",
+ value: function canReceiveRoomEvent(eventType) {
+ var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType, msgtype);
+ });
+ }
+ }, {
+ key: "canReceiveStateEvent",
+ value: function canReceiveStateEvent(eventType, stateKey) {
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey);
+ });
+ }
+ }, {
+ key: "canReceiveToDeviceEvent",
+ value: function canReceiveToDeviceEvent(eventType) {
+ return this.allowedEvents.some(function (e) {
+ return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType);
+ });
+ }
+ }, {
+ key: "stop",
+ value: function stop() {
+ this.isStopped = true;
+ this.transport.stop();
+ }
+ }, {
+ key: "beginCapabilities",
+ value: function beginCapabilities() {
+ var _this2 = this;
+ // widget has loaded - tell all the listeners that
+ this.emit("preparing");
+ var requestedCaps;
+ this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.Capabilities, {}).then(function (caps) {
+ requestedCaps = caps.capabilities;
+ return _this2.driver.validateCapabilities(new Set(caps.capabilities));
+ }).then(function (allowedCaps) {
+ console.log("Widget ".concat(_this2.widget.id, " is allowed capabilities:"), Array.from(allowedCaps));
+ _this2.allowedCapabilities = allowedCaps;
+ _this2.allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowedCaps);
+ _this2.notifyCapabilities(requestedCaps);
+ _this2.emit("ready");
+ });
+ }
+ }, {
+ key: "notifyCapabilities",
+ value: function notifyCapabilities(requested) {
+ var _this3 = this;
+ this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities, {
+ requested: requested,
+ approved: Array.from(this.allowedCapabilities)
+ })["catch"](function (e) {
+ console.warn("non-fatal error notifying widget of approved capabilities:", e);
+ }).then(function () {
+ _this3.emit("capabilitiesNotified");
+ });
+ }
+ }, {
+ key: "onIframeLoad",
+ value: function onIframeLoad(ev) {
+ if (this.widget.waitForIframeLoad) {
+ // If the widget is set to waitForIframeLoad the capabilities immediatly get setup after load.
+ // The client does not wait for the ContentLoaded action.
+ this.beginCapabilities();
+ } else {
+ // Reaching this means, that the Iframe got reloaded/loaded and
+ // the clientApi is awaiting the FIRST ContentLoaded action.
+ this.contentLoadedActionSent = false;
+ }
+ }
+ }, {
+ key: "handleContentLoadedAction",
+ value: function handleContentLoadedAction(action) {
+ if (this.contentLoadedActionSent) {
+ throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded " + "and should only be used if waitForIframeLoad is false (default=true)");
+ }
+ if (this.widget.waitForIframeLoad) {
+ this.transport.reply(action, {
+ error: {
+ message: "Improper sequence: not expecting ContentLoaded event if " + "waitForIframLoad is true (default=true)"
+ }
+ });
+ } else {
+ this.transport.reply(action, {});
+ this.beginCapabilities();
+ }
+ this.contentLoadedActionSent = true;
+ }
+ }, {
+ key: "replyVersions",
+ value: function replyVersions(request) {
+ this.transport.reply(request, {
+ supported_versions: _ApiVersion.CurrentApiVersions
+ });
+ }
+ }, {
+ key: "handleCapabilitiesRenegotiate",
+ value: function handleCapabilitiesRenegotiate(request) {
+ var _request$data,
+ _this4 = this;
+ // acknowledge first
+ this.transport.reply(request, {});
+ var requested = ((_request$data = request.data) === null || _request$data === void 0 ? void 0 : _request$data.capabilities) || [];
+ var newlyRequested = new Set(requested.filter(function (r) {
+ return !_this4.hasCapability(r);
+ }));
+ if (newlyRequested.size === 0) {
+ // Nothing to do - notify capabilities
+ return this.notifyCapabilities([]);
+ }
+ this.driver.validateCapabilities(newlyRequested).then(function (allowed) {
+ allowed.forEach(function (c) {
+ return _this4.allowedCapabilities.add(c);
+ });
+ var allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowed);
+ allowedEvents.forEach(function (c) {
+ return _this4.allowedEvents.push(c);
+ });
+ return _this4.notifyCapabilities(Array.from(newlyRequested));
+ });
+ }
+ }, {
+ key: "handleNavigate",
+ value: function handleNavigate(request) {
+ var _request$data2,
+ _request$data3,
+ _this5 = this;
+ if (!this.hasCapability(_Capabilities.MatrixCapabilities.MSC2931Navigate)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Missing capability"
+ }
+ });
+ }
+ if (!((_request$data2 = request.data) !== null && _request$data2 !== void 0 && _request$data2.uri) || !((_request$data3 = request.data) !== null && _request$data3 !== void 0 && _request$data3.uri.toString().startsWith("https://matrix.to/#"))) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid matrix.to URI"
+ }
+ });
+ }
+ var onErr = function onErr(e) {
+ console.error("[ClientWidgetApi] Failed to handle navigation: ", e);
+ return _this5.transport.reply(request, {
+ error: {
+ message: "Error handling navigation"
+ }
+ });
+ };
+ try {
+ this.driver.navigate(request.data.uri.toString())["catch"](function (e) {
+ return onErr(e);
+ }).then(function () {
+ return _this5.transport.reply(request, {});
+ });
+ } catch (e) {
+ return onErr(e);
+ }
+ }
+ }, {
+ key: "handleOIDC",
+ value: function handleOIDC(request) {
+ var _this6 = this;
+ var phase = 1; // 1 = initial request, 2 = after user manual confirmation
+
+ var replyState = function replyState(state, credential) {
+ credential = credential || {};
+ if (phase > 1) {
+ return _this6.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials, _objectSpread({
+ state: state,
+ original_request_id: request.requestId
+ }, credential));
+ } else {
+ return _this6.transport.reply(request, _objectSpread({
+ state: state
+ }, credential));
+ }
+ };
+ var replyError = function replyError(msg) {
+ console.error("[ClientWidgetApi] Failed to handle OIDC: ", msg);
+ if (phase > 1) {
+ // We don't have a way to indicate that a random error happened in this flow, so
+ // just block the attempt.
+ return replyState(_GetOpenIDAction.OpenIDRequestState.Blocked);
+ } else {
+ return _this6.transport.reply(request, {
+ error: {
+ message: msg
+ }
+ });
+ }
+ };
+ var observer = new _SimpleObservable.SimpleObservable(function (update) {
+ if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation && phase > 1) {
+ observer.close();
+ return replyError("client provided out-of-phase response to OIDC flow");
+ }
+ if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) {
+ replyState(update.state);
+ phase++;
+ return;
+ }
+ if (update.state === _GetOpenIDAction.OpenIDRequestState.Allowed && !update.token) {
+ return replyError("client provided invalid OIDC token for an allowed request");
+ }
+ if (update.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {
+ update.token = undefined; // just in case the client did something weird
+ }
+
+ observer.close();
+ return replyState(update.state, update.token);
+ });
+ this.driver.askOpenID(observer);
+ }
+ }, {
+ key: "handleReadEvents",
+ value: function handleReadEvents(request) {
+ var _this7 = this;
+ if (!request.data.type) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing event type"
+ }
+ });
+ }
+ if (request.data.limit !== undefined && (!request.data.limit || request.data.limit < 0)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - limit out of range"
+ }
+ });
+ }
+ var askRoomIds = null; // null denotes current room only
+ if (request.data.room_ids) {
+ askRoomIds = request.data.room_ids;
+ if (!Array.isArray(askRoomIds)) {
+ askRoomIds = [askRoomIds];
+ }
+ var _iterator2 = _createForOfIteratorHelper(askRoomIds),
+ _step2;
+ try {
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
+ var roomId = _step2.value;
+ if (!this.canUseRoomTimeline(roomId)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Unable to access room timeline: ".concat(roomId)
+ }
+ });
+ }
+ }
+ } catch (err) {
+ _iterator2.e(err);
+ } finally {
+ _iterator2.f();
+ }
+ }
+ var limit = request.data.limit || 0;
+ var events = Promise.resolve([]);
+ if (request.data.state_key !== undefined) {
+ var stateKey = request.data.state_key === true ? undefined : request.data.state_key.toString();
+ if (!this.canReceiveStateEvent(request.data.type, stateKey !== null && stateKey !== void 0 ? stateKey : null)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Cannot read state events of this type"
+ }
+ });
+ }
+ events = this.driver.readStateEvents(request.data.type, stateKey, limit, askRoomIds);
+ } else {
+ if (!this.canReceiveRoomEvent(request.data.type, request.data.msgtype)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Cannot read room events of this type"
+ }
+ });
+ }
+ events = this.driver.readRoomEvents(request.data.type, request.data.msgtype, limit, askRoomIds);
+ }
+ return events.then(function (evs) {
+ return _this7.transport.reply(request, {
+ events: evs
+ });
+ });
+ }
+ }, {
+ key: "handleSendEvent",
+ value: function handleSendEvent(request) {
+ var _this8 = this;
+ if (!request.data.type) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing event type"
+ }
+ });
+ }
+ if (!!request.data.room_id && !this.canUseRoomTimeline(request.data.room_id)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Unable to access room timeline: ".concat(request.data.room_id)
+ }
+ });
+ }
+ var isState = request.data.state_key !== null && request.data.state_key !== undefined;
+ var sendEventPromise;
+ if (isState) {
+ if (!this.canSendStateEvent(request.data.type, request.data.state_key)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Cannot send state events of this type"
+ }
+ });
+ }
+ sendEventPromise = this.driver.sendEvent(request.data.type, request.data.content || {}, request.data.state_key, request.data.room_id);
+ } else {
+ var content = request.data.content || {};
+ var msgtype = content['msgtype'];
+ if (!this.canSendRoomEvent(request.data.type, msgtype)) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Cannot send room events of this type"
+ }
+ });
+ }
+ sendEventPromise = this.driver.sendEvent(request.data.type, content, null,
+ // not sending a state event
+ request.data.room_id);
+ }
+ sendEventPromise.then(function (sentEvent) {
+ return _this8.transport.reply(request, {
+ room_id: sentEvent.roomId,
+ event_id: sentEvent.eventId
+ });
+ })["catch"](function (e) {
+ console.error("error sending event: ", e);
+ return _this8.transport.reply(request, {
+ error: {
+ message: "Error sending event"
+ }
+ });
+ });
+ }
+ }, {
+ key: "handleSendToDevice",
+ value: function () {
+ var _handleSendToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) {
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ if (request.data.type) {
+ _context.next = 5;
+ break;
+ }
+ _context.next = 3;
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing event type"
+ }
+ });
+ case 3:
+ _context.next = 32;
+ break;
+ case 5:
+ if (request.data.messages) {
+ _context.next = 10;
+ break;
+ }
+ _context.next = 8;
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing event contents"
+ }
+ });
+ case 8:
+ _context.next = 32;
+ break;
+ case 10:
+ if (!(typeof request.data.encrypted !== "boolean")) {
+ _context.next = 15;
+ break;
+ }
+ _context.next = 13;
+ return this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing encryption flag"
+ }
+ });
+ case 13:
+ _context.next = 32;
+ break;
+ case 15:
+ if (this.canSendToDeviceEvent(request.data.type)) {
+ _context.next = 20;
+ break;
+ }
+ _context.next = 18;
+ return this.transport.reply(request, {
+ error: {
+ message: "Cannot send to-device events of this type"
+ }
+ });
+ case 18:
+ _context.next = 32;
+ break;
+ case 20:
+ _context.prev = 20;
+ _context.next = 23;
+ return this.driver.sendToDevice(request.data.type, request.data.encrypted, request.data.messages);
+ case 23:
+ _context.next = 25;
+ return this.transport.reply(request, {});
+ case 25:
+ _context.next = 32;
+ break;
+ case 27:
+ _context.prev = 27;
+ _context.t0 = _context["catch"](20);
+ console.error("error sending to-device event", _context.t0);
+ _context.next = 32;
+ return this.transport.reply(request, {
+ error: {
+ message: "Error sending event"
+ }
+ });
+ case 32:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, this, [[20, 27]]);
+ }));
+ function handleSendToDevice(_x) {
+ return _handleSendToDevice.apply(this, arguments);
+ }
+ return handleSendToDevice;
+ }()
+ }, {
+ key: "pollTurnServers",
+ value: function () {
+ var _pollTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(turnServers, initialServer) {
+ var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, server;
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
+ while (1) switch (_context2.prev = _context2.next) {
+ case 0:
+ _context2.prev = 0;
+ _context2.next = 3;
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, initialServer // it's compatible, but missing the index signature
+ );
+ case 3:
+ // Pick the generator up where we left off
+ _iteratorAbruptCompletion = false;
+ _didIteratorError = false;
+ _context2.prev = 5;
+ _iterator = _asyncIterator(turnServers);
+ case 7:
+ _context2.next = 9;
+ return _iterator.next();
+ case 9:
+ if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) {
+ _context2.next = 16;
+ break;
+ }
+ server = _step.value;
+ _context2.next = 13;
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, server // it's compatible, but missing the index signature
+ );
+ case 13:
+ _iteratorAbruptCompletion = false;
+ _context2.next = 7;
+ break;
+ case 16:
+ _context2.next = 22;
+ break;
+ case 18:
+ _context2.prev = 18;
+ _context2.t0 = _context2["catch"](5);
+ _didIteratorError = true;
+ _iteratorError = _context2.t0;
+ case 22:
+ _context2.prev = 22;
+ _context2.prev = 23;
+ if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) {
+ _context2.next = 27;
+ break;
+ }
+ _context2.next = 27;
+ return _iterator["return"]();
+ case 27:
+ _context2.prev = 27;
+ if (!_didIteratorError) {
+ _context2.next = 30;
+ break;
+ }
+ throw _iteratorError;
+ case 30:
+ return _context2.finish(27);
+ case 31:
+ return _context2.finish(22);
+ case 32:
+ _context2.next = 37;
+ break;
+ case 34:
+ _context2.prev = 34;
+ _context2.t1 = _context2["catch"](0);
+ console.error("error polling for TURN servers", _context2.t1);
+ case 37:
+ case "end":
+ return _context2.stop();
+ }
+ }, _callee2, this, [[0, 34], [5, 18, 22, 32], [23,, 27, 31]]);
+ }));
+ function pollTurnServers(_x2, _x3) {
+ return _pollTurnServers.apply(this, arguments);
+ }
+ return pollTurnServers;
+ }()
+ }, {
+ key: "handleWatchTurnServers",
+ value: function () {
+ var _handleWatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(request) {
+ var turnServers, _yield$turnServers$ne, done, value;
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
+ while (1) switch (_context3.prev = _context3.next) {
+ case 0:
+ if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) {
+ _context3.next = 5;
+ break;
+ }
+ _context3.next = 3;
+ return this.transport.reply(request, {
+ error: {
+ message: "Missing capability"
+ }
+ });
+ case 3:
+ _context3.next = 30;
+ break;
+ case 5:
+ if (!this.turnServers) {
+ _context3.next = 10;
+ break;
+ }
+ _context3.next = 8;
+ return this.transport.reply(request, {});
+ case 8:
+ _context3.next = 30;
+ break;
+ case 10:
+ _context3.prev = 10;
+ turnServers = this.driver.getTurnServers(); // Peek at the first result, so we can at least verify that the
+ // client isn't banned from getting TURN servers entirely
+ _context3.next = 14;
+ return turnServers.next();
+ case 14:
+ _yield$turnServers$ne = _context3.sent;
+ done = _yield$turnServers$ne.done;
+ value = _yield$turnServers$ne.value;
+ if (!done) {
+ _context3.next = 19;
+ break;
+ }
+ throw new Error("Client refuses to provide any TURN servers");
+ case 19:
+ _context3.next = 21;
+ return this.transport.reply(request, {});
+ case 21:
+ // Start the poll loop, sending the widget the initial result
+ this.pollTurnServers(turnServers, value);
+ this.turnServers = turnServers;
+ _context3.next = 30;
+ break;
+ case 25:
+ _context3.prev = 25;
+ _context3.t0 = _context3["catch"](10);
+ console.error("error getting first TURN server results", _context3.t0);
+ _context3.next = 30;
+ return this.transport.reply(request, {
+ error: {
+ message: "TURN servers not available"
+ }
+ });
+ case 30:
+ case "end":
+ return _context3.stop();
+ }
+ }, _callee3, this, [[10, 25]]);
+ }));
+ function handleWatchTurnServers(_x4) {
+ return _handleWatchTurnServers.apply(this, arguments);
+ }
+ return handleWatchTurnServers;
+ }()
+ }, {
+ key: "handleUnwatchTurnServers",
+ value: function () {
+ var _handleUnwatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request) {
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
+ while (1) switch (_context4.prev = _context4.next) {
+ case 0:
+ if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) {
+ _context4.next = 5;
+ break;
+ }
+ _context4.next = 3;
+ return this.transport.reply(request, {
+ error: {
+ message: "Missing capability"
+ }
+ });
+ case 3:
+ _context4.next = 15;
+ break;
+ case 5:
+ if (this.turnServers) {
+ _context4.next = 10;
+ break;
+ }
+ _context4.next = 8;
+ return this.transport.reply(request, {});
+ case 8:
+ _context4.next = 15;
+ break;
+ case 10:
+ _context4.next = 12;
+ return this.turnServers["return"](undefined);
+ case 12:
+ this.turnServers = null;
+ _context4.next = 15;
+ return this.transport.reply(request, {});
+ case 15:
+ case "end":
+ return _context4.stop();
+ }
+ }, _callee4, this);
+ }));
+ function handleUnwatchTurnServers(_x5) {
+ return _handleUnwatchTurnServers.apply(this, arguments);
+ }
+ return handleUnwatchTurnServers;
+ }()
+ }, {
+ key: "handleReadRelations",
+ value: function () {
+ var _handleReadRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(request) {
+ var _this9 = this;
+ var result, chunk;
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
+ while (1) switch (_context5.prev = _context5.next) {
+ case 0:
+ if (request.data.event_id) {
+ _context5.next = 2;
+ break;
+ }
+ return _context5.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing event ID"
+ }
+ }));
+ case 2:
+ if (!(request.data.limit !== undefined && request.data.limit < 0)) {
+ _context5.next = 4;
+ break;
+ }
+ return _context5.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Invalid request - limit out of range"
+ }
+ }));
+ case 4:
+ if (!(request.data.room_id !== undefined && !this.canUseRoomTimeline(request.data.room_id))) {
+ _context5.next = 6;
+ break;
+ }
+ return _context5.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Unable to access room timeline: ".concat(request.data.room_id)
+ }
+ }));
+ case 6:
+ _context5.prev = 6;
+ _context5.next = 9;
+ return this.driver.readEventRelations(request.data.event_id, request.data.room_id, request.data.rel_type, request.data.event_type, request.data.from, request.data.to, request.data.limit, request.data.direction);
+ case 9:
+ result = _context5.sent;
+ // only return events that the user has the permission to receive
+ chunk = result.chunk.filter(function (e) {
+ if (e.state_key !== undefined) {
+ return _this9.canReceiveStateEvent(e.type, e.state_key);
+ } else {
+ return _this9.canReceiveRoomEvent(e.type, e.content['msgtype']);
+ }
+ });
+ return _context5.abrupt("return", this.transport.reply(request, {
+ chunk: chunk,
+ prev_batch: result.prevBatch,
+ next_batch: result.nextBatch
+ }));
+ case 14:
+ _context5.prev = 14;
+ _context5.t0 = _context5["catch"](6);
+ console.error("error getting the relations", _context5.t0);
+ _context5.next = 19;
+ return this.transport.reply(request, {
+ error: {
+ message: "Unexpected error while reading relations"
+ }
+ });
+ case 19:
+ case "end":
+ return _context5.stop();
+ }
+ }, _callee5, this, [[6, 14]]);
+ }));
+ function handleReadRelations(_x6) {
+ return _handleReadRelations.apply(this, arguments);
+ }
+ return handleReadRelations;
+ }()
+ }, {
+ key: "handleUserDirectorySearch",
+ value: function () {
+ var _handleUserDirectorySearch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(request) {
+ var result;
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
+ while (1) switch (_context6.prev = _context6.next) {
+ case 0:
+ if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3973UserDirectorySearch)) {
+ _context6.next = 2;
+ break;
+ }
+ return _context6.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Missing capability"
+ }
+ }));
+ case 2:
+ if (!(typeof request.data.search_term !== 'string')) {
+ _context6.next = 4;
+ break;
+ }
+ return _context6.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Invalid request - missing search term"
+ }
+ }));
+ case 4:
+ if (!(request.data.limit !== undefined && request.data.limit < 0)) {
+ _context6.next = 6;
+ break;
+ }
+ return _context6.abrupt("return", this.transport.reply(request, {
+ error: {
+ message: "Invalid request - limit out of range"
+ }
+ }));
+ case 6:
+ _context6.prev = 6;
+ _context6.next = 9;
+ return this.driver.searchUserDirectory(request.data.search_term, request.data.limit);
+ case 9:
+ result = _context6.sent;
+ return _context6.abrupt("return", this.transport.reply(request, {
+ limited: result.limited,
+ results: result.results.map(function (r) {
+ return {
+ user_id: r.userId,
+ display_name: r.displayName,
+ avatar_url: r.avatarUrl
+ };
+ })
+ }));
+ case 13:
+ _context6.prev = 13;
+ _context6.t0 = _context6["catch"](6);
+ console.error("error searching in the user directory", _context6.t0);
+ _context6.next = 18;
+ return this.transport.reply(request, {
+ error: {
+ message: "Unexpected error while searching in the user directory"
+ }
+ });
+ case 18:
+ case "end":
+ return _context6.stop();
+ }
+ }, _callee6, this, [[6, 13]]);
+ }));
+ function handleUserDirectorySearch(_x7) {
+ return _handleUserDirectorySearch.apply(this, arguments);
+ }
+ return handleUserDirectorySearch;
+ }()
+ }, {
+ key: "handleMessage",
+ value: function handleMessage(ev) {
+ if (this.isStopped) return;
+ var actionEv = new CustomEvent("action:".concat(ev.detail.action), {
+ detail: ev.detail,
+ cancelable: true
+ });
+ this.emit("action:".concat(ev.detail.action), actionEv);
+ if (!actionEv.defaultPrevented) {
+ switch (ev.detail.action) {
+ case _WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded:
+ return this.handleContentLoadedAction(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions:
+ return this.replyVersions(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.SendEvent:
+ return this.handleSendEvent(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice:
+ return this.handleSendToDevice(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials:
+ return this.handleOIDC(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate:
+ return this.handleNavigate(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:
+ return this.handleCapabilitiesRenegotiate(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents:
+ return this.handleReadEvents(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers:
+ return this.handleWatchTurnServers(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers:
+ return this.handleUnwatchTurnServers(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations:
+ return this.handleReadRelations(ev.detail);
+ case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:
+ return this.handleUserDirectorySearch(ev.detail);
+ default:
+ return this.transport.reply(ev.detail, {
+ error: {
+ message: "Unknown or unsupported action: " + ev.detail.action
+ }
+ });
+ }
+ }
+ }
+
+ /**
+ * Takes a screenshot of the widget.
+ * @returns Resolves to the widget's screenshot.
+ * @throws Throws if there is a problem.
+ */
+ }, {
+ key: "takeScreenshot",
+ value: function takeScreenshot() {
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.TakeScreenshot, {});
+ }
+
+ /**
+ * Alerts the widget to whether or not it is currently visible.
+ * @param {boolean} isVisible Whether the widget is visible or not.
+ * @returns {Promise<IWidgetApiResponseData>} Resolves when the widget acknowledges the update.
+ */
+ }, {
+ key: "updateVisibility",
+ value: function updateVisibility(isVisible) {
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility, {
+ visible: isVisible
+ });
+ }
+ }, {
+ key: "sendWidgetConfig",
+ value: function sendWidgetConfig(data) {
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.WidgetConfig, data).then();
+ }
+ }, {
+ key: "notifyModalWidgetButtonClicked",
+ value: function notifyModalWidgetButtonClicked(id) {
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.ButtonClicked, {
+ id: id
+ }).then();
+ }
+ }, {
+ key: "notifyModalWidgetClose",
+ value: function notifyModalWidgetClose(data) {
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.CloseModalWidget, data).then();
+ }
+
+ /**
+ * Feeds an event to the widget. If the widget is not able to accept the event due to
+ * permissions, this will no-op and return calmly. If the widget failed to handle the
+ * event, this will raise an error.
+ * @param {IRoomEvent} rawEvent The event to (try to) send to the widget.
+ * @param {string} currentViewedRoomId The room ID the user is currently interacting with.
+ * Not the room ID of the event.
+ * @returns {Promise<void>} Resolves when complete, rejects if there was an error sending.
+ */
+ }, {
+ key: "feedEvent",
+ value: function () {
+ var _feedEvent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(rawEvent, currentViewedRoomId) {
+ var _rawEvent$content;
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
+ while (1) switch (_context7.prev = _context7.next) {
+ case 0:
+ if (!(rawEvent.room_id !== currentViewedRoomId && !this.canUseRoomTimeline(rawEvent.room_id))) {
+ _context7.next = 2;
+ break;
+ }
+ return _context7.abrupt("return");
+ case 2:
+ if (!(rawEvent.state_key !== undefined && rawEvent.state_key !== null)) {
+ _context7.next = 7;
+ break;
+ }
+ if (this.canReceiveStateEvent(rawEvent.type, rawEvent.state_key)) {
+ _context7.next = 5;
+ break;
+ }
+ return _context7.abrupt("return");
+ case 5:
+ _context7.next = 9;
+ break;
+ case 7:
+ if (this.canReceiveRoomEvent(rawEvent.type, (_rawEvent$content = rawEvent.content) === null || _rawEvent$content === void 0 ? void 0 : _rawEvent$content["msgtype"])) {
+ _context7.next = 9;
+ break;
+ }
+ return _context7.abrupt("return");
+ case 9:
+ _context7.next = 11;
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendEvent, rawEvent // it's compatible, but missing the index signature
+ );
+ case 11:
+ case "end":
+ return _context7.stop();
+ }
+ }, _callee7, this);
+ }));
+ function feedEvent(_x8, _x9) {
+ return _feedEvent.apply(this, arguments);
+ }
+ return feedEvent;
+ }()
+ /**
+ * Feeds a to-device event to the widget. If the widget is not able to accept the
+ * event due to permissions, this will no-op and return calmly. If the widget failed
+ * to handle the event, this will raise an error.
+ * @param {IRoomEvent} rawEvent The event to (try to) send to the widget.
+ * @param {boolean} encrypted Whether the event contents were encrypted.
+ * @returns {Promise<void>} Resolves when complete, rejects if there was an error sending.
+ */
+ }, {
+ key: "feedToDevice",
+ value: function () {
+ var _feedToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(rawEvent, encrypted) {
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
+ while (1) switch (_context8.prev = _context8.next) {
+ case 0:
+ if (!this.canReceiveToDeviceEvent(rawEvent.type)) {
+ _context8.next = 3;
+ break;
+ }
+ _context8.next = 3;
+ return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendToDevice, // it's compatible, but missing the index signature
+ _objectSpread(_objectSpread({}, rawEvent), {}, {
+ encrypted: encrypted
+ }));
+ case 3:
+ case "end":
+ return _context8.stop();
+ }
+ }, _callee8, this);
+ }));
+ function feedToDevice(_x10, _x11) {
+ return _feedToDevice.apply(this, arguments);
+ }
+ return feedToDevice;
+ }()
+ }]);
+ return ClientWidgetApi;
+}(_events.EventEmitter);
+exports.ClientWidgetApi = ClientWidgetApi;
+//# sourceMappingURL=ClientWidgetApi.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/LICENSE b/comm/chat/protocols/matrix/lib/matrix-widget-api/LICENSE
new file mode 100644
index 0000000000..261eeb9e9f
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/Symbols.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/Symbols.js
new file mode 100644
index 0000000000..8b4942046c
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/Symbols.js
@@ -0,0 +1,27 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.Symbols = void 0;
+/*
+ * Copyright 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var Symbols = /*#__PURE__*/function (Symbols) {
+ Symbols["AnyRoom"] = "*";
+ return Symbols;
+}({});
+exports.Symbols = Symbols;
+//# sourceMappingURL=Symbols.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/WidgetApi.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/WidgetApi.js
new file mode 100644
index 0000000000..85f96163b8
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/WidgetApi.js
@@ -0,0 +1,808 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetApi = void 0;
+var _events = require("events");
+var _WidgetApiDirection = require("./interfaces/WidgetApiDirection");
+var _ApiVersion = require("./interfaces/ApiVersion");
+var _PostmessageTransport = require("./transport/PostmessageTransport");
+var _WidgetApiAction = require("./interfaces/WidgetApiAction");
+var _GetOpenIDAction = require("./interfaces/GetOpenIDAction");
+var _WidgetType = require("./interfaces/WidgetType");
+var _ModalWidgetActions = require("./interfaces/ModalWidgetActions");
+var _WidgetEventCapability = require("./models/WidgetEventCapability");
+var _Symbols = require("./Symbols");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+function _awaitAsyncGenerator(value) { return new _OverloadYield(value, 0); }
+function _wrapAsyncGenerator(fn) { return function () { return new _AsyncGenerator(fn.apply(this, arguments)); }; }
+function _AsyncGenerator(gen) { var front, back; function resume(key, arg) { try { var result = gen[key](arg), value = result.value, overloaded = value instanceof _OverloadYield; Promise.resolve(overloaded ? value.v : value).then(function (arg) { if (overloaded) { var nextKey = "return" === key ? "return" : "next"; if (!value.k || arg.done) return resume(nextKey, arg); arg = gen[nextKey](arg).value; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: !0 }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: !1 }); } (front = front.next) ? resume(front.key, front.arg) : back = null; } this._invoke = function (key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; back ? back = back.next = request : (front = back = request, resume(key, arg)); }); }, "function" != typeof gen["return"] && (this["return"] = void 0); }
+_AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, _AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }, _AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }, _AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); };
+function _OverloadYield(value, kind) { this.v = value, this.k = kind; } /*
+ * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * API handler for widgets. This raises events for each action
+ * received as `action:${action}` (eg: "action:screenshot").
+ * Default handling can be prevented by using preventDefault()
+ * on the raised event. The default handling varies for each
+ * action: ones which the SDK can handle safely are acknowledged
+ * appropriately and ones which are unhandled (custom or require
+ * the widget to do something) are rejected with an error.
+ *
+ * Events which are preventDefault()ed must reply using the
+ * transport. The events raised will have a detail of an
+ * IWidgetApiRequest interface.
+ *
+ * When the WidgetApi is ready to start sending requests, it will
+ * raise a "ready" CustomEvent. After the ready event fires, actions
+ * can be sent and the transport will be ready.
+ */
+var WidgetApi = /*#__PURE__*/function (_EventEmitter) {
+ _inherits(WidgetApi, _EventEmitter);
+ var _super = _createSuper(WidgetApi);
+ /**
+ * Creates a new API handler for the given widget.
+ * @param {string} widgetId The widget ID to listen for. If not supplied then
+ * the API will use the widget ID from the first valid request it receives.
+ * @param {string} clientOrigin The origin of the client, or null if not known.
+ */
+ function WidgetApi() {
+ var _this2;
+ var widgetId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ var clientOrigin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+ _classCallCheck(this, WidgetApi);
+ _this2 = _super.call(this);
+ _this2.clientOrigin = clientOrigin;
+ _defineProperty(_assertThisInitialized(_this2), "transport", void 0);
+ _defineProperty(_assertThisInitialized(_this2), "capabilitiesFinished", false);
+ _defineProperty(_assertThisInitialized(_this2), "supportsMSC2974Renegotiate", false);
+ _defineProperty(_assertThisInitialized(_this2), "requestedCapabilities", []);
+ _defineProperty(_assertThisInitialized(_this2), "approvedCapabilities", void 0);
+ _defineProperty(_assertThisInitialized(_this2), "cachedClientVersions", void 0);
+ _defineProperty(_assertThisInitialized(_this2), "turnServerWatchers", 0);
+ if (!window.parent) {
+ throw new Error("No parent window. This widget doesn't appear to be embedded properly.");
+ }
+ _this2.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.FromWidget, widgetId, window.parent, window);
+ _this2.transport.targetOrigin = clientOrigin;
+ _this2.transport.on("message", _this2.handleMessage.bind(_assertThisInitialized(_this2)));
+ return _this2;
+ }
+
+ /**
+ * Determines if the widget was granted a particular capability. Note that on
+ * clients where the capabilities are not fed back to the widget this function
+ * will rely on requested capabilities instead.
+ * @param {Capability} capability The capability to check for approval of.
+ * @returns {boolean} True if the widget has approval for the given capability.
+ */
+ _createClass(WidgetApi, [{
+ key: "hasCapability",
+ value: function hasCapability(capability) {
+ if (Array.isArray(this.approvedCapabilities)) {
+ return this.approvedCapabilities.includes(capability);
+ }
+ return this.requestedCapabilities.includes(capability);
+ }
+
+ /**
+ * Request a capability from the client. It is not guaranteed to be allowed,
+ * but will be asked for.
+ * @param {Capability} capability The capability to request.
+ * @throws Throws if the capabilities negotiation has already started and the
+ * widget is unable to request additional capabilities.
+ */
+ }, {
+ key: "requestCapability",
+ value: function requestCapability(capability) {
+ if (this.capabilitiesFinished && !this.supportsMSC2974Renegotiate) {
+ throw new Error("Capabilities have already been negotiated");
+ }
+ this.requestedCapabilities.push(capability);
+ }
+
+ /**
+ * Request capabilities from the client. They are not guaranteed to be allowed,
+ * but will be asked for if the negotiation has not already happened.
+ * @param {Capability[]} capabilities The capabilities to request.
+ * @throws Throws if the capabilities negotiation has already started.
+ */
+ }, {
+ key: "requestCapabilities",
+ value: function requestCapabilities(capabilities) {
+ var _this3 = this;
+ capabilities.forEach(function (cap) {
+ return _this3.requestCapability(cap);
+ });
+ }
+
+ /**
+ * Requests the capability to interact with rooms other than the user's currently
+ * viewed room. Applies to event receiving and sending.
+ * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` to
+ * denote all known rooms.
+ */
+ }, {
+ key: "requestCapabilityForRoomTimeline",
+ value: function requestCapabilityForRoomTimeline(roomId) {
+ this.requestCapability("org.matrix.msc2762.timeline:".concat(roomId));
+ }
+
+ /**
+ * Requests the capability to send a given state event with optional explicit
+ * state key. It is not guaranteed to be allowed, but will be asked for if the
+ * negotiation has not already happened.
+ * @param {string} eventType The state event type to ask for.
+ * @param {string} stateKey If specified, the specific state key to request.
+ * Otherwise all state keys will be requested.
+ */
+ }, {
+ key: "requestCapabilityToSendState",
+ value: function requestCapabilityToSendState(eventType, stateKey) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey).raw);
+ }
+
+ /**
+ * Requests the capability to receive a given state event with optional explicit
+ * state key. It is not guaranteed to be allowed, but will be asked for if the
+ * negotiation has not already happened.
+ * @param {string} eventType The state event type to ask for.
+ * @param {string} stateKey If specified, the specific state key to request.
+ * Otherwise all state keys will be requested.
+ */
+ }, {
+ key: "requestCapabilityToReceiveState",
+ value: function requestCapabilityToReceiveState(eventType, stateKey) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey).raw);
+ }
+
+ /**
+ * Requests the capability to send a given to-device event. It is not
+ * guaranteed to be allowed, but will be asked for if the negotiation has
+ * not already happened.
+ * @param {string} eventType The room event type to ask for.
+ */
+ }, {
+ key: "requestCapabilityToSendToDevice",
+ value: function requestCapabilityToSendToDevice(eventType) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);
+ }
+
+ /**
+ * Requests the capability to receive a given to-device event. It is not
+ * guaranteed to be allowed, but will be asked for if the negotiation has
+ * not already happened.
+ * @param {string} eventType The room event type to ask for.
+ */
+ }, {
+ key: "requestCapabilityToReceiveToDevice",
+ value: function requestCapabilityToReceiveToDevice(eventType) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);
+ }
+
+ /**
+ * Requests the capability to send a given room event. It is not guaranteed to be
+ * allowed, but will be asked for if the negotiation has not already happened.
+ * @param {string} eventType The room event type to ask for.
+ */
+ }, {
+ key: "requestCapabilityToSendEvent",
+ value: function requestCapabilityToSendEvent(eventType) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);
+ }
+
+ /**
+ * Requests the capability to receive a given room event. It is not guaranteed to be
+ * allowed, but will be asked for if the negotiation has not already happened.
+ * @param {string} eventType The room event type to ask for.
+ */
+ }, {
+ key: "requestCapabilityToReceiveEvent",
+ value: function requestCapabilityToReceiveEvent(eventType) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);
+ }
+
+ /**
+ * Requests the capability to send a given message event with optional explicit
+ * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the
+ * negotiation has not already happened.
+ * @param {string} msgtype If specified, the specific msgtype to request.
+ * Otherwise all message types will be requested.
+ */
+ }, {
+ key: "requestCapabilityToSendMessage",
+ value: function requestCapabilityToSendMessage(msgtype) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Send, msgtype).raw);
+ }
+
+ /**
+ * Requests the capability to receive a given message event with optional explicit
+ * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the
+ * negotiation has not already happened.
+ * @param {string} msgtype If specified, the specific msgtype to request.
+ * Otherwise all message types will be requested.
+ */
+ }, {
+ key: "requestCapabilityToReceiveMessage",
+ value: function requestCapabilityToReceiveMessage(msgtype) {
+ this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Receive, msgtype).raw);
+ }
+
+ /**
+ * Requests an OpenID Connect token from the client for the currently logged in
+ * user. This token can be validated server-side with the federation API. Note
+ * that the widget is responsible for validating the token and caching any results
+ * it needs.
+ * @returns {Promise<IOpenIDCredentials>} Resolves to a token for verification.
+ * @throws Throws if the user rejected the request or the request failed.
+ */
+ }, {
+ key: "requestOpenIDConnectToken",
+ value: function requestOpenIDConnectToken() {
+ var _this4 = this;
+ return new Promise(function (resolve, reject) {
+ _this4.transport.sendComplete(_WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials, {}).then(function (response) {
+ var rdata = response.response;
+ if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {
+ resolve(rdata);
+ } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {
+ reject(new Error("User declined to verify their identity"));
+ } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) {
+ var handlerFn = function handlerFn(ev) {
+ ev.preventDefault();
+ var request = ev.detail;
+ if (request.data.original_request_id !== response.requestId) return;
+ if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {
+ resolve(request.data);
+ _this4.transport.reply(request, {}); // ack
+ } else if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {
+ reject(new Error("User declined to verify their identity"));
+ _this4.transport.reply(request, {}); // ack
+ } else {
+ reject(new Error("Invalid state on reply: " + rdata.state));
+ _this4.transport.reply(request, {
+ error: {
+ message: "Invalid state"
+ }
+ });
+ }
+ _this4.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);
+ };
+ _this4.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);
+ } else {
+ reject(new Error("Invalid state: " + rdata.state));
+ }
+ })["catch"](reject);
+ });
+ }
+
+ /**
+ * Asks the client for additional capabilities. Capabilities can be queued for this
+ * request with the requestCapability() functions.
+ * @returns {Promise<void>} Resolves when complete. Note that the promise resolves when
+ * the capabilities request has gone through, not when the capabilities are approved/denied.
+ * Use the WidgetApiToWidgetAction.NotifyCapabilities action to detect changes.
+ */
+ }, {
+ key: "updateRequestedCapabilities",
+ value: function updateRequestedCapabilities() {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities, {
+ capabilities: this.requestedCapabilities
+ }).then();
+ }
+
+ /**
+ * Tell the client that the content has been loaded.
+ * @returns {Promise} Resolves when the client acknowledges the request.
+ */
+ }, {
+ key: "sendContentLoaded",
+ value: function sendContentLoaded() {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded, {}).then();
+ }
+
+ /**
+ * Sends a sticker to the client.
+ * @param {IStickerActionRequestData} sticker The sticker to send.
+ * @returns {Promise} Resolves when the client acknowledges the request.
+ */
+ }, {
+ key: "sendSticker",
+ value: function sendSticker(sticker) {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendSticker, sticker).then();
+ }
+
+ /**
+ * Asks the client to set the always-on-screen status for this widget.
+ * @param {boolean} value The new state to request.
+ * @returns {Promise<boolean>} Resolve with true if the client was able to fulfill
+ * the request, resolves to false otherwise. Rejects if an error occurred.
+ */
+ }, {
+ key: "setAlwaysOnScreen",
+ value: function setAlwaysOnScreen(value) {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, {
+ value: value
+ }).then(function (res) {
+ return res.success;
+ });
+ }
+
+ /**
+ * Opens a modal widget.
+ * @param {string} url The URL to the modal widget.
+ * @param {string} name The name of the widget.
+ * @param {IModalWidgetOpenRequestDataButton[]} buttons The buttons to have on the widget.
+ * @param {IModalWidgetCreateData} data Data to supply to the modal widget.
+ * @param {WidgetType} type The type of modal widget.
+ * @returns {Promise<void>} Resolves when the modal widget has been opened.
+ */
+ }, {
+ key: "openModalWidget",
+ value: function openModalWidget(url, name) {
+ var buttons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
+ var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+ var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _WidgetType.MatrixWidgetType.Custom;
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.OpenModalWidget, {
+ type: type,
+ url: url,
+ name: name,
+ buttons: buttons,
+ data: data
+ }).then();
+ }
+
+ /**
+ * Closes the modal widget. The widget's session will be terminated shortly after.
+ * @param {IModalWidgetReturnData} data Optional data to close the modal widget with.
+ * @returns {Promise<void>} Resolves when complete.
+ */
+ }, {
+ key: "closeModalWidget",
+ value: function closeModalWidget() {
+ var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.CloseModalWidget, data).then();
+ }
+ }, {
+ key: "sendRoomEvent",
+ value: function sendRoomEvent(eventType, content, roomId) {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, {
+ type: eventType,
+ content: content,
+ room_id: roomId
+ });
+ }
+ }, {
+ key: "sendStateEvent",
+ value: function sendStateEvent(eventType, stateKey, content, roomId) {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, {
+ type: eventType,
+ content: content,
+ state_key: stateKey,
+ room_id: roomId
+ });
+ }
+
+ /**
+ * Sends a to-device event.
+ * @param {string} eventType The type of events being sent.
+ * @param {boolean} encrypted Whether to encrypt the message contents.
+ * @param {Object} contentMap A map from user IDs to device IDs to message contents.
+ * @returns {Promise<ISendToDeviceFromWidgetResponseData>} Resolves when complete.
+ */
+ }, {
+ key: "sendToDevice",
+ value: function sendToDevice(eventType, encrypted, contentMap) {
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice, {
+ type: eventType,
+ encrypted: encrypted,
+ messages: contentMap
+ });
+ }
+ }, {
+ key: "readRoomEvents",
+ value: function readRoomEvents(eventType, limit, msgtype, roomIds) {
+ var data = {
+ type: eventType,
+ msgtype: msgtype
+ };
+ if (limit !== undefined) {
+ data.limit = limit;
+ }
+ if (roomIds) {
+ if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {
+ data.room_ids = _Symbols.Symbols.AnyRoom;
+ } else {
+ data.room_ids = roomIds;
+ }
+ }
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {
+ return r.events;
+ });
+ }
+
+ /**
+ * Reads all related events given a known eventId.
+ * @param eventId The id of the parent event to be read.
+ * @param roomId The room to look within. When undefined, the user's currently
+ * viewed room.
+ * @param relationType The relationship type of child events to search for.
+ * When undefined, all relations are returned.
+ * @param eventType The event type of child events to search for. When undefined,
+ * all related events are returned.
+ * @param limit The maximum number of events to retrieve per room. If not
+ * supplied, the server will apply a default limit.
+ * @param from The pagination token to start returning results from, as
+ * received from a previous call. If not supplied, results start at the most
+ * recent topological event known to the server.
+ * @param to The pagination token to stop returning results at. If not
+ * supplied, results continue up to limit or until there are no more events.
+ * @param direction The direction to search for according to MSC3715.
+ * @returns Resolves to the room relations.
+ */
+ }, {
+ key: "readEventRelations",
+ value: function () {
+ var _readEventRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(eventId, roomId, relationType, eventType, limit, from, to, direction) {
+ var versions, data;
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ _context.next = 2;
+ return this.getClientVersions();
+ case 2:
+ versions = _context.sent;
+ if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3869)) {
+ _context.next = 5;
+ break;
+ }
+ throw new Error("The read_relations action is not supported by the client.");
+ case 5:
+ data = {
+ event_id: eventId,
+ rel_type: relationType,
+ event_type: eventType,
+ room_id: roomId,
+ to: to,
+ from: from,
+ limit: limit,
+ direction: direction
+ };
+ return _context.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations, data));
+ case 7:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, this);
+ }));
+ function readEventRelations(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8) {
+ return _readEventRelations.apply(this, arguments);
+ }
+ return readEventRelations;
+ }()
+ }, {
+ key: "readStateEvents",
+ value: function readStateEvents(eventType, limit, stateKey, roomIds) {
+ var data = {
+ type: eventType,
+ state_key: stateKey === undefined ? true : stateKey
+ };
+ if (limit !== undefined) {
+ data.limit = limit;
+ }
+ if (roomIds) {
+ if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {
+ data.room_ids = _Symbols.Symbols.AnyRoom;
+ } else {
+ data.room_ids = roomIds;
+ }
+ }
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {
+ return r.events;
+ });
+ }
+
+ /**
+ * Sets a button as disabled or enabled on the modal widget. Buttons are enabled by default.
+ * @param {ModalButtonID} buttonId The button ID to enable/disable.
+ * @param {boolean} isEnabled Whether or not the button is enabled.
+ * @returns {Promise<void>} Resolves when complete.
+ * @throws Throws if the button cannot be disabled, or the client refuses to disable the button.
+ */
+ }, {
+ key: "setModalButtonEnabled",
+ value: function setModalButtonEnabled(buttonId, isEnabled) {
+ if (buttonId === _ModalWidgetActions.BuiltInModalButtonID.Close) {
+ throw new Error("The close button cannot be disabled");
+ }
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SetModalButtonEnabled, {
+ button: buttonId,
+ enabled: isEnabled
+ }).then();
+ }
+
+ /**
+ * Attempts to navigate the client to the given URI. This can only be called with Matrix URIs
+ * (currently only matrix.to, but in future a Matrix URI scheme will be defined).
+ * @param {string} uri The URI to navigate to.
+ * @returns {Promise<void>} Resolves when complete.
+ * @throws Throws if the URI is invalid or cannot be processed.
+ * @deprecated This currently relies on an unstable MSC (MSC2931).
+ */
+ }, {
+ key: "navigateTo",
+ value: function navigateTo(uri) {
+ if (!uri || !uri.startsWith("https://matrix.to/#")) {
+ throw new Error("Invalid matrix.to URI");
+ }
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate, {
+ uri: uri
+ }).then();
+ }
+
+ /**
+ * Starts watching for TURN servers, yielding an initial set of credentials as soon as possible,
+ * and thereafter yielding new credentials whenever the previous ones expire.
+ * @yields {ITurnServer} The TURN server URIs and credentials currently available to the widget.
+ */
+ }, {
+ key: "getTurnServers",
+ value: function getTurnServers() {
+ var _this = this;
+ return _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
+ var setTurnServer, onUpdateTurnServers;
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
+ while (1) switch (_context3.prev = _context3.next) {
+ case 0:
+ onUpdateTurnServers = /*#__PURE__*/function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ev) {
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
+ while (1) switch (_context2.prev = _context2.next) {
+ case 0:
+ ev.preventDefault();
+ setTurnServer(ev.detail.data);
+ _context2.next = 4;
+ return _this.transport.reply(ev.detail, {});
+ case 4:
+ case "end":
+ return _context2.stop();
+ }
+ }, _callee2);
+ }));
+ return function onUpdateTurnServers(_x9) {
+ return _ref.apply(this, arguments);
+ };
+ }(); // Start listening for updates before we even start watching, to catch
+ // TURN data that is sent immediately
+ _this.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
+
+ // Only send the 'watch' action if we aren't already watching
+ if (!(_this.turnServerWatchers === 0)) {
+ _context3.next = 12;
+ break;
+ }
+ _context3.prev = 3;
+ _context3.next = 6;
+ return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers, {}));
+ case 6:
+ _context3.next = 12;
+ break;
+ case 8:
+ _context3.prev = 8;
+ _context3.t0 = _context3["catch"](3);
+ _this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
+ throw _context3.t0;
+ case 12:
+ _this.turnServerWatchers++;
+ _context3.prev = 13;
+ case 14:
+ if (!true) {
+ _context3.next = 21;
+ break;
+ }
+ _context3.next = 17;
+ return _awaitAsyncGenerator(new Promise(function (resolve) {
+ return setTurnServer = resolve;
+ }));
+ case 17:
+ _context3.next = 19;
+ return _context3.sent;
+ case 19:
+ _context3.next = 14;
+ break;
+ case 21:
+ _context3.prev = 21;
+ // The loop was broken by the caller - clean up
+ _this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
+
+ // Since sending the 'unwatch' action will end updates for all other
+ // consumers, only send it if we're the only consumer remaining
+ _this.turnServerWatchers--;
+ if (!(_this.turnServerWatchers === 0)) {
+ _context3.next = 27;
+ break;
+ }
+ _context3.next = 27;
+ return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers, {}));
+ case 27:
+ return _context3.finish(21);
+ case 28:
+ case "end":
+ return _context3.stop();
+ }
+ }, _callee3, null, [[3, 8], [13,, 21, 28]]);
+ }))();
+ }
+
+ /**
+ * Search for users in the user directory.
+ * @param searchTerm The term to search for.
+ * @param limit The maximum number of results to return. If not supplied, the
+ * @returns Resolves to the search results.
+ */
+ }, {
+ key: "searchUserDirectory",
+ value: function () {
+ var _searchUserDirectory = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(searchTerm, limit) {
+ var versions, data;
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
+ while (1) switch (_context4.prev = _context4.next) {
+ case 0:
+ _context4.next = 2;
+ return this.getClientVersions();
+ case 2:
+ versions = _context4.sent;
+ if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3973)) {
+ _context4.next = 5;
+ break;
+ }
+ throw new Error("The user_directory_search action is not supported by the client.");
+ case 5:
+ data = {
+ search_term: searchTerm,
+ limit: limit
+ };
+ return _context4.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch, data));
+ case 7:
+ case "end":
+ return _context4.stop();
+ }
+ }, _callee4, this);
+ }));
+ function searchUserDirectory(_x10, _x11) {
+ return _searchUserDirectory.apply(this, arguments);
+ }
+ return searchUserDirectory;
+ }()
+ /**
+ * Starts the communication channel. This should be done early to ensure
+ * that messages are not missed. Communication can only be stopped by the client.
+ */
+ }, {
+ key: "start",
+ value: function start() {
+ var _this5 = this;
+ this.transport.start();
+ this.getClientVersions().then(function (v) {
+ if (v.includes(_ApiVersion.UnstableApiVersion.MSC2974)) {
+ _this5.supportsMSC2974Renegotiate = true;
+ }
+ });
+ }
+ }, {
+ key: "handleMessage",
+ value: function handleMessage(ev) {
+ var actionEv = new CustomEvent("action:".concat(ev.detail.action), {
+ detail: ev.detail,
+ cancelable: true
+ });
+ this.emit("action:".concat(ev.detail.action), actionEv);
+ if (!actionEv.defaultPrevented) {
+ switch (ev.detail.action) {
+ case _WidgetApiAction.WidgetApiToWidgetAction.SupportedApiVersions:
+ return this.replyVersions(ev.detail);
+ case _WidgetApiAction.WidgetApiToWidgetAction.Capabilities:
+ return this.handleCapabilities(ev.detail);
+ case _WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility:
+ return this.transport.reply(ev.detail, {});
+ // ack to avoid error spam
+ case _WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities:
+ return this.transport.reply(ev.detail, {});
+ // ack to avoid error spam
+ default:
+ return this.transport.reply(ev.detail, {
+ error: {
+ message: "Unknown or unsupported action: " + ev.detail.action
+ }
+ });
+ }
+ }
+ }
+ }, {
+ key: "replyVersions",
+ value: function replyVersions(request) {
+ this.transport.reply(request, {
+ supported_versions: _ApiVersion.CurrentApiVersions
+ });
+ }
+ }, {
+ key: "getClientVersions",
+ value: function getClientVersions() {
+ var _this6 = this;
+ if (Array.isArray(this.cachedClientVersions)) {
+ return Promise.resolve(this.cachedClientVersions);
+ }
+ return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions, {}).then(function (r) {
+ _this6.cachedClientVersions = r.supported_versions;
+ return r.supported_versions;
+ })["catch"](function (e) {
+ console.warn("non-fatal error getting supported client versions: ", e);
+ return [];
+ });
+ }
+ }, {
+ key: "handleCapabilities",
+ value: function handleCapabilities(request) {
+ var _this7 = this;
+ if (this.capabilitiesFinished) {
+ return this.transport.reply(request, {
+ error: {
+ message: "Capability negotiation already completed"
+ }
+ });
+ }
+
+ // See if we can expect a capabilities notification or not
+ return this.getClientVersions().then(function (v) {
+ if (v.includes(_ApiVersion.UnstableApiVersion.MSC2871)) {
+ _this7.once("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) {
+ _this7.approvedCapabilities = ev.detail.data.approved;
+ _this7.emit("ready");
+ });
+ } else {
+ // if we can't expect notification, we're as done as we can be
+ _this7.emit("ready");
+ }
+
+ // in either case, reply to that capabilities request
+ _this7.capabilitiesFinished = true;
+ return _this7.transport.reply(request, {
+ capabilities: _this7.requestedCapabilities
+ });
+ });
+ }
+ }]);
+ return WidgetApi;
+}(_events.EventEmitter);
+exports.WidgetApi = WidgetApi;
+//# sourceMappingURL=WidgetApi.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/driver/WidgetDriver.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/driver/WidgetDriver.js
new file mode 100644
index 0000000000..17621a9f87
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/driver/WidgetDriver.js
@@ -0,0 +1,239 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetDriver = void 0;
+var _ = require("..");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
+ * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Represents the functions and behaviour the widget-api is unable to
+ * do, such as prompting the user for information or interacting with
+ * the UI. Clients are expected to implement this class and override
+ * any functions they need/want to support.
+ *
+ * This class assumes the client will have a context of a Widget
+ * instance already.
+ */
+var WidgetDriver = /*#__PURE__*/function () {
+ function WidgetDriver() {
+ _classCallCheck(this, WidgetDriver);
+ }
+ _createClass(WidgetDriver, [{
+ key: "validateCapabilities",
+ value:
+ /**
+ * Verifies the widget's requested capabilities, returning the ones
+ * it is approved to use. Mutating the requested capabilities will
+ * have no effect.
+ *
+ * This SHOULD result in the user being prompted to approve/deny
+ * capabilities.
+ *
+ * By default this rejects all capabilities (returns an empty set).
+ * @param {Set<Capability>} requested The set of requested capabilities.
+ * @returns {Promise<Set<Capability>>} Resolves to the allowed capabilities.
+ */
+ function validateCapabilities(requested) {
+ return Promise.resolve(new Set());
+ }
+
+ /**
+ * Sends an event into a room. If `roomId` is falsy, the client should send the event
+ * into the room the user is currently looking at. The widget API will have already
+ * verified that the widget is capable of sending the event to that room.
+ * @param {string} eventType The event type to be sent.
+ * @param {*} content The content for the event.
+ * @param {string|null} stateKey The state key if this is a state event, otherwise null.
+ * May be an empty string.
+ * @param {string|null} roomId The room ID to send the event to. If falsy, the room the
+ * user is currently looking at.
+ * @returns {Promise<ISendEventDetails>} Resolves when the event has been sent with
+ * details of that event.
+ * @throws Rejected when the event could not be sent.
+ */
+ }, {
+ key: "sendEvent",
+ value: function sendEvent(eventType, content) {
+ var stateKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
+ var roomId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
+ return Promise.reject(new Error("Failed to override function"));
+ }
+
+ /**
+ * Sends a to-device event. The widget API will have already verified that the widget
+ * is capable of sending the event.
+ * @param {string} eventType The event type to be sent.
+ * @param {boolean} encrypted Whether to encrypt the message contents.
+ * @param {Object} contentMap A map from user ID and device ID to event content.
+ * @returns {Promise<void>} Resolves when the event has been sent.
+ * @throws Rejected when the event could not be sent.
+ */
+ }, {
+ key: "sendToDevice",
+ value: function sendToDevice(eventType, encrypted, contentMap) {
+ return Promise.reject(new Error("Failed to override function"));
+ }
+
+ /**
+ * Reads all events of the given type, and optionally `msgtype` (if applicable/defined),
+ * the user has access to. The widget API will have already verified that the widget is
+ * capable of receiving the events. Less events than the limit are allowed to be returned,
+ * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that
+ * `limit` in each of the client's known rooms should be returned. When `null`, only the
+ * room the user is currently looking at should be considered.
+ * @param eventType The event type to be read.
+ * @param msgtype The msgtype of the events to be read, if applicable/defined.
+ * @param limit The maximum number of events to retrieve per room. Will be zero to denote "as many
+ * as possible".
+ * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs
+ * to look within, possibly containing Symbols.AnyRoom to denote all known rooms.
+ * @returns {Promise<IRoomEvent[]>} Resolves to the room events, or an empty array.
+ */
+ }, {
+ key: "readRoomEvents",
+ value: function readRoomEvents(eventType, msgtype, limit) {
+ var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
+ return Promise.resolve([]);
+ }
+
+ /**
+ * Reads all events of the given type, and optionally state key (if applicable/defined),
+ * the user has access to. The widget API will have already verified that the widget is
+ * capable of receiving the events. Less events than the limit are allowed to be returned,
+ * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that
+ * `limit` in each of the client's known rooms should be returned. When `null`, only the
+ * room the user is currently looking at should be considered.
+ * @param eventType The event type to be read.
+ * @param stateKey The state key of the events to be read, if applicable/defined.
+ * @param limit The maximum number of events to retrieve. Will be zero to denote "as many
+ * as possible".
+ * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs
+ * to look within, possibly containing Symbols.AnyRoom to denote all known rooms.
+ * @returns {Promise<IRoomEvent[]>} Resolves to the state events, or an empty array.
+ */
+ }, {
+ key: "readStateEvents",
+ value: function readStateEvents(eventType, stateKey, limit) {
+ var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
+ return Promise.resolve([]);
+ }
+
+ /**
+ * Reads all events that are related to a given event. The widget API will
+ * have already verified that the widget is capable of receiving the event,
+ * or will make sure to reject access to events which are returned from this
+ * function, but are not capable of receiving. If `relationType` or `eventType`
+ * are set, the returned events should already be filtered. Less events than
+ * the limit are allowed to be returned, but not more.
+ * @param eventId The id of the parent event to be read.
+ * @param roomId The room to look within. When undefined, the user's
+ * currently viewed room.
+ * @param relationType The relationship type of child events to search for.
+ * When undefined, all relations are returned.
+ * @param eventType The event type of child events to search for. When undefined,
+ * all related events are returned.
+ * @param from The pagination token to start returning results from, as
+ * received from a previous call. If not supplied, results start at the most
+ * recent topological event known to the server.
+ * @param to The pagination token to stop returning results at. If not
+ * supplied, results continue up to limit or until there are no more events.
+ * @param limit The maximum number of events to retrieve per room. If not
+ * supplied, the server will apply a default limit.
+ * @param direction The direction to search for according to MSC3715
+ * @returns Resolves to the room relations.
+ */
+ }, {
+ key: "readEventRelations",
+ value: function readEventRelations(eventId, roomId, relationType, eventType, from, to, limit, direction) {
+ return Promise.resolve({
+ chunk: []
+ });
+ }
+
+ /**
+ * Asks the user for permission to validate their identity through OpenID Connect. The
+ * interface for this function is an observable which accepts the state machine of the
+ * OIDC exchange flow. For example, if the client/user blocks the request then it would
+ * feed back a `{state: Blocked}` into the observable. Similarly, if the user already
+ * approved the widget then a `{state: Allowed}` would be fed into the observable alongside
+ * the token itself. If the client is asking for permission, it should feed in a
+ * `{state: PendingUserConfirmation}` followed by the relevant Allowed or Blocked state.
+ *
+ * The widget API will reject the widget's request with an error if this contract is not
+ * met properly. By default, the widget driver will block all OIDC requests.
+ * @param {SimpleObservable<IOpenIDUpdate>} observer The observable to feed updates into.
+ */
+ }, {
+ key: "askOpenID",
+ value: function askOpenID(observer) {
+ observer.update({
+ state: _.OpenIDRequestState.Blocked
+ });
+ }
+
+ /**
+ * Navigates the client with a matrix.to URI. In future this function will also be provided
+ * with the Matrix URIs once matrix.to is replaced. The given URI will have already been
+ * lightly checked to ensure it looks like a valid URI, though the implementation is recommended
+ * to do further checks on the URI.
+ * @param {string} uri The URI to navigate to.
+ * @returns {Promise<void>} Resolves when complete.
+ * @throws Throws if there's a problem with the navigation, such as invalid format.
+ */
+ }, {
+ key: "navigate",
+ value: function navigate(uri) {
+ throw new Error("Navigation is not implemented");
+ }
+
+ /**
+ * Polls for TURN server data, yielding an initial set of credentials as soon as possible, and
+ * thereafter yielding new credentials whenever the previous ones expire. The widget API will
+ * have already verified that the widget has permission to access TURN servers.
+ * @yields {ITurnServer} The TURN server URIs and credentials currently available to the client.
+ */
+ }, {
+ key: "getTurnServers",
+ value: function getTurnServers() {
+ throw new Error("TURN server support is not implemented");
+ }
+
+ /**
+ * Search for users in the user directory.
+ * @param searchTerm The term to search for.
+ * @param limit The maximum number of results to return. If not supplied, the
+ * @returns Resolves to the search results.
+ */
+ }, {
+ key: "searchUserDirectory",
+ value: function searchUserDirectory(searchTerm, limit) {
+ return Promise.resolve({
+ limited: false,
+ results: []
+ });
+ }
+ }]);
+ return WidgetDriver;
+}();
+exports.WidgetDriver = WidgetDriver;
+//# sourceMappingURL=WidgetDriver.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/index.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/index.js
new file mode 100644
index 0000000000..20eb378a7b
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/index.js
@@ -0,0 +1,512 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+var _WidgetApi = require("./WidgetApi");
+Object.keys(_WidgetApi).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetApi[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetApi[key];
+ }
+ });
+});
+var _ClientWidgetApi = require("./ClientWidgetApi");
+Object.keys(_ClientWidgetApi).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ClientWidgetApi[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ClientWidgetApi[key];
+ }
+ });
+});
+var _Symbols = require("./Symbols");
+Object.keys(_Symbols).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _Symbols[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _Symbols[key];
+ }
+ });
+});
+var _ITransport = require("./transport/ITransport");
+Object.keys(_ITransport).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ITransport[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ITransport[key];
+ }
+ });
+});
+var _PostmessageTransport = require("./transport/PostmessageTransport");
+Object.keys(_PostmessageTransport).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _PostmessageTransport[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _PostmessageTransport[key];
+ }
+ });
+});
+var _ICustomWidgetData = require("./interfaces/ICustomWidgetData");
+Object.keys(_ICustomWidgetData).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ICustomWidgetData[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ICustomWidgetData[key];
+ }
+ });
+});
+var _IJitsiWidgetData = require("./interfaces/IJitsiWidgetData");
+Object.keys(_IJitsiWidgetData).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IJitsiWidgetData[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IJitsiWidgetData[key];
+ }
+ });
+});
+var _IStickerpickerWidgetData = require("./interfaces/IStickerpickerWidgetData");
+Object.keys(_IStickerpickerWidgetData).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IStickerpickerWidgetData[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IStickerpickerWidgetData[key];
+ }
+ });
+});
+var _IWidget = require("./interfaces/IWidget");
+Object.keys(_IWidget).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IWidget[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IWidget[key];
+ }
+ });
+});
+var _WidgetType = require("./interfaces/WidgetType");
+Object.keys(_WidgetType).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetType[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetType[key];
+ }
+ });
+});
+var _IWidgetApiErrorResponse = require("./interfaces/IWidgetApiErrorResponse");
+Object.keys(_IWidgetApiErrorResponse).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IWidgetApiErrorResponse[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IWidgetApiErrorResponse[key];
+ }
+ });
+});
+var _IWidgetApiRequest = require("./interfaces/IWidgetApiRequest");
+Object.keys(_IWidgetApiRequest).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IWidgetApiRequest[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IWidgetApiRequest[key];
+ }
+ });
+});
+var _IWidgetApiResponse = require("./interfaces/IWidgetApiResponse");
+Object.keys(_IWidgetApiResponse).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IWidgetApiResponse[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IWidgetApiResponse[key];
+ }
+ });
+});
+var _WidgetApiAction = require("./interfaces/WidgetApiAction");
+Object.keys(_WidgetApiAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetApiAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetApiAction[key];
+ }
+ });
+});
+var _WidgetApiDirection = require("./interfaces/WidgetApiDirection");
+Object.keys(_WidgetApiDirection).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetApiDirection[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetApiDirection[key];
+ }
+ });
+});
+var _ApiVersion = require("./interfaces/ApiVersion");
+Object.keys(_ApiVersion).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ApiVersion[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ApiVersion[key];
+ }
+ });
+});
+var _Capabilities = require("./interfaces/Capabilities");
+Object.keys(_Capabilities).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _Capabilities[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _Capabilities[key];
+ }
+ });
+});
+var _CapabilitiesAction = require("./interfaces/CapabilitiesAction");
+Object.keys(_CapabilitiesAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _CapabilitiesAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _CapabilitiesAction[key];
+ }
+ });
+});
+var _ContentLoadedAction = require("./interfaces/ContentLoadedAction");
+Object.keys(_ContentLoadedAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ContentLoadedAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ContentLoadedAction[key];
+ }
+ });
+});
+var _ScreenshotAction = require("./interfaces/ScreenshotAction");
+Object.keys(_ScreenshotAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ScreenshotAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ScreenshotAction[key];
+ }
+ });
+});
+var _StickerAction = require("./interfaces/StickerAction");
+Object.keys(_StickerAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _StickerAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _StickerAction[key];
+ }
+ });
+});
+var _StickyAction = require("./interfaces/StickyAction");
+Object.keys(_StickyAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _StickyAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _StickyAction[key];
+ }
+ });
+});
+var _SupportedVersionsAction = require("./interfaces/SupportedVersionsAction");
+Object.keys(_SupportedVersionsAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _SupportedVersionsAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _SupportedVersionsAction[key];
+ }
+ });
+});
+var _VisibilityAction = require("./interfaces/VisibilityAction");
+Object.keys(_VisibilityAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _VisibilityAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _VisibilityAction[key];
+ }
+ });
+});
+var _GetOpenIDAction = require("./interfaces/GetOpenIDAction");
+Object.keys(_GetOpenIDAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _GetOpenIDAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _GetOpenIDAction[key];
+ }
+ });
+});
+var _OpenIDCredentialsAction = require("./interfaces/OpenIDCredentialsAction");
+Object.keys(_OpenIDCredentialsAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _OpenIDCredentialsAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _OpenIDCredentialsAction[key];
+ }
+ });
+});
+var _WidgetKind = require("./interfaces/WidgetKind");
+Object.keys(_WidgetKind).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetKind[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetKind[key];
+ }
+ });
+});
+var _ModalButtonKind = require("./interfaces/ModalButtonKind");
+Object.keys(_ModalButtonKind).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ModalButtonKind[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ModalButtonKind[key];
+ }
+ });
+});
+var _ModalWidgetActions = require("./interfaces/ModalWidgetActions");
+Object.keys(_ModalWidgetActions).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ModalWidgetActions[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ModalWidgetActions[key];
+ }
+ });
+});
+var _SetModalButtonEnabledAction = require("./interfaces/SetModalButtonEnabledAction");
+Object.keys(_SetModalButtonEnabledAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _SetModalButtonEnabledAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _SetModalButtonEnabledAction[key];
+ }
+ });
+});
+var _WidgetConfigAction = require("./interfaces/WidgetConfigAction");
+Object.keys(_WidgetConfigAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetConfigAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetConfigAction[key];
+ }
+ });
+});
+var _SendEventAction = require("./interfaces/SendEventAction");
+Object.keys(_SendEventAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _SendEventAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _SendEventAction[key];
+ }
+ });
+});
+var _SendToDeviceAction = require("./interfaces/SendToDeviceAction");
+Object.keys(_SendToDeviceAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _SendToDeviceAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _SendToDeviceAction[key];
+ }
+ });
+});
+var _ReadEventAction = require("./interfaces/ReadEventAction");
+Object.keys(_ReadEventAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ReadEventAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ReadEventAction[key];
+ }
+ });
+});
+var _IRoomEvent = require("./interfaces/IRoomEvent");
+Object.keys(_IRoomEvent).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _IRoomEvent[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _IRoomEvent[key];
+ }
+ });
+});
+var _NavigateAction = require("./interfaces/NavigateAction");
+Object.keys(_NavigateAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _NavigateAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _NavigateAction[key];
+ }
+ });
+});
+var _TurnServerActions = require("./interfaces/TurnServerActions");
+Object.keys(_TurnServerActions).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _TurnServerActions[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _TurnServerActions[key];
+ }
+ });
+});
+var _ReadRelationsAction = require("./interfaces/ReadRelationsAction");
+Object.keys(_ReadRelationsAction).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _ReadRelationsAction[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _ReadRelationsAction[key];
+ }
+ });
+});
+var _WidgetEventCapability = require("./models/WidgetEventCapability");
+Object.keys(_WidgetEventCapability).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetEventCapability[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetEventCapability[key];
+ }
+ });
+});
+var _url = require("./models/validation/url");
+Object.keys(_url).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _url[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _url[key];
+ }
+ });
+});
+var _utils = require("./models/validation/utils");
+Object.keys(_utils).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _utils[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _utils[key];
+ }
+ });
+});
+var _Widget = require("./models/Widget");
+Object.keys(_Widget).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _Widget[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _Widget[key];
+ }
+ });
+});
+var _WidgetParser = require("./models/WidgetParser");
+Object.keys(_WidgetParser).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetParser[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetParser[key];
+ }
+ });
+});
+var _urlTemplate = require("./templating/url-template");
+Object.keys(_urlTemplate).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _urlTemplate[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _urlTemplate[key];
+ }
+ });
+});
+var _SimpleObservable = require("./util/SimpleObservable");
+Object.keys(_SimpleObservable).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _SimpleObservable[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _SimpleObservable[key];
+ }
+ });
+});
+var _WidgetDriver = require("./driver/WidgetDriver");
+Object.keys(_WidgetDriver).forEach(function (key) {
+ if (key === "default" || key === "__esModule") return;
+ if (key in exports && exports[key] === _WidgetDriver[key]) return;
+ Object.defineProperty(exports, key, {
+ enumerable: true,
+ get: function get() {
+ return _WidgetDriver[key];
+ }
+ });
+});
+//# sourceMappingURL=index.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ApiVersion.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ApiVersion.js
new file mode 100644
index 0000000000..c685445807
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ApiVersion.js
@@ -0,0 +1,45 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.UnstableApiVersion = exports.MatrixApiVersion = exports.CurrentApiVersions = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var MatrixApiVersion = /*#__PURE__*/function (MatrixApiVersion) {
+ MatrixApiVersion["Prerelease1"] = "0.0.1";
+ MatrixApiVersion["Prerelease2"] = "0.0.2";
+ return MatrixApiVersion;
+}({}); //V010 = "0.1.0", // first release
+exports.MatrixApiVersion = MatrixApiVersion;
+var UnstableApiVersion = /*#__PURE__*/function (UnstableApiVersion) {
+ UnstableApiVersion["MSC2762"] = "org.matrix.msc2762";
+ UnstableApiVersion["MSC2871"] = "org.matrix.msc2871";
+ UnstableApiVersion["MSC2931"] = "org.matrix.msc2931";
+ UnstableApiVersion["MSC2974"] = "org.matrix.msc2974";
+ UnstableApiVersion["MSC2876"] = "org.matrix.msc2876";
+ UnstableApiVersion["MSC3819"] = "org.matrix.msc3819";
+ UnstableApiVersion["MSC3846"] = "town.robin.msc3846";
+ UnstableApiVersion["MSC3869"] = "org.matrix.msc3869";
+ UnstableApiVersion["MSC3973"] = "org.matrix.msc3973";
+ return UnstableApiVersion;
+}({});
+exports.UnstableApiVersion = UnstableApiVersion;
+var CurrentApiVersions = [MatrixApiVersion.Prerelease1, MatrixApiVersion.Prerelease2,
+//MatrixApiVersion.V010,
+UnstableApiVersion.MSC2762, UnstableApiVersion.MSC2871, UnstableApiVersion.MSC2931, UnstableApiVersion.MSC2974, UnstableApiVersion.MSC2876, UnstableApiVersion.MSC3819, UnstableApiVersion.MSC3846, UnstableApiVersion.MSC3869, UnstableApiVersion.MSC3973];
+exports.CurrentApiVersions = CurrentApiVersions;
+//# sourceMappingURL=ApiVersion.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/Capabilities.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/Capabilities.js
new file mode 100644
index 0000000000..ce695ffcc7
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/Capabilities.js
@@ -0,0 +1,69 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.VideoConferenceCapabilities = exports.StickerpickerCapabilities = exports.MatrixCapabilities = void 0;
+exports.getTimelineRoomIDFromCapability = getTimelineRoomIDFromCapability;
+exports.isTimelineCapability = isTimelineCapability;
+exports.isTimelineCapabilityFor = isTimelineCapabilityFor;
+/*
+ * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var MatrixCapabilities = /*#__PURE__*/function (MatrixCapabilities) {
+ MatrixCapabilities["Screenshots"] = "m.capability.screenshot";
+ MatrixCapabilities["StickerSending"] = "m.sticker";
+ MatrixCapabilities["AlwaysOnScreen"] = "m.always_on_screen";
+ MatrixCapabilities["RequiresClient"] = "io.element.requires_client";
+ MatrixCapabilities["MSC2931Navigate"] = "org.matrix.msc2931.navigate";
+ MatrixCapabilities["MSC3846TurnServers"] = "town.robin.msc3846.turn_servers";
+ MatrixCapabilities["MSC3973UserDirectorySearch"] = "org.matrix.msc3973.user_directory_search";
+ return MatrixCapabilities;
+}({});
+exports.MatrixCapabilities = MatrixCapabilities;
+var StickerpickerCapabilities = [MatrixCapabilities.StickerSending];
+exports.StickerpickerCapabilities = StickerpickerCapabilities;
+var VideoConferenceCapabilities = [MatrixCapabilities.AlwaysOnScreen];
+
+/**
+ * Determines if a capability is a capability for a timeline.
+ * @param {Capability} capability The capability to test.
+ * @returns {boolean} True if a timeline capability, false otherwise.
+ */
+exports.VideoConferenceCapabilities = VideoConferenceCapabilities;
+function isTimelineCapability(capability) {
+ // TODO: Change when MSC2762 becomes stable.
+ return capability === null || capability === void 0 ? void 0 : capability.startsWith("org.matrix.msc2762.timeline:");
+}
+
+/**
+ * Determines if a capability is a timeline capability for the given room.
+ * @param {Capability} capability The capability to test.
+ * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` for that designation.
+ * @returns {boolean} True if a matching capability, false otherwise.
+ */
+function isTimelineCapabilityFor(capability, roomId) {
+ return capability === "org.matrix.msc2762.timeline:".concat(roomId);
+}
+
+/**
+ * Gets the room ID described by a timeline capability.
+ * @param {string} capability The capability to parse.
+ * @returns {string} The room ID.
+ */
+function getTimelineRoomIDFromCapability(capability) {
+ return capability.substring(capability.indexOf(":") + 1);
+}
+//# sourceMappingURL=Capabilities.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/CapabilitiesAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/CapabilitiesAction.js
new file mode 100644
index 0000000000..c6ce50b3be
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/CapabilitiesAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=CapabilitiesAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ContentLoadedAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ContentLoadedAction.js
new file mode 100644
index 0000000000..65d778b468
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ContentLoadedAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ContentLoadedAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/GetOpenIDAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/GetOpenIDAction.js
new file mode 100644
index 0000000000..45cd3d90e1
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/GetOpenIDAction.js
@@ -0,0 +1,29 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.OpenIDRequestState = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var OpenIDRequestState = /*#__PURE__*/function (OpenIDRequestState) {
+ OpenIDRequestState["Allowed"] = "allowed";
+ OpenIDRequestState["Blocked"] = "blocked";
+ OpenIDRequestState["PendingUserConfirmation"] = "request";
+ return OpenIDRequestState;
+}({});
+exports.OpenIDRequestState = OpenIDRequestState;
+//# sourceMappingURL=GetOpenIDAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ICustomWidgetData.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ICustomWidgetData.js
new file mode 100644
index 0000000000..8edf8d96a2
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ICustomWidgetData.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ICustomWidgetData.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IJitsiWidgetData.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IJitsiWidgetData.js
new file mode 100644
index 0000000000..c63beb0538
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IJitsiWidgetData.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IJitsiWidgetData.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IRoomEvent.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IRoomEvent.js
new file mode 100644
index 0000000000..44478222d0
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IRoomEvent.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IRoomEvent.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IStickerpickerWidgetData.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IStickerpickerWidgetData.js
new file mode 100644
index 0000000000..4085bb0a5e
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IStickerpickerWidgetData.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IStickerpickerWidgetData.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidget.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidget.js
new file mode 100644
index 0000000000..d7e607baa7
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidget.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IWidget.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiErrorResponse.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiErrorResponse.js
new file mode 100644
index 0000000000..c3168d40b4
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiErrorResponse.js
@@ -0,0 +1,30 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.isErrorResponse = isErrorResponse;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function isErrorResponse(responseData) {
+ if ("error" in responseData) {
+ var err = responseData;
+ return !!err.error.message;
+ }
+ return false;
+}
+//# sourceMappingURL=IWidgetApiErrorResponse.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiRequest.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiRequest.js
new file mode 100644
index 0000000000..4596846264
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiRequest.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IWidgetApiRequest.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiResponse.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiResponse.js
new file mode 100644
index 0000000000..3324d18dd7
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/IWidgetApiResponse.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=IWidgetApiResponse.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalButtonKind.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalButtonKind.js
new file mode 100644
index 0000000000..4fb8c0ee1a
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalButtonKind.js
@@ -0,0 +1,31 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.ModalButtonKind = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ModalButtonKind = /*#__PURE__*/function (ModalButtonKind) {
+ ModalButtonKind["Primary"] = "m.primary";
+ ModalButtonKind["Secondary"] = "m.secondary";
+ ModalButtonKind["Warning"] = "m.warning";
+ ModalButtonKind["Danger"] = "m.danger";
+ ModalButtonKind["Link"] = "m.link";
+ return ModalButtonKind;
+}({});
+exports.ModalButtonKind = ModalButtonKind;
+//# sourceMappingURL=ModalButtonKind.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalWidgetActions.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalWidgetActions.js
new file mode 100644
index 0000000000..ab9ddb8e3f
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ModalWidgetActions.js
@@ -0,0 +1,30 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.BuiltInModalButtonID = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var BuiltInModalButtonID = /*#__PURE__*/function (BuiltInModalButtonID) {
+ BuiltInModalButtonID["Close"] = "m.close";
+ return BuiltInModalButtonID;
+}({}); // Types for a normal modal requesting the opening a modal widget
+// Types for a modal widget receiving notifications that its buttons have been pressed
+// Types for a modal widget requesting close
+// Types for a normal widget being notified that the modal widget it opened has been closed
+exports.BuiltInModalButtonID = BuiltInModalButtonID;
+//# sourceMappingURL=ModalWidgetActions.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/NavigateAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/NavigateAction.js
new file mode 100644
index 0000000000..8ea051aa5f
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/NavigateAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=NavigateAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/OpenIDCredentialsAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/OpenIDCredentialsAction.js
new file mode 100644
index 0000000000..7b56879ff0
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/OpenIDCredentialsAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=OpenIDCredentialsAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadEventAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadEventAction.js
new file mode 100644
index 0000000000..4402d229b1
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadEventAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ReadEventAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadRelationsAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadRelationsAction.js
new file mode 100644
index 0000000000..a655252d6d
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ReadRelationsAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ReadRelationsAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ScreenshotAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ScreenshotAction.js
new file mode 100644
index 0000000000..5f51dc8cf7
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/ScreenshotAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ScreenshotAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendEventAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendEventAction.js
new file mode 100644
index 0000000000..acad463560
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendEventAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=SendEventAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendToDeviceAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendToDeviceAction.js
new file mode 100644
index 0000000000..af55b1fa15
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SendToDeviceAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=SendToDeviceAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SetModalButtonEnabledAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SetModalButtonEnabledAction.js
new file mode 100644
index 0000000000..fedab38cb1
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SetModalButtonEnabledAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=SetModalButtonEnabledAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickerAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickerAction.js
new file mode 100644
index 0000000000..004ea7f47e
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickerAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=StickerAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickyAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickyAction.js
new file mode 100644
index 0000000000..05f58f7105
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/StickyAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=StickyAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SupportedVersionsAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SupportedVersionsAction.js
new file mode 100644
index 0000000000..9faeccab03
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/SupportedVersionsAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=SupportedVersionsAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/TurnServerActions.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/TurnServerActions.js
new file mode 100644
index 0000000000..01f7c8f98b
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/TurnServerActions.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=TurnServerActions.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/UserDirectorySearchAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/UserDirectorySearchAction.js
new file mode 100644
index 0000000000..f051b1a48a
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/UserDirectorySearchAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=UserDirectorySearchAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/VisibilityAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/VisibilityAction.js
new file mode 100644
index 0000000000..cc4c9902ad
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/VisibilityAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=VisibilityAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiAction.js
new file mode 100644
index 0000000000..f7e644bec4
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiAction.js
@@ -0,0 +1,59 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetApiToWidgetAction = exports.WidgetApiFromWidgetAction = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var WidgetApiToWidgetAction = /*#__PURE__*/function (WidgetApiToWidgetAction) {
+ WidgetApiToWidgetAction["SupportedApiVersions"] = "supported_api_versions";
+ WidgetApiToWidgetAction["Capabilities"] = "capabilities";
+ WidgetApiToWidgetAction["NotifyCapabilities"] = "notify_capabilities";
+ WidgetApiToWidgetAction["TakeScreenshot"] = "screenshot";
+ WidgetApiToWidgetAction["UpdateVisibility"] = "visibility";
+ WidgetApiToWidgetAction["OpenIDCredentials"] = "openid_credentials";
+ WidgetApiToWidgetAction["WidgetConfig"] = "widget_config";
+ WidgetApiToWidgetAction["CloseModalWidget"] = "close_modal";
+ WidgetApiToWidgetAction["ButtonClicked"] = "button_clicked";
+ WidgetApiToWidgetAction["SendEvent"] = "send_event";
+ WidgetApiToWidgetAction["SendToDevice"] = "send_to_device";
+ WidgetApiToWidgetAction["UpdateTurnServers"] = "update_turn_servers";
+ return WidgetApiToWidgetAction;
+}({});
+exports.WidgetApiToWidgetAction = WidgetApiToWidgetAction;
+var WidgetApiFromWidgetAction = /*#__PURE__*/function (WidgetApiFromWidgetAction) {
+ WidgetApiFromWidgetAction["SupportedApiVersions"] = "supported_api_versions";
+ WidgetApiFromWidgetAction["ContentLoaded"] = "content_loaded";
+ WidgetApiFromWidgetAction["SendSticker"] = "m.sticker";
+ WidgetApiFromWidgetAction["UpdateAlwaysOnScreen"] = "set_always_on_screen";
+ WidgetApiFromWidgetAction["GetOpenIDCredentials"] = "get_openid";
+ WidgetApiFromWidgetAction["CloseModalWidget"] = "close_modal";
+ WidgetApiFromWidgetAction["OpenModalWidget"] = "open_modal";
+ WidgetApiFromWidgetAction["SetModalButtonEnabled"] = "set_button_enabled";
+ WidgetApiFromWidgetAction["SendEvent"] = "send_event";
+ WidgetApiFromWidgetAction["SendToDevice"] = "send_to_device";
+ WidgetApiFromWidgetAction["WatchTurnServers"] = "watch_turn_servers";
+ WidgetApiFromWidgetAction["UnwatchTurnServers"] = "unwatch_turn_servers";
+ WidgetApiFromWidgetAction["MSC2876ReadEvents"] = "org.matrix.msc2876.read_events";
+ WidgetApiFromWidgetAction["MSC2931Navigate"] = "org.matrix.msc2931.navigate";
+ WidgetApiFromWidgetAction["MSC2974RenegotiateCapabilities"] = "org.matrix.msc2974.request_capabilities";
+ WidgetApiFromWidgetAction["MSC3869ReadRelations"] = "org.matrix.msc3869.read_relations";
+ WidgetApiFromWidgetAction["MSC3973UserDirectorySearch"] = "org.matrix.msc3973.user_directory_search";
+ return WidgetApiFromWidgetAction;
+}({});
+exports.WidgetApiFromWidgetAction = WidgetApiFromWidgetAction;
+//# sourceMappingURL=WidgetApiAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiDirection.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiDirection.js
new file mode 100644
index 0000000000..69a6ea679c
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetApiDirection.js
@@ -0,0 +1,38 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetApiDirection = void 0;
+exports.invertedDirection = invertedDirection;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var WidgetApiDirection = /*#__PURE__*/function (WidgetApiDirection) {
+ WidgetApiDirection["ToWidget"] = "toWidget";
+ WidgetApiDirection["FromWidget"] = "fromWidget";
+ return WidgetApiDirection;
+}({});
+exports.WidgetApiDirection = WidgetApiDirection;
+function invertedDirection(dir) {
+ if (dir === WidgetApiDirection.ToWidget) {
+ return WidgetApiDirection.FromWidget;
+ } else if (dir === WidgetApiDirection.FromWidget) {
+ return WidgetApiDirection.ToWidget;
+ } else {
+ throw new Error("Invalid direction");
+ }
+}
+//# sourceMappingURL=WidgetApiDirection.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetConfigAction.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetConfigAction.js
new file mode 100644
index 0000000000..821abebdc0
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetConfigAction.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=WidgetConfigAction.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetKind.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetKind.js
new file mode 100644
index 0000000000..2d552e9c17
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetKind.js
@@ -0,0 +1,29 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetKind = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var WidgetKind = /*#__PURE__*/function (WidgetKind) {
+ WidgetKind["Room"] = "room";
+ WidgetKind["Account"] = "account";
+ WidgetKind["Modal"] = "modal";
+ return WidgetKind;
+}({});
+exports.WidgetKind = WidgetKind;
+//# sourceMappingURL=WidgetKind.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetType.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetType.js
new file mode 100644
index 0000000000..7eb82917a7
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/interfaces/WidgetType.js
@@ -0,0 +1,29 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.MatrixWidgetType = void 0;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var MatrixWidgetType = /*#__PURE__*/function (MatrixWidgetType) {
+ MatrixWidgetType["Custom"] = "m.custom";
+ MatrixWidgetType["JitsiMeet"] = "m.jitsi";
+ MatrixWidgetType["Stickerpicker"] = "m.stickerpicker";
+ return MatrixWidgetType;
+}({});
+exports.MatrixWidgetType = MatrixWidgetType;
+//# sourceMappingURL=WidgetType.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/models/Widget.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/Widget.js
new file mode 100644
index 0000000000..57d1e4a3b3
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/Widget.js
@@ -0,0 +1,142 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.Widget = void 0;
+var _utils = require("./validation/utils");
+var _ = require("..");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Represents the barest form of widget.
+ */
+var Widget = /*#__PURE__*/function () {
+ function Widget(definition) {
+ _classCallCheck(this, Widget);
+ this.definition = definition;
+ if (!this.definition) throw new Error("Definition is required");
+ (0, _utils.assertPresent)(definition, "id");
+ (0, _utils.assertPresent)(definition, "creatorUserId");
+ (0, _utils.assertPresent)(definition, "type");
+ (0, _utils.assertPresent)(definition, "url");
+ }
+
+ /**
+ * The user ID who created the widget.
+ */
+ _createClass(Widget, [{
+ key: "creatorUserId",
+ get: function get() {
+ return this.definition.creatorUserId;
+ }
+
+ /**
+ * The type of widget.
+ */
+ }, {
+ key: "type",
+ get: function get() {
+ return this.definition.type;
+ }
+
+ /**
+ * The ID of the widget.
+ */
+ }, {
+ key: "id",
+ get: function get() {
+ return this.definition.id;
+ }
+
+ /**
+ * The name of the widget, or null if not set.
+ */
+ }, {
+ key: "name",
+ get: function get() {
+ return this.definition.name || null;
+ }
+
+ /**
+ * The title for the widget, or null if not set.
+ */
+ }, {
+ key: "title",
+ get: function get() {
+ return this.rawData.title || null;
+ }
+
+ /**
+ * The templated URL for the widget.
+ */
+ }, {
+ key: "templateUrl",
+ get: function get() {
+ return this.definition.url;
+ }
+
+ /**
+ * The origin for this widget.
+ */
+ }, {
+ key: "origin",
+ get: function get() {
+ return new URL(this.templateUrl).origin;
+ }
+
+ /**
+ * Whether or not the client should wait for the iframe to load. Defaults
+ * to true.
+ */
+ }, {
+ key: "waitForIframeLoad",
+ get: function get() {
+ if (this.definition.waitForIframeLoad === false) return false;
+ if (this.definition.waitForIframeLoad === true) return true;
+ return true; // default true
+ }
+
+ /**
+ * The raw data for the widget. This will always be defined, though
+ * may be empty.
+ */
+ }, {
+ key: "rawData",
+ get: function get() {
+ return this.definition.data || {};
+ }
+
+ /**
+ * Gets a complete widget URL for the client to render.
+ * @param {ITemplateParams} params The template parameters.
+ * @returns {string} A templated URL.
+ */
+ }, {
+ key: "getCompleteUrl",
+ value: function getCompleteUrl(params) {
+ return (0, _.runTemplate)(this.templateUrl, this.definition, params);
+ }
+ }]);
+ return Widget;
+}();
+exports.Widget = Widget;
+//# sourceMappingURL=Widget.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetEventCapability.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetEventCapability.js
new file mode 100644
index 0000000000..e0738905b9
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetEventCapability.js
@@ -0,0 +1,237 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetEventCapability = exports.EventKind = exports.EventDirection = void 0;
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
+function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
+function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var EventKind = /*#__PURE__*/function (EventKind) {
+ EventKind["Event"] = "event";
+ EventKind["State"] = "state_event";
+ EventKind["ToDevice"] = "to_device";
+ return EventKind;
+}({});
+exports.EventKind = EventKind;
+var EventDirection = /*#__PURE__*/function (EventDirection) {
+ EventDirection["Send"] = "send";
+ EventDirection["Receive"] = "receive";
+ return EventDirection;
+}({});
+exports.EventDirection = EventDirection;
+var WidgetEventCapability = /*#__PURE__*/function () {
+ function WidgetEventCapability(direction, eventType, kind, keyStr, raw) {
+ _classCallCheck(this, WidgetEventCapability);
+ this.direction = direction;
+ this.eventType = eventType;
+ this.kind = kind;
+ this.keyStr = keyStr;
+ this.raw = raw;
+ }
+ _createClass(WidgetEventCapability, [{
+ key: "matchesAsStateEvent",
+ value: function matchesAsStateEvent(direction, eventType, stateKey) {
+ if (this.kind !== EventKind.State) return false; // not a state event
+ if (this.direction !== direction) return false; // direction mismatch
+ if (this.eventType !== eventType) return false; // event type mismatch
+ if (this.keyStr === null) return true; // all state keys are allowed
+ if (this.keyStr === stateKey) return true; // this state key is allowed
+
+ // Default not allowed
+ return false;
+ }
+ }, {
+ key: "matchesAsToDeviceEvent",
+ value: function matchesAsToDeviceEvent(direction, eventType) {
+ if (this.kind !== EventKind.ToDevice) return false; // not a to-device event
+ if (this.direction !== direction) return false; // direction mismatch
+ if (this.eventType !== eventType) return false; // event type mismatch
+
+ // Checks passed, the event is allowed
+ return true;
+ }
+ }, {
+ key: "matchesAsRoomEvent",
+ value: function matchesAsRoomEvent(direction, eventType) {
+ var msgtype = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
+ if (this.kind !== EventKind.Event) return false; // not a room event
+ if (this.direction !== direction) return false; // direction mismatch
+ if (this.eventType !== eventType) return false; // event type mismatch
+
+ if (this.eventType === "m.room.message") {
+ if (this.keyStr === null) return true; // all message types are allowed
+ if (this.keyStr === msgtype) return true; // this message type is allowed
+ } else {
+ return true; // already passed the check for if the event is allowed
+ }
+
+ // Default not allowed
+ return false;
+ }
+ }], [{
+ key: "forStateEvent",
+ value: function forStateEvent(direction, eventType, stateKey) {
+ // TODO: Enable support for m.* namespace once the MSC lands.
+ // https://github.com/matrix-org/matrix-widget-api/issues/22
+ eventType = eventType.replace(/#/g, '\\#');
+ stateKey = stateKey !== null && stateKey !== undefined ? "#".concat(stateKey) : '';
+ var str = "org.matrix.msc2762.".concat(direction, ".state_event:").concat(eventType).concat(stateKey);
+
+ // cheat by sending it through the processor
+ return WidgetEventCapability.findEventCapabilities([str])[0];
+ }
+ }, {
+ key: "forToDeviceEvent",
+ value: function forToDeviceEvent(direction, eventType) {
+ // TODO: Enable support for m.* namespace once the MSC lands.
+ // https://github.com/matrix-org/matrix-widget-api/issues/56
+ var str = "org.matrix.msc3819.".concat(direction, ".to_device:").concat(eventType);
+
+ // cheat by sending it through the processor
+ return WidgetEventCapability.findEventCapabilities([str])[0];
+ }
+ }, {
+ key: "forRoomEvent",
+ value: function forRoomEvent(direction, eventType) {
+ // TODO: Enable support for m.* namespace once the MSC lands.
+ // https://github.com/matrix-org/matrix-widget-api/issues/22
+ var str = "org.matrix.msc2762.".concat(direction, ".event:").concat(eventType);
+
+ // cheat by sending it through the processor
+ return WidgetEventCapability.findEventCapabilities([str])[0];
+ }
+ }, {
+ key: "forRoomMessageEvent",
+ value: function forRoomMessageEvent(direction, msgtype) {
+ // TODO: Enable support for m.* namespace once the MSC lands.
+ // https://github.com/matrix-org/matrix-widget-api/issues/22
+ msgtype = msgtype === null || msgtype === undefined ? '' : msgtype;
+ var str = "org.matrix.msc2762.".concat(direction, ".event:m.room.message#").concat(msgtype);
+
+ // cheat by sending it through the processor
+ return WidgetEventCapability.findEventCapabilities([str])[0];
+ }
+
+ /**
+ * Parses a capabilities request to find all the event capability requests.
+ * @param {Iterable<Capability>} capabilities The capabilities requested/to parse.
+ * @returns {WidgetEventCapability[]} An array of event capability requests. May be empty, but never null.
+ */
+ }, {
+ key: "findEventCapabilities",
+ value: function findEventCapabilities(capabilities) {
+ var parsed = [];
+ var _iterator = _createForOfIteratorHelper(capabilities),
+ _step;
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var cap = _step.value;
+ var _direction = null;
+ var eventSegment = void 0;
+ var _kind = null;
+
+ // TODO: Enable support for m.* namespace once the MSCs land.
+ // https://github.com/matrix-org/matrix-widget-api/issues/22
+ // https://github.com/matrix-org/matrix-widget-api/issues/56
+
+ if (cap.startsWith("org.matrix.msc2762.send.event:")) {
+ _direction = EventDirection.Send;
+ _kind = EventKind.Event;
+ eventSegment = cap.substring("org.matrix.msc2762.send.event:".length);
+ } else if (cap.startsWith("org.matrix.msc2762.send.state_event:")) {
+ _direction = EventDirection.Send;
+ _kind = EventKind.State;
+ eventSegment = cap.substring("org.matrix.msc2762.send.state_event:".length);
+ } else if (cap.startsWith("org.matrix.msc3819.send.to_device:")) {
+ _direction = EventDirection.Send;
+ _kind = EventKind.ToDevice;
+ eventSegment = cap.substring("org.matrix.msc3819.send.to_device:".length);
+ } else if (cap.startsWith("org.matrix.msc2762.receive.event:")) {
+ _direction = EventDirection.Receive;
+ _kind = EventKind.Event;
+ eventSegment = cap.substring("org.matrix.msc2762.receive.event:".length);
+ } else if (cap.startsWith("org.matrix.msc2762.receive.state_event:")) {
+ _direction = EventDirection.Receive;
+ _kind = EventKind.State;
+ eventSegment = cap.substring("org.matrix.msc2762.receive.state_event:".length);
+ } else if (cap.startsWith("org.matrix.msc3819.receive.to_device:")) {
+ _direction = EventDirection.Receive;
+ _kind = EventKind.ToDevice;
+ eventSegment = cap.substring("org.matrix.msc3819.receive.to_device:".length);
+ }
+ if (_direction === null || _kind === null || eventSegment === undefined) continue;
+
+ // The capability uses `#` as a separator between event type and state key/msgtype,
+ // so we split on that. However, a # is also valid in either one of those so we
+ // join accordingly.
+ // Eg: `m.room.message##m.text` is "m.room.message" event with msgtype "#m.text".
+ var expectingKeyStr = eventSegment.startsWith("m.room.message#") || _kind === EventKind.State;
+ var _keyStr = null;
+ if (eventSegment.includes('#') && expectingKeyStr) {
+ // Dev note: regex is difficult to write, so instead the rules are manually written
+ // out. This is probably just as understandable as a boring regex though, so win-win?
+
+ // Test cases:
+ // str eventSegment keyStr
+ // -------------------------------------------------------------
+ // m.room.message# m.room.message <empty string>
+ // m.room.message#test m.room.message test
+ // m.room.message\# m.room.message# test
+ // m.room.message##test m.room.message #test
+ // m.room.message\##test m.room.message# test
+ // m.room.message\\##test m.room.message\# test
+ // m.room.message\\###test m.room.message\# #test
+
+ // First step: explode the string
+ var parts = eventSegment.split('#');
+
+ // To form the eventSegment, we'll keep finding parts of the exploded string until
+ // there's one that doesn't end with the escape character (\). We'll then join those
+ // segments together with the exploding character. We have to remember to consume the
+ // escape character as well.
+ var idx = parts.findIndex(function (p) {
+ return !p.endsWith("\\");
+ });
+ eventSegment = parts.slice(0, idx + 1).map(function (p) {
+ return p.endsWith('\\') ? p.substring(0, p.length - 1) : p;
+ }).join('#');
+
+ // The keyStr is whatever is left over.
+ _keyStr = parts.slice(idx + 1).join('#');
+ }
+ parsed.push(new WidgetEventCapability(_direction, eventSegment, _kind, _keyStr, cap));
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+ return parsed;
+ }
+ }]);
+ return WidgetEventCapability;
+}();
+exports.WidgetEventCapability = WidgetEventCapability;
+//# sourceMappingURL=WidgetEventCapability.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetParser.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetParser.js
new file mode 100644
index 0000000000..cd2a742563
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/WidgetParser.js
@@ -0,0 +1,152 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WidgetParser = void 0;
+var _Widget = require("./Widget");
+var _url = require("./validation/url");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
+function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
+function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var WidgetParser = /*#__PURE__*/function () {
+ function WidgetParser() {
+ _classCallCheck(this, WidgetParser);
+ } // private constructor because this is a util class
+
+ /**
+ * Parses widgets from the "m.widgets" account data event. This will always
+ * return an array, though may be empty if no valid widgets were found.
+ * @param {IAccountDataWidgets} content The content of the "m.widgets" account data.
+ * @returns {Widget[]} The widgets in account data, or an empty array.
+ */
+ _createClass(WidgetParser, null, [{
+ key: "parseAccountData",
+ value: function parseAccountData(content) {
+ if (!content) return [];
+ var result = [];
+ for (var _i = 0, _Object$keys = Object.keys(content); _i < _Object$keys.length; _i++) {
+ var _widgetId = _Object$keys[_i];
+ var roughWidget = content[_widgetId];
+ if (!roughWidget) continue;
+ if (roughWidget.type !== "m.widget" && roughWidget.type !== "im.vector.modular.widgets") continue;
+ if (!roughWidget.sender) continue;
+ var probableWidgetId = roughWidget.state_key || roughWidget.id;
+ if (probableWidgetId !== _widgetId) continue;
+ var asStateEvent = {
+ content: roughWidget.content,
+ sender: roughWidget.sender,
+ type: "m.widget",
+ state_key: _widgetId,
+ event_id: "$example",
+ room_id: "!example",
+ origin_server_ts: 1
+ };
+ var widget = WidgetParser.parseRoomWidget(asStateEvent);
+ if (widget) result.push(widget);
+ }
+ return result;
+ }
+
+ /**
+ * Parses all the widgets possible in the given array. This will always return
+ * an array, though may be empty if no widgets could be parsed.
+ * @param {IStateEvent[]} currentState The room state to parse.
+ * @returns {Widget[]} The widgets in the state, or an empty array.
+ */
+ }, {
+ key: "parseWidgetsFromRoomState",
+ value: function parseWidgetsFromRoomState(currentState) {
+ if (!currentState) return [];
+ var result = [];
+ var _iterator = _createForOfIteratorHelper(currentState),
+ _step;
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var state = _step.value;
+ var widget = WidgetParser.parseRoomWidget(state);
+ if (widget) result.push(widget);
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+ return result;
+ }
+
+ /**
+ * Parses a state event into a widget. If the state event does not represent
+ * a widget (wrong event type, invalid widget, etc) then null is returned.
+ * @param {IStateEvent} stateEvent The state event.
+ * @returns {Widget|null} The widget, or null if invalid
+ */
+ }, {
+ key: "parseRoomWidget",
+ value: function parseRoomWidget(stateEvent) {
+ if (!stateEvent) return null;
+
+ // TODO: [Legacy] Remove legacy support
+ if (stateEvent.type !== "m.widget" && stateEvent.type !== "im.vector.modular.widgets") {
+ return null;
+ }
+
+ // Dev note: Throughout this function we have null safety to ensure that
+ // if the caller did not supply something useful that we don't error. This
+ // is done against the requirements of the interface because not everyone
+ // will have an interface to validate against.
+
+ var content = stateEvent.content || {};
+
+ // Form our best approximation of a widget with the information we have
+ var estimatedWidget = {
+ id: stateEvent.state_key,
+ creatorUserId: content['creatorUserId'] || stateEvent.sender,
+ name: content['name'],
+ type: content['type'],
+ url: content['url'],
+ waitForIframeLoad: content['waitForIframeLoad'],
+ data: content['data']
+ };
+
+ // Finally, process that widget
+ return WidgetParser.processEstimatedWidget(estimatedWidget);
+ }
+ }, {
+ key: "processEstimatedWidget",
+ value: function processEstimatedWidget(widget) {
+ // Validate that the widget has the best chance of passing as a widget
+ if (!widget.id || !widget.creatorUserId || !widget.type) {
+ return null;
+ }
+ if (!(0, _url.isValidUrl)(widget.url)) {
+ return null;
+ }
+ // TODO: Validate data for known widget types
+ return new _Widget.Widget(widget);
+ }
+ }]);
+ return WidgetParser;
+}();
+exports.WidgetParser = WidgetParser;
+//# sourceMappingURL=WidgetParser.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/url.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/url.js
new file mode 100644
index 0000000000..30bce1a380
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/url.js
@@ -0,0 +1,39 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.isValidUrl = isValidUrl;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function isValidUrl(val) {
+ if (!val) return false; // easy: not valid if not present
+
+ try {
+ var parsed = new URL(val);
+ if (parsed.protocol !== "http" && parsed.protocol !== "https") {
+ return false;
+ }
+ return true;
+ } catch (e) {
+ if (e instanceof TypeError) {
+ return false;
+ }
+ throw e;
+ }
+}
+//# sourceMappingURL=url.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/utils.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/utils.js
new file mode 100644
index 0000000000..0615393f73
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/models/validation/utils.js
@@ -0,0 +1,28 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.assertPresent = assertPresent;
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function assertPresent(obj, key) {
+ if (!obj[key]) {
+ throw new Error("".concat(String(key), " is required"));
+ }
+}
+//# sourceMappingURL=utils.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/templating/url-template.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/templating/url-template.js
new file mode 100644
index 0000000000..4cdfed5e4c
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/templating/url-template.js
@@ -0,0 +1,59 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.runTemplate = runTemplate;
+exports.toString = toString;
+/*
+ * Copyright 2020, 2021 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function runTemplate(url, widget, params) {
+ // Always apply the supplied params over top of data to ensure the data can't lie about them.
+ var variables = Object.assign({}, widget.data, {
+ 'matrix_room_id': params.widgetRoomId || "",
+ 'matrix_user_id': params.currentUserId,
+ 'matrix_display_name': params.userDisplayName || params.currentUserId,
+ 'matrix_avatar_url': params.userHttpAvatarUrl || "",
+ 'matrix_widget_id': widget.id,
+ // TODO: Convert to stable (https://github.com/matrix-org/matrix-doc/pull/2873)
+ 'org.matrix.msc2873.client_id': params.clientId || "",
+ 'org.matrix.msc2873.client_theme': params.clientTheme || "",
+ 'org.matrix.msc2873.client_language': params.clientLanguage || "",
+ // TODO: Convert to stable (https://github.com/matrix-org/matrix-spec-proposals/pull/3819)
+ 'org.matrix.msc3819.matrix_device_id': params.deviceId || ""
+ });
+ var result = url;
+ for (var _i = 0, _Object$keys = Object.keys(variables); _i < _Object$keys.length; _i++) {
+ var key = _Object$keys[_i];
+ // Regex escape from https://stackoverflow.com/a/6969486/7037379
+ var pattern = "$".concat(key).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
+ var rexp = new RegExp(pattern, 'g');
+
+ // This is technically not what we're supposed to do for a couple of reasons:
+ // 1. We are assuming that there won't later be a $key match after we replace a variable.
+ // 2. We are assuming that the variable is in a place where it can be escaped (eg: path or query string).
+ result = result.replace(rexp, encodeURIComponent(toString(variables[key])));
+ }
+ return result;
+}
+function toString(a) {
+ if (a === null || a === undefined) {
+ return "".concat(a);
+ }
+ return String(a);
+}
+//# sourceMappingURL=url-template.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/ITransport.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/ITransport.js
new file mode 100644
index 0000000000..c5f48db031
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/ITransport.js
@@ -0,0 +1,6 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+//# sourceMappingURL=ITransport.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/PostmessageTransport.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/PostmessageTransport.js
new file mode 100644
index 0000000000..c387170213
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/transport/PostmessageTransport.js
@@ -0,0 +1,222 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.PostmessageTransport = void 0;
+var _events = require("events");
+var _ = require("..");
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Transport for the Widget API over postMessage.
+ */
+var PostmessageTransport = /*#__PURE__*/function (_EventEmitter) {
+ _inherits(PostmessageTransport, _EventEmitter);
+ var _super = _createSuper(PostmessageTransport);
+ function PostmessageTransport(sendDirection, initialWidgetId, transportWindow, inboundWindow) {
+ var _this;
+ _classCallCheck(this, PostmessageTransport);
+ _this = _super.call(this);
+ _this.sendDirection = sendDirection;
+ _this.initialWidgetId = initialWidgetId;
+ _this.transportWindow = transportWindow;
+ _this.inboundWindow = inboundWindow;
+ _defineProperty(_assertThisInitialized(_this), "strictOriginCheck", false);
+ _defineProperty(_assertThisInitialized(_this), "targetOrigin", "*");
+ _defineProperty(_assertThisInitialized(_this), "timeoutSeconds", 10);
+ _defineProperty(_assertThisInitialized(_this), "_ready", false);
+ _defineProperty(_assertThisInitialized(_this), "_widgetId", null);
+ _defineProperty(_assertThisInitialized(_this), "outboundRequests", new Map());
+ _defineProperty(_assertThisInitialized(_this), "stopController", new AbortController());
+ _this._widgetId = initialWidgetId;
+ return _this;
+ }
+ _createClass(PostmessageTransport, [{
+ key: "ready",
+ get: function get() {
+ return this._ready;
+ }
+ }, {
+ key: "widgetId",
+ get: function get() {
+ return this._widgetId || null;
+ }
+ }, {
+ key: "nextRequestId",
+ get: function get() {
+ var idBase = "widgetapi-".concat(Date.now());
+ var index = 0;
+ var id = idBase;
+ while (this.outboundRequests.has(id)) {
+ id = "".concat(idBase, "-").concat(index++);
+ }
+
+ // reserve the ID
+ this.outboundRequests.set(id, null);
+ return id;
+ }
+ }, {
+ key: "sendInternal",
+ value: function sendInternal(message) {
+ console.log("[PostmessageTransport] Sending object to ".concat(this.targetOrigin, ": "), message);
+ this.transportWindow.postMessage(message, this.targetOrigin);
+ }
+ }, {
+ key: "reply",
+ value: function reply(request, responseData) {
+ return this.sendInternal(_objectSpread(_objectSpread({}, request), {}, {
+ response: responseData
+ }));
+ }
+ }, {
+ key: "send",
+ value: function send(action, data) {
+ return this.sendComplete(action, data).then(function (r) {
+ return r.response;
+ });
+ }
+ }, {
+ key: "sendComplete",
+ value: function sendComplete(action, data) {
+ var _this2 = this;
+ if (!this.ready || !this.widgetId) {
+ return Promise.reject(new Error("Not ready or unknown widget ID"));
+ }
+ var request = {
+ api: this.sendDirection,
+ widgetId: this.widgetId,
+ requestId: this.nextRequestId,
+ action: action,
+ data: data
+ };
+ if (action === _.WidgetApiToWidgetAction.UpdateVisibility) {
+ request['visible'] = data['visible'];
+ }
+ return new Promise(function (prResolve, prReject) {
+ var resolve = function resolve(response) {
+ cleanUp();
+ prResolve(response);
+ };
+ var reject = function reject(err) {
+ cleanUp();
+ prReject(err);
+ };
+ var timerId = setTimeout(function () {
+ return reject(new Error("Request timed out"));
+ }, (_this2.timeoutSeconds || 1) * 1000);
+ var onStop = function onStop() {
+ return reject(new Error("Transport stopped"));
+ };
+ _this2.stopController.signal.addEventListener("abort", onStop);
+ var cleanUp = function cleanUp() {
+ _this2.outboundRequests["delete"](request.requestId);
+ clearTimeout(timerId);
+ _this2.stopController.signal.removeEventListener("abort", onStop);
+ };
+ _this2.outboundRequests.set(request.requestId, {
+ request: request,
+ resolve: resolve,
+ reject: reject
+ });
+ _this2.sendInternal(request);
+ });
+ }
+ }, {
+ key: "start",
+ value: function start() {
+ var _this3 = this;
+ this.inboundWindow.addEventListener("message", function (ev) {
+ _this3.handleMessage(ev);
+ });
+ this._ready = true;
+ }
+ }, {
+ key: "stop",
+ value: function stop() {
+ this._ready = false;
+ this.stopController.abort();
+ }
+ }, {
+ key: "handleMessage",
+ value: function handleMessage(ev) {
+ if (this.stopController.signal.aborted) return;
+ if (!ev.data) return; // invalid event
+
+ if (this.strictOriginCheck && ev.origin !== window.origin) return; // bad origin
+
+ // treat the message as a response first, then downgrade to a request
+ var response = ev.data;
+ if (!response.action || !response.requestId || !response.widgetId) return; // invalid request/response
+
+ if (!response.response) {
+ // it's a request
+ var request = response;
+ if (request.api !== (0, _.invertedDirection)(this.sendDirection)) return; // wrong direction
+ this.handleRequest(request);
+ } else {
+ // it's a response
+ if (response.api !== this.sendDirection) return; // wrong direction
+ this.handleResponse(response);
+ }
+ }
+ }, {
+ key: "handleRequest",
+ value: function handleRequest(request) {
+ if (this.widgetId) {
+ if (this.widgetId !== request.widgetId) return; // wrong widget
+ } else {
+ this._widgetId = request.widgetId;
+ }
+ this.emit("message", new CustomEvent("message", {
+ detail: request
+ }));
+ }
+ }, {
+ key: "handleResponse",
+ value: function handleResponse(response) {
+ if (response.widgetId !== this.widgetId) return; // wrong widget
+
+ var req = this.outboundRequests.get(response.requestId);
+ if (!req) return; // response to an unknown request
+
+ if ((0, _.isErrorResponse)(response.response)) {
+ var _err = response.response;
+ req.reject(new Error(_err.error.message));
+ } else {
+ req.resolve(response);
+ }
+ }
+ }]);
+ return PostmessageTransport;
+}(_events.EventEmitter);
+exports.PostmessageTransport = PostmessageTransport;
+//# sourceMappingURL=PostmessageTransport.js.map \ No newline at end of file
diff --git a/comm/chat/protocols/matrix/lib/matrix-widget-api/util/SimpleObservable.js b/comm/chat/protocols/matrix/lib/matrix-widget-api/util/SimpleObservable.js
new file mode 100644
index 0000000000..45bb9f215a
--- /dev/null
+++ b/comm/chat/protocols/matrix/lib/matrix-widget-api/util/SimpleObservable.js
@@ -0,0 +1,68 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.SimpleObservable = void 0;
+function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
+function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
+function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var SimpleObservable = /*#__PURE__*/function () {
+ function SimpleObservable(initialFn) {
+ _classCallCheck(this, SimpleObservable);
+ _defineProperty(this, "listeners", []);
+ if (initialFn) this.listeners.push(initialFn);
+ }
+ _createClass(SimpleObservable, [{
+ key: "onUpdate",
+ value: function onUpdate(fn) {
+ this.listeners.push(fn);
+ }
+ }, {
+ key: "update",
+ value: function update(val) {
+ var _iterator = _createForOfIteratorHelper(this.listeners),
+ _step;
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var listener = _step.value;
+ listener(val);
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+ }
+ }, {
+ key: "close",
+ value: function close() {
+ this.listeners = []; // reset
+ }
+ }]);
+ return SimpleObservable;
+}();
+exports.SimpleObservable = SimpleObservable;
+//# sourceMappingURL=SimpleObservable.js.map \ No newline at end of file