/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ 5246:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;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 (global, factory) {
  ( false ? 0 : _typeof(exports)) === 'object' && "object" !== 'undefined' ? factory(exports, __webpack_require__(4038)) :  true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(4038)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
})(this, function (exports, localforage) {
  'use strict';

  localforage = 'default' in localforage ? localforage['default'] : localforage;
  function getSerializerPromise(localForageInstance) {
    if (getSerializerPromise.result) {
      return getSerializerPromise.result;
    }
    if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {
      return Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));
    }
    getSerializerPromise.result = localForageInstance.getSerializer();
    return getSerializerPromise.result;
  }
  function executeCallback(promise, callback) {
    if (callback) {
      promise.then(function (result) {
        callback(null, result);
      }, function (error) {
        callback(error);
      });
    }
    return promise;
  }
  function getItemKeyValue(key, callback) {
    var localforageInstance = this;
    var promise = localforageInstance.getItem(key).then(function (value) {
      return {
        key: key,
        value: value
      };
    });
    executeCallback(promise, callback);
    return promise;
  }
  function getItemsGeneric(keys /*, callback*/) {
    var localforageInstance = this;
    var promise = new Promise(function (resolve, reject) {
      var itemPromises = [];
      for (var i = 0, len = keys.length; i < len; i++) {
        itemPromises.push(getItemKeyValue.call(localforageInstance, keys[i]));
      }
      Promise.all(itemPromises).then(function (keyValuePairs) {
        var result = {};
        for (var i = 0, len = keyValuePairs.length; i < len; i++) {
          var keyValuePair = keyValuePairs[i];
          result[keyValuePair.key] = keyValuePair.value;
        }
        resolve(result);
      }).catch(reject);
    });
    return promise;
  }
  function getAllItemsUsingIterate() {
    var localforageInstance = this;
    var accumulator = {};
    return localforageInstance.iterate(function (value, key /*, iterationNumber*/) {
      accumulator[key] = value;
    }).then(function () {
      return accumulator;
    });
  }
  function getIDBKeyRange() {
    /* global IDBKeyRange, webkitIDBKeyRange, mozIDBKeyRange */
    if (typeof IDBKeyRange !== 'undefined') {
      return IDBKeyRange;
    }
    if (typeof webkitIDBKeyRange !== 'undefined') {
      return webkitIDBKeyRange;
    }
    if (typeof mozIDBKeyRange !== 'undefined') {
      return mozIDBKeyRange;
    }
  }
  var idbKeyRange = getIDBKeyRange();
  function getItemsIndexedDB(keys /*, callback*/) {
    keys = keys.slice();
    var localforageInstance = this;
    function comparer(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
    }
    var promise = new Promise(function (resolve, reject) {
      localforageInstance.ready().then(function () {
        // Thanks https://hacks.mozilla.org/2014/06/breaking-the-borders-of-indexeddb/
        var dbInfo = localforageInstance._dbInfo;
        var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
        var set = keys.sort(comparer);
        var keyRangeValue = idbKeyRange.bound(keys[0], keys[keys.length - 1], false, false);
        var req;
        if ('getAll' in store) {
          req = store.getAll(keyRangeValue);
          req.onsuccess = function () {
            var value = req.result;
            if (value === undefined) {
              value = null;
            }
            resolve(value);
          };
        } else {
          req = store.openCursor(keyRangeValue);
          var result = {};
          var i = 0;
          req.onsuccess = function () /*event*/{
            var cursor = req.result; // event.target.result;

            if (!cursor) {
              resolve(result);
              return;
            }
            var key = cursor.key;
            while (key > set[i]) {
              i++; // The cursor has passed beyond this key. Check next.

              if (i === set.length) {
                // There is no next. Stop searching.
                resolve(result);
                return;
              }
            }
            if (key === set[i]) {
              // The current cursor value should be included and we should continue
              // a single step in case next item has the same key or possibly our
              // next key in set.
              var value = cursor.value;
              if (value === undefined) {
                value = null;
              }
              result[key] = value;
              // onfound(cursor.value);
              cursor.continue();
            } else {
              // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
              cursor.continue(set[i]);
            }
          };
        }
        req.onerror = function () /*event*/{
          reject(req.error);
        };
      }).catch(reject);
    });
    return promise;
  }
  function getItemsWebsql(keys /*, callback*/) {
    var localforageInstance = this;
    var promise = new Promise(function (resolve, reject) {
      localforageInstance.ready().then(function () {
        return getSerializerPromise(localforageInstance);
      }).then(function (serializer) {
        var dbInfo = localforageInstance._dbInfo;
        dbInfo.db.transaction(function (t) {
          var queryParts = new Array(keys.length);
          for (var i = 0, len = keys.length; i < len; i++) {
            queryParts[i] = '?';
          }
          t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE (key IN (' + queryParts.join(',') + '))', keys, function (t, results) {
            var result = {};
            var rows = results.rows;
            for (var i = 0, len = rows.length; i < len; i++) {
              var item = rows.item(i);
              var value = item.value;

              // Check to see if this is serialized content we need to
              // unpack.
              if (value) {
                value = serializer.deserialize(value);
              }
              result[item.key] = value;
            }
            resolve(result);
          }, function (t, error) {
            reject(error);
          });
        });
      }).catch(reject);
    });
    return promise;
  }
  function localforageGetItems(keys, callback) {
    var localforageInstance = this;
    var promise;
    if (!arguments.length || keys === null) {
      promise = getAllItemsUsingIterate.apply(localforageInstance);
    } else {
      var currentDriver = localforageInstance.driver();
      if (currentDriver === localforageInstance.INDEXEDDB) {
        promise = getItemsIndexedDB.apply(localforageInstance, arguments);
      } else if (currentDriver === localforageInstance.WEBSQL) {
        promise = getItemsWebsql.apply(localforageInstance, arguments);
      } else {
        promise = getItemsGeneric.apply(localforageInstance, arguments);
      }
    }
    executeCallback(promise, callback);
    return promise;
  }
  function extendPrototype(localforage$$1) {
    var localforagePrototype = Object.getPrototypeOf(localforage$$1);
    if (localforagePrototype) {
      localforagePrototype.getItems = localforageGetItems;
      localforagePrototype.getItems.indexedDB = function () {
        return getItemsIndexedDB.apply(this, arguments);
      };
      localforagePrototype.getItems.websql = function () {
        return getItemsWebsql.apply(this, arguments);
      };
      localforagePrototype.getItems.generic = function () {
        return getItemsGeneric.apply(this, arguments);
      };
    }
  }
  var extendPrototypeResult = extendPrototype(localforage);
  exports.localforageGetItems = localforageGetItems;
  exports.extendPrototype = extendPrototype;
  exports.extendPrototypeResult = extendPrototypeResult;
  exports.getItemsGeneric = getItemsGeneric;
  Object.defineProperty(exports, '__esModule', {
    value: true
  });
});

/***/ }),

/***/ 5542:
/***/ ((module, exports, __webpack_require__) => {

/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;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 (t, e) {
  "object" == ( false ? 0 : _typeof(exports)) && "object" == ( false ? 0 : _typeof(module)) ? module.exports = e() :  true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (e),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}(window, function () {
  return function (t) {
    var e = {};
    function r(n) {
      if (e[n]) return e[n].exports;
      var i = e[n] = {
        i: n,
        l: !1,
        exports: {}
      };
      return t[n].call(i.exports, i, i.exports, r), i.l = !0, i.exports;
    }
    return r.m = t, r.c = e, r.d = function (t, e, n) {
      r.o(t, e) || Object.defineProperty(t, e, {
        configurable: !1,
        enumerable: !0,
        get: n
      });
    }, r.r = function (t) {
      Object.defineProperty(t, "__esModule", {
        value: !0
      });
    }, r.n = function (t) {
      var e = t && t.__esModule ? function () {
        return t.default;
      } : function () {
        return t;
      };
      return r.d(e, "a", e), e;
    }, r.o = function (t, e) {
      return Object.prototype.hasOwnProperty.call(t, e);
    }, r.p = "", r(r.s = 7);
  }([function (t, e, r) {
    "use strict";

    Object.defineProperty(e, "__esModule", {
      value: !0
    });
    e.loadImageElement = function (t, e) {
      return new Promise(function (r, n) {
        t.addEventListener("load", function () {
          r(t);
        }, !1), t.addEventListener("error", function (t) {
          n(t);
        }, !1), t.src = e;
      });
    }, e.resize = function (t, e, r, n) {
      if (!r && !n) return {
        currentWidth: t,
        currentHeight: e
      };
      var i = t / e,
        o = void 0,
        a = void 0;
      return i > r / n ? a = (o = Math.min(t, r)) / i : o = (a = Math.min(e, n)) * i, {
        width: o,
        height: a
      };
    };
  }, function (t, e, r) {
    "use strict";

    Object.defineProperty(e, "__esModule", {
      value: !0
    });
    e.base64ToFile = function (t) {
      for (var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "image/jpeg", r = window.atob(t), n = [], i = 0; i < r.length; i++) n[i] = r.charCodeAt(i);
      return new window.Blob([new Uint8Array(n)], {
        type: e
      });
    }, e.imageToCanvas = function (t, e, r, n) {
      var i = document.createElement("canvas"),
        o = i.getContext("2d");
      if (i.width = e, i.height = r, !n || n > 8) return o.drawImage(t, 0, 0, i.width, i.height), i;
      switch (n > 4 && (i.width = r, i.height = e), n) {
        case 2:
          o.translate(e, 0), o.scale(-1, 1);
          break;
        case 3:
          o.translate(e, r), o.rotate(Math.PI);
          break;
        case 4:
          o.translate(0, r), o.scale(1, -1);
          break;
        case 5:
          o.rotate(.5 * Math.PI), o.scale(1, -1);
          break;
        case 6:
          o.rotate(.5 * Math.PI), o.translate(0, -r);
          break;
        case 7:
          o.rotate(.5 * Math.PI), o.translate(e, -r), o.scale(-1, 1);
          break;
        case 8:
          o.rotate(-.5 * Math.PI), o.translate(-e, 0);
      }
      return n > 4 ? o.drawImage(t, 0, 0, i.height, i.width) : o.drawImage(t, 0, 0, i.width, i.height), i;
    }, e.canvasToBlob = function (t, e) {
      return new Promise(function (r, n) {
        t.toBlob(function (t) {
          r(t);
        }, "image/jpeg", e);
      });
    }, e.size = function (t) {
      return {
        kB: .001 * t,
        MB: 1e-6 * t
      };
    }, e.blobToBase64 = function (t) {
      return new Promise(function (e, r) {
        var n = new window.FileReader();
        n.addEventListener("load", function (t) {
          e(t.target.result);
        }, !1), n.addEventListener("error", function (t) {
          r(t);
        }, !1), n.readAsDataURL(t);
      });
    };
  }, function (t, e, r) {
    t.exports = r(6);
  }, function (t, e, r) {
    "use strict";

    Object.defineProperty(e, "__esModule", {
      value: !0
    });
    e.extractOrientation = function (t) {
      return new Promise(function (e, r) {
        var n = new window.FileReader();
        n.onload = function (t) {
          var r = new DataView(t.target.result);
          65496 !== r.getUint16(0, !1) && e(-2);
          for (var n = r.byteLength, i = 2; i < n;) {
            var o = r.getUint16(i, !1);
            if (i += 2, 65505 === o) {
              1165519206 !== r.getUint32(i += 2, !1) && e(-1);
              var a = 18761 === r.getUint16(i += 6, !1);
              i += r.getUint32(i + 4, a);
              var u = r.getUint16(i, a);
              i += 2;
              for (var s = 0; s < u; s++) 274 === r.getUint16(i + 12 * s, a) && e(r.getUint16(i + 12 * s + 8, a));
            } else {
              if (65280 != (65280 & o)) break;
              i += r.getUint16(i, !1);
            }
          }
          e(-1);
        }, n.readAsArrayBuffer(t.slice(0, 65536));
      });
    };
  }, function (t, e, r) {
    "use strict";

    Object.defineProperty(e, "__esModule", {
      value: !0
    });
    var n,
      i = r(2),
      o = (n = i) && n.__esModule ? n : {
        default: n
      },
      a = function () {
        function t(t, e) {
          for (var r = 0; r < e.length; r++) {
            var n = e[r];
            n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(t, n.key, n);
          }
        }
        return function (e, r, n) {
          return r && t(e.prototype, r), n && t(e, n), e;
        };
      }(),
      u = r(3),
      s = r(0),
      c = r(1);
    function f(t) {
      return function () {
        var e = t.apply(this, arguments);
        return new Promise(function (t, r) {
          return function n(i, o) {
            try {
              var a = e[i](o),
                u = a.value;
            } catch (t) {
              return void r(t);
            }
            if (!a.done) return Promise.resolve(u).then(function (t) {
              n("next", t);
            }, function (t) {
              n("throw", t);
            });
            t(u);
          }("next");
        });
      };
    }
    var l = function () {
      function t(e) {
        !function (t, e) {
          if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function");
        }(this, t), this.data = e, this.name = e.name, this.type = e.type, this.size = e.size;
      }
      return a(t, [{
        key: "setData",
        value: function value(t) {
          this.data = t, this.size = t.size, this.type = t.type;
        }
      }, {
        key: "_calculateOrientation",
        value: function () {
          var t = f(o.default.mark(function t() {
            var e;
            return o.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return t.next = 2, (0, u.extractOrientation)(this.data);
                case 2:
                  e = t.sent, this.orientation = e;
                case 4:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function () {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "load",
        value: function () {
          var t = f(o.default.mark(function t() {
            var e, r;
            return o.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return t.next = 2, this._calculateOrientation();
                case 2:
                  return e = URL.createObjectURL(this.data), r = new window.Image(), t.next = 6, (0, s.loadImageElement)(r, e);
                case 6:
                  URL.revokeObjectURL(e), this._img = r, this.width = r.naturalWidth, this.height = r.naturalHeight;
                case 10:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function () {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "getCanvas",
        value: function value(t, e, r) {
          return void 0 !== r ? (0, c.imageToCanvas)(this._img, t, e, r) : (0, c.imageToCanvas)(this._img, t, e, this.orientation);
        }
      }]), t;
    }();
    e.default = l, t.exports = e.default;
  }, function (t, e) {
    !function (e) {
      "use strict";

      var r,
        n = Object.prototype,
        i = n.hasOwnProperty,
        o = "function" == typeof Symbol ? Symbol : {},
        a = o.iterator || "@@iterator",
        u = o.asyncIterator || "@@asyncIterator",
        s = o.toStringTag || "@@toStringTag",
        c = "object" == _typeof(t),
        f = e.regeneratorRuntime;
      if (f) c && (t.exports = f);else {
        (f = e.regeneratorRuntime = c ? t.exports : {}).wrap = w;
        var l = "suspendedStart",
          h = "suspendedYield",
          p = "executing",
          d = "completed",
          A = {},
          v = {};
        v[a] = function () {
          return this;
        };
        var y = Object.getPrototypeOf,
          g = y && y(y(z([])));
        g && g !== n && i.call(g, a) && (v = g);
        var m = B.prototype = x.prototype = Object.create(v);
        b.prototype = m.constructor = B, B.constructor = b, B[s] = b.displayName = "GeneratorFunction", f.isGeneratorFunction = function (t) {
          var e = "function" == typeof t && t.constructor;
          return !!e && (e === b || "GeneratorFunction" === (e.displayName || e.name));
        }, f.mark = function (t) {
          return Object.setPrototypeOf ? Object.setPrototypeOf(t, B) : (t.__proto__ = B, s in t || (t[s] = "GeneratorFunction")), t.prototype = Object.create(m), t;
        }, f.awrap = function (t) {
          return {
            __await: t
          };
        }, Q(_.prototype), _.prototype[u] = function () {
          return this;
        }, f.AsyncIterator = _, f.async = function (t, e, r, n) {
          var i = new _(w(t, e, r, n));
          return f.isGeneratorFunction(e) ? i : i.next().then(function (t) {
            return t.done ? t.value : i.next();
          });
        }, Q(m), m[s] = "Generator", m[a] = function () {
          return this;
        }, m.toString = function () {
          return "[object Generator]";
        }, f.keys = function (t) {
          var e = [];
          for (var r in t) e.push(r);
          return e.reverse(), function r() {
            for (; e.length;) {
              var n = e.pop();
              if (n in t) return r.value = n, r.done = !1, r;
            }
            return r.done = !0, r;
          };
        }, f.values = z, O.prototype = {
          constructor: O,
          reset: function reset(t) {
            if (this.prev = 0, this.next = 0, this.sent = this._sent = r, this.done = !1, this.delegate = null, this.method = "next", this.arg = r, this.tryEntries.forEach(P), !t) for (var e in this) "t" === e.charAt(0) && i.call(this, e) && !isNaN(+e.slice(1)) && (this[e] = r);
          },
          stop: function stop() {
            this.done = !0;
            var t = this.tryEntries[0].completion;
            if ("throw" === t.type) throw t.arg;
            return this.rval;
          },
          dispatchException: function dispatchException(t) {
            if (this.done) throw t;
            var e = this;
            function n(n, i) {
              return u.type = "throw", u.arg = t, e.next = n, i && (e.method = "next", e.arg = r), !!i;
            }
            for (var o = this.tryEntries.length - 1; o >= 0; --o) {
              var a = this.tryEntries[o],
                u = a.completion;
              if ("root" === a.tryLoc) return n("end");
              if (a.tryLoc <= this.prev) {
                var s = i.call(a, "catchLoc"),
                  c = i.call(a, "finallyLoc");
                if (s && c) {
                  if (this.prev < a.catchLoc) return n(a.catchLoc, !0);
                  if (this.prev < a.finallyLoc) return n(a.finallyLoc);
                } else if (s) {
                  if (this.prev < a.catchLoc) return n(a.catchLoc, !0);
                } else {
                  if (!c) throw new Error("try statement without catch or finally");
                  if (this.prev < a.finallyLoc) return n(a.finallyLoc);
                }
              }
            }
          },
          abrupt: function abrupt(t, e) {
            for (var r = this.tryEntries.length - 1; r >= 0; --r) {
              var n = this.tryEntries[r];
              if (n.tryLoc <= this.prev && i.call(n, "finallyLoc") && this.prev < n.finallyLoc) {
                var o = n;
                break;
              }
            }
            o && ("break" === t || "continue" === t) && o.tryLoc <= e && e <= o.finallyLoc && (o = null);
            var a = o ? o.completion : {};
            return a.type = t, a.arg = e, o ? (this.method = "next", this.next = o.finallyLoc, A) : this.complete(a);
          },
          complete: function complete(t, e) {
            if ("throw" === t.type) throw t.arg;
            return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), A;
          },
          finish: function finish(t) {
            for (var e = this.tryEntries.length - 1; e >= 0; --e) {
              var r = this.tryEntries[e];
              if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), P(r), A;
            }
          },
          catch: function _catch(t) {
            for (var e = this.tryEntries.length - 1; e >= 0; --e) {
              var r = this.tryEntries[e];
              if (r.tryLoc === t) {
                var n = r.completion;
                if ("throw" === n.type) {
                  var i = n.arg;
                  P(r);
                }
                return i;
              }
            }
            throw new Error("illegal catch attempt");
          },
          delegateYield: function delegateYield(t, e, n) {
            return this.delegate = {
              iterator: z(t),
              resultName: e,
              nextLoc: n
            }, "next" === this.method && (this.arg = r), A;
          }
        };
      }
      function w(t, e, r, n) {
        var i = e && e.prototype instanceof x ? e : x,
          o = Object.create(i.prototype),
          a = new O(n || []);
        return o._invoke = function (t, e, r) {
          var n = l;
          return function (i, o) {
            if (n === p) throw new Error("Generator is already running");
            if (n === d) {
              if ("throw" === i) throw o;
              return j();
            }
            for (r.method = i, r.arg = o;;) {
              var a = r.delegate;
              if (a) {
                var u = k(a, r);
                if (u) {
                  if (u === A) continue;
                  return u;
                }
              }
              if ("next" === r.method) r.sent = r._sent = r.arg;else if ("throw" === r.method) {
                if (n === l) throw n = d, r.arg;
                r.dispatchException(r.arg);
              } else "return" === r.method && r.abrupt("return", r.arg);
              n = p;
              var s = E(t, e, r);
              if ("normal" === s.type) {
                if (n = r.done ? d : h, s.arg === A) continue;
                return {
                  value: s.arg,
                  done: r.done
                };
              }
              "throw" === s.type && (n = d, r.method = "throw", r.arg = s.arg);
            }
          };
        }(t, r, a), o;
      }
      function E(t, e, r) {
        try {
          return {
            type: "normal",
            arg: t.call(e, r)
          };
        } catch (t) {
          return {
            type: "throw",
            arg: t
          };
        }
      }
      function x() {}
      function b() {}
      function B() {}
      function Q(t) {
        ["next", "throw", "return"].forEach(function (e) {
          t[e] = function (t) {
            return this._invoke(e, t);
          };
        });
      }
      function _(t) {
        var e;
        this._invoke = function (r, n) {
          function o() {
            return new Promise(function (e, o) {
              !function e(r, n, o, a) {
                var u = E(t[r], t, n);
                if ("throw" !== u.type) {
                  var s = u.arg,
                    c = s.value;
                  return c && "object" == _typeof(c) && i.call(c, "__await") ? Promise.resolve(c.__await).then(function (t) {
                    e("next", t, o, a);
                  }, function (t) {
                    e("throw", t, o, a);
                  }) : Promise.resolve(c).then(function (t) {
                    s.value = t, o(s);
                  }, a);
                }
                a(u.arg);
              }(r, n, e, o);
            });
          }
          return e = e ? e.then(o, o) : o();
        };
      }
      function k(t, e) {
        var n = t.iterator[e.method];
        if (n === r) {
          if (e.delegate = null, "throw" === e.method) {
            if (t.iterator.return && (e.method = "return", e.arg = r, k(t, e), "throw" === e.method)) return A;
            e.method = "throw", e.arg = new TypeError("The iterator does not provide a 'throw' method");
          }
          return A;
        }
        var i = E(n, t.iterator, e.arg);
        if ("throw" === i.type) return e.method = "throw", e.arg = i.arg, e.delegate = null, A;
        var o = i.arg;
        return o ? o.done ? (e[t.resultName] = o.value, e.next = t.nextLoc, "return" !== e.method && (e.method = "next", e.arg = r), e.delegate = null, A) : o : (e.method = "throw", e.arg = new TypeError("iterator result is not an object"), e.delegate = null, A);
      }
      function L(t) {
        var e = {
          tryLoc: t[0]
        };
        1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
      }
      function P(t) {
        var e = t.completion || {};
        e.type = "normal", delete e.arg, t.completion = e;
      }
      function O(t) {
        this.tryEntries = [{
          tryLoc: "root"
        }], t.forEach(L, this), this.reset(!0);
      }
      function z(t) {
        if (t) {
          var e = t[a];
          if (e) return e.call(t);
          if ("function" == typeof t.next) return t;
          if (!isNaN(t.length)) {
            var n = -1,
              o = function e() {
                for (; ++n < t.length;) if (i.call(t, n)) return e.value = t[n], e.done = !1, e;
                return e.value = r, e.done = !0, e;
              };
            return o.next = o;
          }
        }
        return {
          next: j
        };
      }
      function j() {
        return {
          value: r,
          done: !0
        };
      }
    }(function () {
      return this;
    }() || Function("return this")());
  }, function (t, e, r) {
    var n = function () {
        return this;
      }() || Function("return this")(),
      i = n.regeneratorRuntime && Object.getOwnPropertyNames(n).indexOf("regeneratorRuntime") >= 0,
      o = i && n.regeneratorRuntime;
    if (n.regeneratorRuntime = void 0, t.exports = r(5), i) n.regeneratorRuntime = o;else try {
      delete n.regeneratorRuntime;
    } catch (t) {
      n.regeneratorRuntime = void 0;
    }
  }, function (t, e, r) {
    "use strict";

    Object.defineProperty(e, "__esModule", {
      value: !0
    });
    var n = s(r(2)),
      i = function () {
        function t(t, e) {
          for (var r = 0; r < e.length; r++) {
            var n = e[r];
            n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(t, n.key, n);
          }
        }
        return function (e, r, n) {
          return r && t(e.prototype, r), n && t(e, n), e;
        };
      }(),
      o = function (t) {
        if (t && t.__esModule) return t;
        var e = {};
        if (null != t) for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && (e[r] = t[r]);
        return e.default = t, e;
      }(r(1)),
      a = r(0),
      u = s(r(4));
    function s(t) {
      return t && t.__esModule ? t : {
        default: t
      };
    }
    function c(t) {
      return function () {
        var e = t.apply(this, arguments);
        return new Promise(function (t, r) {
          return function n(i, o) {
            try {
              var a = e[i](o),
                u = a.value;
            } catch (t) {
              return void r(t);
            }
            if (!a.done) return Promise.resolve(u).then(function (t) {
              n("next", t);
            }, function (t) {
              n("throw", t);
            });
            t(u);
          }("next");
        });
      };
    }
    var f = function () {
      function t() {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
        !function (t, e) {
          if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function");
        }(this, t), this.setOptions(e);
      }
      return i(t, [{
        key: "setOptions",
        value: function value(t) {
          var e = {
              targetSize: 1 / 0,
              quality: .75,
              minQuality: .5,
              qualityStepSize: .1,
              maxWidth: 1920,
              maxHeight: 1920,
              resize: !0,
              throwIfSizeNotReached: !1,
              autoRotate: !0
            },
            r = new Proxy(t, {
              get: function get(t, r) {
                return r in t ? t[r] : e[r];
              }
            });
          this.options = r;
        }
      }, {
        key: "_compressFile",
        value: function () {
          var t = c(n.default.mark(function t(e) {
            var r, i;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return r = new u.default(e), (i = {}).start = window.performance.now(), i.quality = this.options.quality, i.startType = r.type, t.next = 7, r.load();
                case 7:
                  return t.next = 9, this._compressImage(r, i);
                case 9:
                  return t.abrupt("return", t.sent);
                case 10:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function (e) {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "_compressImage",
        value: function () {
          var t = c(n.default.mark(function t(e, r) {
            var i, u, s, c, f;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return r.startWidth = e.width, r.startHeight = e.height, i = void 0, u = void 0, this.options.resize ? (s = (0, a.resize)(e.width, e.height, this.options.maxWidth, this.options.maxHeight), i = s.width, u = s.height) : (i = e.width, u = e.height), r.endWidth = i, r.endHeight = u, c = this.doAutoRotation ? void 0 : 1, f = e.getCanvas(i, u, c), r.iterations = 0, r.startSizeMB = o.size(e.size).MB, t.next = 12, this._loopCompression(f, e, r);
                case 12:
                  return r.endSizeMB = o.size(e.size).MB, r.sizeReducedInPercent = (r.startSizeMB - r.endSizeMB) / r.startSizeMB * 100, r.end = window.performance.now(), r.elapsedTimeInSeconds = (r.end - r.start) / 1e3, r.endType = e.type, t.abrupt("return", {
                    photo: e,
                    info: r
                  });
                case 18:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function (e, r) {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "_loopCompression",
        value: function () {
          var t = c(n.default.mark(function t(e, r, i) {
            var a;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return i.iterations++, t.t0 = r, t.next = 4, o.canvasToBlob(e, i.quality);
                case 4:
                  if (t.t1 = t.sent, t.t0.setData.call(t.t0, t.t1), 1 == i.iterations && (r.width = i.endWidth, r.height = i.endHeight), !(o.size(r.size).MB > this.options.targetSize)) {
                    t.next = 24;
                    break;
                  }
                  if (!(i.quality.toFixed(10) - .1 < this.options.minQuality)) {
                    t.next = 18;
                    break;
                  }
                  if (a = "Couldn't compress image to target size while maintaining quality.\n        Target size: " + this.options.targetSize + "\n        Actual size: " + o.size(r.size).MB, this.options.throwIfSizeNotReached) {
                    t.next = 14;
                    break;
                  }
                  console.error(a), t.next = 15;
                  break;
                case 14:
                  throw new Error(a);
                case 15:
                  return t.abrupt("return");
                case 18:
                  return i.quality -= this.options.qualityStepSize, t.next = 21, this._loopCompression(e, r, i);
                case 21:
                  return t.abrupt("return", t.sent);
                case 22:
                  t.next = 25;
                  break;
                case 24:
                  return t.abrupt("return");
                case 25:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function (e, r, n) {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "setAutoRotate",
        value: function () {
          var e = c(n.default.mark(function e() {
            var r;
            return n.default.wrap(function (e) {
              for (;;) switch (e.prev = e.next) {
                case 0:
                  return e.next = 2, t.automaticRotationFeatureTest();
                case 2:
                  r = e.sent, this.doAutoRotation = this.options.autoRotate && !r;
                case 4:
                case "end":
                  return e.stop();
              }
            }, e, this);
          }));
          return function () {
            return e.apply(this, arguments);
          };
        }()
      }, {
        key: "compress",
        value: function () {
          var t = c(n.default.mark(function t(e) {
            var r = this;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return t.next = 2, this.setAutoRotate();
                case 2:
                  return t.abrupt("return", Promise.all(e.map(function (t) {
                    return r._compressFile(t);
                  })));
                case 3:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function (e) {
            return t.apply(this, arguments);
          };
        }()
      }], [{
        key: "blobToBase64",
        value: function () {
          var t = c(n.default.mark(function t() {
            var e = arguments;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return t.next = 2, o.blobToBase64.apply(o, e);
                case 2:
                  return t.abrupt("return", t.sent);
                case 3:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function () {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "loadImageElement",
        value: function () {
          var t = c(n.default.mark(function t() {
            var e = arguments;
            return n.default.wrap(function (t) {
              for (;;) switch (t.prev = t.next) {
                case 0:
                  return t.next = 2, a.loadImageElement.apply(void 0, e);
                case 2:
                  return t.abrupt("return", t.sent);
                case 3:
                case "end":
                  return t.stop();
              }
            }, t, this);
          }));
          return function () {
            return t.apply(this, arguments);
          };
        }()
      }, {
        key: "automaticRotationFeatureTest",
        value: function value() {
          return new Promise(function (t) {
            var e = new Image();
            e.onload = function () {
              var r = 1 === e.width && 2 === e.height;
              t(r);
            }, e.src = "data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/xABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q==";
          });
        }
      }]), t;
    }();
    e.default = f, t.exports = e.default;
  }]);
});

/***/ }),

/***/ 2977:
/***/ ((module) => {

"use strict";


/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
module.exports = function (cssWithMappingToString) {
  var list = [];

  // return the list of modules as css string
  list.toString = function toString() {
    return this.map(function (item) {
      var content = "";
      var needLayer = typeof item[5] !== "undefined";
      if (item[4]) {
        content += "@supports (".concat(item[4], ") {");
      }
      if (item[2]) {
        content += "@media ".concat(item[2], " {");
      }
      if (needLayer) {
        content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
      }
      content += cssWithMappingToString(item);
      if (needLayer) {
        content += "}";
      }
      if (item[2]) {
        content += "}";
      }
      if (item[4]) {
        content += "}";
      }
      return content;
    }).join("");
  };

  // import a list of modules into the list
  list.i = function i(modules, media, dedupe, supports, layer) {
    if (typeof modules === "string") {
      modules = [[null, modules, undefined]];
    }
    var alreadyImportedModules = {};
    if (dedupe) {
      for (var k = 0; k < this.length; k++) {
        var id = this[k][0];
        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }
    for (var _k = 0; _k < modules.length; _k++) {
      var item = [].concat(modules[_k]);
      if (dedupe && alreadyImportedModules[item[0]]) {
        continue;
      }
      if (typeof layer !== "undefined") {
        if (typeof item[5] === "undefined") {
          item[5] = layer;
        } else {
          item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
          item[5] = layer;
        }
      }
      if (media) {
        if (!item[2]) {
          item[2] = media;
        } else {
          item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
          item[2] = media;
        }
      }
      if (supports) {
        if (!item[4]) {
          item[4] = "".concat(supports);
        } else {
          item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
          item[4] = supports;
        }
      }
      list.push(item);
    }
  };
  return list;
};

/***/ }),

/***/ 8539:
/***/ ((module) => {

"use strict";


module.exports = function (item) {
  var content = item[1];
  var cssMapping = item[3];
  if (!cssMapping) {
    return content;
  }
  if (typeof btoa === "function") {
    var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
    var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
    var sourceMapping = "/*# ".concat(data, " */");
    return [content].concat([sourceMapping]).join("\n");
  }
  return [content].join("\n");
};

/***/ }),

/***/ 4735:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;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 (t, e) {
  "object" == ( false ? 0 : _typeof(exports)) && "undefined" != "object" ? module.exports = e() :  true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
		__WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}(this, function () {
  "use strict";

  var t = 1e3,
    e = 6e4,
    n = 36e5,
    r = "millisecond",
    i = "second",
    s = "minute",
    u = "hour",
    a = "day",
    o = "week",
    f = "month",
    h = "quarter",
    c = "year",
    d = "date",
    l = "Invalid Date",
    $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,
    y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,
    M = {
      name: "en",
      weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
      months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
      ordinal: function ordinal(t) {
        var e = ["th", "st", "nd", "rd"],
          n = t % 100;
        return "[" + t + (e[(n - 20) % 10] || e[n] || e[0]) + "]";
      }
    },
    m = function m(t, e, n) {
      var r = String(t);
      return !r || r.length >= e ? t : "" + Array(e + 1 - r.length).join(n) + t;
    },
    v = {
      s: m,
      z: function z(t) {
        var e = -t.utcOffset(),
          n = Math.abs(e),
          r = Math.floor(n / 60),
          i = n % 60;
        return (e <= 0 ? "+" : "-") + m(r, 2, "0") + ":" + m(i, 2, "0");
      },
      m: function t(e, n) {
        if (e.date() < n.date()) return -t(n, e);
        var r = 12 * (n.year() - e.year()) + (n.month() - e.month()),
          i = e.clone().add(r, f),
          s = n - i < 0,
          u = e.clone().add(r + (s ? -1 : 1), f);
        return +(-(r + (n - i) / (s ? i - u : u - i)) || 0);
      },
      a: function a(t) {
        return t < 0 ? Math.ceil(t) || 0 : Math.floor(t);
      },
      p: function p(t) {
        return {
          M: f,
          y: c,
          w: o,
          d: a,
          D: d,
          h: u,
          m: s,
          s: i,
          ms: r,
          Q: h
        }[t] || String(t || "").toLowerCase().replace(/s$/, "");
      },
      u: function u(t) {
        return void 0 === t;
      }
    },
    g = "en",
    D = {};
  D[g] = M;
  var p = function p(t) {
      return t instanceof _;
    },
    S = function t(e, n, r) {
      var i;
      if (!e) return g;
      if ("string" == typeof e) {
        var s = e.toLowerCase();
        D[s] && (i = s), n && (D[s] = n, i = s);
        var u = e.split("-");
        if (!i && u.length > 1) return t(u[0]);
      } else {
        var a = e.name;
        D[a] = e, i = a;
      }
      return !r && i && (g = i), i || !r && g;
    },
    w = function w(t, e) {
      if (p(t)) return t.clone();
      var n = "object" == _typeof(e) ? e : {};
      return n.date = t, n.args = arguments, new _(n);
    },
    O = v;
  O.l = S, O.i = p, O.w = function (t, e) {
    return w(t, {
      locale: e.$L,
      utc: e.$u,
      x: e.$x,
      $offset: e.$offset
    });
  };
  var _ = function () {
      function M(t) {
        this.$L = S(t.locale, null, !0), this.parse(t);
      }
      var m = M.prototype;
      return m.parse = function (t) {
        this.$d = function (t) {
          var e = t.date,
            n = t.utc;
          if (null === e) return new Date(NaN);
          if (O.u(e)) return new Date();
          if (e instanceof Date) return new Date(e);
          if ("string" == typeof e && !/Z$/i.test(e)) {
            var r = e.match($);
            if (r) {
              var i = r[2] - 1 || 0,
                s = (r[7] || "0").substring(0, 3);
              return n ? new Date(Date.UTC(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s)) : new Date(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s);
            }
          }
          return new Date(e);
        }(t), this.$x = t.x || {}, this.init();
      }, m.init = function () {
        var t = this.$d;
        this.$y = t.getFullYear(), this.$M = t.getMonth(), this.$D = t.getDate(), this.$W = t.getDay(), this.$H = t.getHours(), this.$m = t.getMinutes(), this.$s = t.getSeconds(), this.$ms = t.getMilliseconds();
      }, m.$utils = function () {
        return O;
      }, m.isValid = function () {
        return !(this.$d.toString() === l);
      }, m.isSame = function (t, e) {
        var n = w(t);
        return this.startOf(e) <= n && n <= this.endOf(e);
      }, m.isAfter = function (t, e) {
        return w(t) < this.startOf(e);
      }, m.isBefore = function (t, e) {
        return this.endOf(e) < w(t);
      }, m.$g = function (t, e, n) {
        return O.u(t) ? this[e] : this.set(n, t);
      }, m.unix = function () {
        return Math.floor(this.valueOf() / 1e3);
      }, m.valueOf = function () {
        return this.$d.getTime();
      }, m.startOf = function (t, e) {
        var n = this,
          r = !!O.u(e) || e,
          h = O.p(t),
          l = function l(t, e) {
            var i = O.w(n.$u ? Date.UTC(n.$y, e, t) : new Date(n.$y, e, t), n);
            return r ? i : i.endOf(a);
          },
          $ = function $(t, e) {
            return O.w(n.toDate()[t].apply(n.toDate("s"), (r ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e)), n);
          },
          y = this.$W,
          M = this.$M,
          m = this.$D,
          v = "set" + (this.$u ? "UTC" : "");
        switch (h) {
          case c:
            return r ? l(1, 0) : l(31, 11);
          case f:
            return r ? l(1, M) : l(0, M + 1);
          case o:
            var g = this.$locale().weekStart || 0,
              D = (y < g ? y + 7 : y) - g;
            return l(r ? m - D : m + (6 - D), M);
          case a:
          case d:
            return $(v + "Hours", 0);
          case u:
            return $(v + "Minutes", 1);
          case s:
            return $(v + "Seconds", 2);
          case i:
            return $(v + "Milliseconds", 3);
          default:
            return this.clone();
        }
      }, m.endOf = function (t) {
        return this.startOf(t, !1);
      }, m.$set = function (t, e) {
        var n,
          o = O.p(t),
          h = "set" + (this.$u ? "UTC" : ""),
          l = (n = {}, n[a] = h + "Date", n[d] = h + "Date", n[f] = h + "Month", n[c] = h + "FullYear", n[u] = h + "Hours", n[s] = h + "Minutes", n[i] = h + "Seconds", n[r] = h + "Milliseconds", n)[o],
          $ = o === a ? this.$D + (e - this.$W) : e;
        if (o === f || o === c) {
          var y = this.clone().set(d, 1);
          y.$d[l]($), y.init(), this.$d = y.set(d, Math.min(this.$D, y.daysInMonth())).$d;
        } else l && this.$d[l]($);
        return this.init(), this;
      }, m.set = function (t, e) {
        return this.clone().$set(t, e);
      }, m.get = function (t) {
        return this[O.p(t)]();
      }, m.add = function (r, h) {
        var d,
          l = this;
        r = Number(r);
        var $ = O.p(h),
          y = function y(t) {
            var e = w(l);
            return O.w(e.date(e.date() + Math.round(t * r)), l);
          };
        if ($ === f) return this.set(f, this.$M + r);
        if ($ === c) return this.set(c, this.$y + r);
        if ($ === a) return y(1);
        if ($ === o) return y(7);
        var M = (d = {}, d[s] = e, d[u] = n, d[i] = t, d)[$] || 1,
          m = this.$d.getTime() + r * M;
        return O.w(m, this);
      }, m.subtract = function (t, e) {
        return this.add(-1 * t, e);
      }, m.format = function (t) {
        var e = this,
          n = this.$locale();
        if (!this.isValid()) return n.invalidDate || l;
        var r = t || "YYYY-MM-DDTHH:mm:ssZ",
          i = O.z(this),
          s = this.$H,
          u = this.$m,
          a = this.$M,
          o = n.weekdays,
          f = n.months,
          h = function h(t, n, i, s) {
            return t && (t[n] || t(e, r)) || i[n].slice(0, s);
          },
          c = function c(t) {
            return O.s(s % 12 || 12, t, "0");
          },
          d = n.meridiem || function (t, e, n) {
            var r = t < 12 ? "AM" : "PM";
            return n ? r.toLowerCase() : r;
          },
          $ = {
            YY: String(this.$y).slice(-2),
            YYYY: O.s(this.$y, 4, "0"),
            M: a + 1,
            MM: O.s(a + 1, 2, "0"),
            MMM: h(n.monthsShort, a, f, 3),
            MMMM: h(f, a),
            D: this.$D,
            DD: O.s(this.$D, 2, "0"),
            d: String(this.$W),
            dd: h(n.weekdaysMin, this.$W, o, 2),
            ddd: h(n.weekdaysShort, this.$W, o, 3),
            dddd: o[this.$W],
            H: String(s),
            HH: O.s(s, 2, "0"),
            h: c(1),
            hh: c(2),
            a: d(s, u, !0),
            A: d(s, u, !1),
            m: String(u),
            mm: O.s(u, 2, "0"),
            s: String(this.$s),
            ss: O.s(this.$s, 2, "0"),
            SSS: O.s(this.$ms, 3, "0"),
            Z: i
          };
        return r.replace(y, function (t, e) {
          return e || $[t] || i.replace(":", "");
        });
      }, m.utcOffset = function () {
        return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
      }, m.diff = function (r, d, l) {
        var $,
          y = O.p(d),
          M = w(r),
          m = (M.utcOffset() - this.utcOffset()) * e,
          v = this - M,
          g = O.m(this, M);
        return g = ($ = {}, $[c] = g / 12, $[f] = g, $[h] = g / 3, $[o] = (v - m) / 6048e5, $[a] = (v - m) / 864e5, $[u] = v / n, $[s] = v / e, $[i] = v / t, $)[y] || v, l ? g : O.a(g);
      }, m.daysInMonth = function () {
        return this.endOf(f).$D;
      }, m.$locale = function () {
        return D[this.$L];
      }, m.locale = function (t, e) {
        if (!t) return this.$L;
        var n = this.clone(),
          r = S(t, e, !0);
        return r && (n.$L = r), n;
      }, m.clone = function () {
        return O.w(this.$d, this);
      }, m.toDate = function () {
        return new Date(this.valueOf());
      }, m.toJSON = function () {
        return this.isValid() ? this.toISOString() : null;
      }, m.toISOString = function () {
        return this.$d.toISOString();
      }, m.toString = function () {
        return this.$d.toUTCString();
      }, M;
    }(),
    T = _.prototype;
  return w.prototype = T, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", f], ["$y", c], ["$D", d]].forEach(function (t) {
    T[t[1]] = function (e) {
      return this.$g(e, t[0], t[1]);
    };
  }), w.extend = function (t, e) {
    return t.$i || (t(e, _, w), t.$i = !0), w;
  }, w.locale = S, w.isDayjs = p, w.unix = function (t) {
    return w(1e3 * t);
  }, w.en = D[g], w.Ls = D, w.p = {}, w;
});

/***/ }),

/***/ 4289:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;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 (e, t) {
  "object" == ( false ? 0 : _typeof(exports)) && "undefined" != "object" ? module.exports = t() :  true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (t),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
		__WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}(this, function () {
  "use strict";

  return function (e, t) {
    var r = t.prototype,
      n = r.format;
    r.format = function (e) {
      var t = this,
        r = this.$locale();
      if (!this.isValid()) return n.bind(this)(e);
      var s = this.$utils(),
        a = (e || "YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g, function (e) {
          switch (e) {
            case "Q":
              return Math.ceil((t.$M + 1) / 3);
            case "Do":
              return r.ordinal(t.$D);
            case "gggg":
              return t.weekYear();
            case "GGGG":
              return t.isoWeekYear();
            case "wo":
              return r.ordinal(t.week(), "W");
            case "w":
            case "ww":
              return s.s(t.week(), "w" === e ? 1 : 2, "0");
            case "W":
            case "WW":
              return s.s(t.isoWeek(), "W" === e ? 1 : 2, "0");
            case "k":
            case "kk":
              return s.s(String(0 === t.$H ? 24 : t.$H), "k" === e ? 1 : 2, "0");
            case "X":
              return Math.floor(t.$d.getTime() / 1e3);
            case "x":
              return t.$d.getTime();
            case "z":
              return "[" + t.offsetName() + "]";
            case "zzz":
              return "[" + t.offsetName("long") + "]";
            default:
              return e;
          }
        });
      return n.bind(this)(a);
    };
  };
});

/***/ }),

/***/ 1754:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof2(obj) {
  "@babel/helpers - typeof";

  return _typeof2 = "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;
  }, _typeof2(obj);
}
/*! @license DOMPurify 2.4.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.5/LICENSE */

(function (global, factory) {
  ( false ? 0 : _typeof2(exports)) === 'object' && "object" !== 'undefined' ? module.exports = factory() :  true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
		__WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : (0);
})(this, function () {
  'use strict';

  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 _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };
    return _setPrototypeOf(o, p);
  }
  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 _construct(Parent, args, Class) {
    if (_isNativeReflectConstruct()) {
      _construct = Reflect.construct;
    } else {
      _construct = function _construct(Parent, args, Class) {
        var a = [null];
        a.push.apply(a, args);
        var Constructor = Function.bind.apply(Parent, a);
        var instance = new Constructor();
        if (Class) _setPrototypeOf(instance, Class.prototype);
        return instance;
      };
    }
    return _construct.apply(null, arguments);
  }
  function _toConsumableArray(arr) {
    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  }
  function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  }
  function _iterableToArray(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  }
  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 _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var hasOwnProperty = Object.hasOwnProperty,
    setPrototypeOf = Object.setPrototypeOf,
    isFrozen = Object.isFrozen,
    getPrototypeOf = Object.getPrototypeOf,
    getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  var freeze = Object.freeze,
    seal = Object.seal,
    create = Object.create; // eslint-disable-line import/no-mutable-exports

  var _ref = typeof Reflect !== 'undefined' && Reflect,
    apply = _ref.apply,
    construct = _ref.construct;
  if (!apply) {
    apply = function apply(fun, thisValue, args) {
      return fun.apply(thisValue, args);
    };
  }
  if (!freeze) {
    freeze = function freeze(x) {
      return x;
    };
  }
  if (!seal) {
    seal = function seal(x) {
      return x;
    };
  }
  if (!construct) {
    construct = function construct(Func, args) {
      return _construct(Func, _toConsumableArray(args));
    };
  }
  var arrayForEach = unapply(Array.prototype.forEach);
  var arrayPop = unapply(Array.prototype.pop);
  var arrayPush = unapply(Array.prototype.push);
  var stringToLowerCase = unapply(String.prototype.toLowerCase);
  var stringToString = unapply(String.prototype.toString);
  var stringMatch = unapply(String.prototype.match);
  var stringReplace = unapply(String.prototype.replace);
  var stringIndexOf = unapply(String.prototype.indexOf);
  var stringTrim = unapply(String.prototype.trim);
  var regExpTest = unapply(RegExp.prototype.test);
  var typeErrorCreate = unconstruct(TypeError);
  function unapply(func) {
    return function (thisArg) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }
      return apply(func, thisArg, args);
    };
  }
  function unconstruct(func) {
    return function () {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      return construct(func, args);
    };
  }
  /* Add properties to a lookup table */

  function addToSet(set, array, transformCaseFunc) {
    transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
    if (setPrototypeOf) {
      // Make 'in' and truthy checks like Boolean(set.constructor)
      // independent of any properties defined on Object.prototype.
      // Prevent prototype setters from intercepting set as a this value.
      setPrototypeOf(set, null);
    }
    var l = array.length;
    while (l--) {
      var element = array[l];
      if (typeof element === 'string') {
        var lcElement = transformCaseFunc(element);
        if (lcElement !== element) {
          // Config presets (e.g. tags.js, attrs.js) are immutable.
          if (!isFrozen(array)) {
            array[l] = lcElement;
          }
          element = lcElement;
        }
      }
      set[element] = true;
    }
    return set;
  }
  /* Shallow clone an object */

  function clone(object) {
    var newObject = create(null);
    var property;
    for (property in object) {
      if (apply(hasOwnProperty, object, [property]) === true) {
        newObject[property] = object[property];
      }
    }
    return newObject;
  }
  /* IE10 doesn't support __lookupGetter__ so lets'
   * simulate it. It also automatically checks
   * if the prop is function or getter and behaves
   * accordingly. */

  function lookupGetter(object, prop) {
    while (object !== null) {
      var desc = getOwnPropertyDescriptor(object, prop);
      if (desc) {
        if (desc.get) {
          return unapply(desc.get);
        }
        if (typeof desc.value === 'function') {
          return unapply(desc.value);
        }
      }
      object = getPrototypeOf(object);
    }
    function fallbackValue(element) {
      console.warn('fallback value for', element);
      return null;
    }
    return fallbackValue;
  }
  var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG

  var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
  var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
  // We still need to know them so that we can do namespace
  // checks properly in case one wants to add them to
  // allow-list.

  var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
  var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements,
  // even those that we disallow by default.

  var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  var text = freeze(['#text']);
  var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
  var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
  var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
  var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
  var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode

  var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
  var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape

  var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape

  var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
  );

  var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
  );

  var DOCTYPE_NAME = seal(/^html$/i);
  var getGlobal = function getGlobal() {
    return typeof window === 'undefined' ? null : window;
  };
  /**
   * Creates a no-op policy for internal use only.
   * Don't export this function outside this module!
   * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
   * @param {Document} document The document object (to determine policy name suffix)
   * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
   * are not supported).
   */

  var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
    if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
      return null;
    } // Allow the callers to control the unique policy name
    // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
    // Policy creation with duplicate names throws in Trusted Types.

    var suffix = null;
    var ATTR_NAME = 'data-tt-policy-suffix';
    if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
      suffix = document.currentScript.getAttribute(ATTR_NAME);
    }
    var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
    try {
      return trustedTypes.createPolicy(policyName, {
        createHTML: function createHTML(html) {
          return html;
        },
        createScriptURL: function createScriptURL(scriptUrl) {
          return scriptUrl;
        }
      });
    } catch (_) {
      // Policy creation failed (most likely another DOMPurify script has
      // already run). Skip creating the policy, as this will only cause errors
      // if TT are enforced.
      console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
      return null;
    }
  };
  function createDOMPurify() {
    var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
    var DOMPurify = function DOMPurify(root) {
      return createDOMPurify(root);
    };
    /**
     * Version label, exposed for easier checks
     * if DOMPurify is up to date or not
     */

    DOMPurify.version = '2.4.5';
    /**
     * Array of elements that DOMPurify removed during sanitation.
     * Empty if nothing was removed.
     */

    DOMPurify.removed = [];
    if (!window || !window.document || window.document.nodeType !== 9) {
      // Not running in a browser, provide a factory function
      // so that you can pass your own Window
      DOMPurify.isSupported = false;
      return DOMPurify;
    }
    var originalDocument = window.document;
    var document = window.document;
    var DocumentFragment = window.DocumentFragment,
      HTMLTemplateElement = window.HTMLTemplateElement,
      Node = window.Node,
      Element = window.Element,
      NodeFilter = window.NodeFilter,
      _window$NamedNodeMap = window.NamedNodeMap,
      NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
      HTMLFormElement = window.HTMLFormElement,
      DOMParser = window.DOMParser,
      trustedTypes = window.trustedTypes;
    var ElementPrototype = Element.prototype;
    var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
    var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
    var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
    var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
    // new document created via createHTMLDocument. As per the spec
    // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
    // a new empty registry is used when creating a template contents owner
    // document, so we use that as our parent document to ensure nothing
    // is inherited.

    if (typeof HTMLTemplateElement === 'function') {
      var template = document.createElement('template');
      if (template.content && template.content.ownerDocument) {
        document = template.content.ownerDocument;
      }
    }
    var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
    var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
    var _document = document,
      implementation = _document.implementation,
      createNodeIterator = _document.createNodeIterator,
      createDocumentFragment = _document.createDocumentFragment,
      getElementsByTagName = _document.getElementsByTagName;
    var importNode = originalDocument.importNode;
    var documentMode = {};
    try {
      documentMode = clone(document).documentMode ? document.documentMode : {};
    } catch (_) {}
    var hooks = {};
    /**
     * Expose whether this browser supports running the full DOMPurify.
     */

    DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
    var MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
      ERB_EXPR$1 = ERB_EXPR,
      TMPLIT_EXPR$1 = TMPLIT_EXPR,
      DATA_ATTR$1 = DATA_ATTR,
      ARIA_ATTR$1 = ARIA_ATTR,
      IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
      ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
    var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
    /**
     * We consider the elements and attributes below to be safe. Ideally
     * don't add any new ones but feel free to remove unwanted ones.
     */

    /* allowed element names */

    var ALLOWED_TAGS = null;
    var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
    /* Allowed attribute names */

    var ALLOWED_ATTR = null;
    var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
    /*
     * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
     * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
     * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
     * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
     */

    var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
      tagNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      attributeNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      allowCustomizedBuiltInElements: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: false
      }
    }));
    /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */

    var FORBID_TAGS = null;
    /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */

    var FORBID_ATTR = null;
    /* Decide if ARIA attributes are okay */

    var ALLOW_ARIA_ATTR = true;
    /* Decide if custom data attributes are okay */

    var ALLOW_DATA_ATTR = true;
    /* Decide if unknown protocols are okay */

    var ALLOW_UNKNOWN_PROTOCOLS = false;
    /* Decide if self-closing tags in attributes are allowed.
     * Usually removed due to a mXSS issue in jQuery 3.0 */

    var ALLOW_SELF_CLOSE_IN_ATTR = true;
    /* Output should be safe for common template engines.
     * This means, DOMPurify removes data attributes, mustaches and ERB
     */

    var SAFE_FOR_TEMPLATES = false;
    /* Decide if document with <html>... should be returned */

    var WHOLE_DOCUMENT = false;
    /* Track whether config is already set on this instance of DOMPurify. */

    var SET_CONFIG = false;
    /* Decide if all elements (e.g. style, script) must be children of
     * document.body. By default, browsers might move them to document.head */

    var FORCE_BODY = false;
    /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
     * string (or a TrustedHTML object if Trusted Types are supported).
     * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
     */

    var RETURN_DOM = false;
    /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
     * string  (or a TrustedHTML object if Trusted Types are supported) */

    var RETURN_DOM_FRAGMENT = false;
    /* Try to return a Trusted Type object instead of a string, return a string in
     * case Trusted Types are not supported  */

    var RETURN_TRUSTED_TYPE = false;
    /* Output should be free from DOM clobbering attacks?
     * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
     */

    var SANITIZE_DOM = true;
    /* Achieve full DOM Clobbering protection by isolating the namespace of named
     * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
     *
     * HTML/DOM spec rules that enable DOM Clobbering:
     *   - Named Access on Window (§7.3.3)
     *   - DOM Tree Accessors (§3.1.5)
     *   - Form Element Parent-Child Relations (§4.10.3)
     *   - Iframe srcdoc / Nested WindowProxies (§4.8.5)
     *   - HTMLCollection (§4.2.10.2)
     *
     * Namespace isolation is implemented by prefixing `id` and `name` attributes
     * with a constant string, i.e., `user-content-`
     */

    var SANITIZE_NAMED_PROPS = false;
    var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
    /* Keep element content when removing element? */

    var KEEP_CONTENT = true;
    /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
     * of importing it into a new Document and returning a sanitized copy */

    var IN_PLACE = false;
    /* Allow usage of profiles like html, svg and mathMl */

    var USE_PROFILES = {};
    /* Tags to ignore content of when KEEP_CONTENT is true */

    var FORBID_CONTENTS = null;
    var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
    /* Tags that are safe for data: URIs */

    var DATA_URI_TAGS = null;
    var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
    /* Attributes safe for values like "javascript:" */

    var URI_SAFE_ATTRIBUTES = null;
    var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
    var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
    var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
    var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
    /* Document namespace */

    var NAMESPACE = HTML_NAMESPACE;
    var IS_EMPTY_INPUT = false;
    /* Allowed XHTML+XML namespaces */

    var ALLOWED_NAMESPACES = null;
    var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
    /* Parsing of strict XHTML documents */

    var PARSER_MEDIA_TYPE;
    var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
    var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
    var transformCaseFunc;
    /* Keep a reference to config to pass to hooks */

    var CONFIG = null;
    /* Ideally, do not touch anything below this line */

    /* ______________________________________________ */

    var formElement = document.createElement('form');
    var isRegexOrFunction = function isRegexOrFunction(testValue) {
      return testValue instanceof RegExp || testValue instanceof Function;
    };
    /**
     * _parseConfig
     *
     * @param  {Object} cfg optional config literal
     */
    // eslint-disable-next-line complexity

    var _parseConfig = function _parseConfig(cfg) {
      if (CONFIG && CONFIG === cfg) {
        return;
      }
      /* Shield configuration object from tampering */

      if (!cfg || _typeof(cfg) !== 'object') {
        cfg = {};
      }
      /* Shield configuration object from prototype pollution */

      cfg = clone(cfg);
      PARSER_MEDIA_TYPE =
      // eslint-disable-next-line unicorn/prefer-includes
      SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.

      transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
      /* Set configuration parameters */

      ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
      ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
      ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
      URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES),
      // eslint-disable-line indent
      cfg.ADD_URI_SAFE_ATTR,
      // eslint-disable-line indent
      transformCaseFunc // eslint-disable-line indent
      ) // eslint-disable-line indent
      : DEFAULT_URI_SAFE_ATTRIBUTES;
      DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS),
      // eslint-disable-line indent
      cfg.ADD_DATA_URI_TAGS,
      // eslint-disable-line indent
      transformCaseFunc // eslint-disable-line indent
      ) // eslint-disable-line indent
      : DEFAULT_DATA_URI_TAGS;
      FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
      FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
      FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
      USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
      ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true

      ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true

      ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false

      ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true

      SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false

      WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false

      RETURN_DOM = cfg.RETURN_DOM || false; // Default false

      RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false

      RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false

      FORCE_BODY = cfg.FORCE_BODY || false; // Default false

      SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true

      SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false

      KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true

      IN_PLACE = cfg.IN_PLACE || false; // Default false

      IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
      NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
      CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
      }
      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
      }
      if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
        CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
      }
      if (SAFE_FOR_TEMPLATES) {
        ALLOW_DATA_ATTR = false;
      }
      if (RETURN_DOM_FRAGMENT) {
        RETURN_DOM = true;
      }
      /* Parse profile info */

      if (USE_PROFILES) {
        ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
        ALLOWED_ATTR = [];
        if (USE_PROFILES.html === true) {
          addToSet(ALLOWED_TAGS, html$1);
          addToSet(ALLOWED_ATTR, html);
        }
        if (USE_PROFILES.svg === true) {
          addToSet(ALLOWED_TAGS, svg$1);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }
        if (USE_PROFILES.svgFilters === true) {
          addToSet(ALLOWED_TAGS, svgFilters);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }
        if (USE_PROFILES.mathMl === true) {
          addToSet(ALLOWED_TAGS, mathMl$1);
          addToSet(ALLOWED_ATTR, mathMl);
          addToSet(ALLOWED_ATTR, xml);
        }
      }
      /* Merge configuration parameters */

      if (cfg.ADD_TAGS) {
        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
          ALLOWED_TAGS = clone(ALLOWED_TAGS);
        }
        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
      }
      if (cfg.ADD_ATTR) {
        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
          ALLOWED_ATTR = clone(ALLOWED_ATTR);
        }
        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
      }
      if (cfg.ADD_URI_SAFE_ATTR) {
        addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
      }
      if (cfg.FORBID_CONTENTS) {
        if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
          FORBID_CONTENTS = clone(FORBID_CONTENTS);
        }
        addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
      }
      /* Add #text in case KEEP_CONTENT is set to true */

      if (KEEP_CONTENT) {
        ALLOWED_TAGS['#text'] = true;
      }
      /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */

      if (WHOLE_DOCUMENT) {
        addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
      }
      /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */

      if (ALLOWED_TAGS.table) {
        addToSet(ALLOWED_TAGS, ['tbody']);
        delete FORBID_TAGS.tbody;
      } // Prevent further manipulation of configuration.
      // Not available in IE8, Safari 5, etc.

      if (freeze) {
        freeze(cfg);
      }
      CONFIG = cfg;
    };
    var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
    var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
    // namespace. We need to specify them explicitly
    // so that they don't get erroneously deleted from
    // HTML namespace.

    var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
    /* Keep track of all possible SVG and MathML tags
     * so that we can perform the namespace checks
     * correctly. */

    var ALL_SVG_TAGS = addToSet({}, svg$1);
    addToSet(ALL_SVG_TAGS, svgFilters);
    addToSet(ALL_SVG_TAGS, svgDisallowed);
    var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
    addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
    /**
     *
     *
     * @param  {Element} element a DOM element whose namespace is being checked
     * @returns {boolean} Return false if the element has a
     *  namespace that a spec-compliant parser would never
     *  return. Return true otherwise.
     */

    var _checkValidNamespace = function _checkValidNamespace(element) {
      var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
      // can be null. We just simulate parent in this case.

      if (!parent || !parent.tagName) {
        parent = {
          namespaceURI: NAMESPACE,
          tagName: 'template'
        };
      }
      var tagName = stringToLowerCase(element.tagName);
      var parentTagName = stringToLowerCase(parent.tagName);
      if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
        return false;
      }
      if (element.namespaceURI === SVG_NAMESPACE) {
        // The only way to switch from HTML namespace to SVG
        // is via <svg>. If it happens via any other tag, then
        // it should be killed.
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === 'svg';
        } // The only way to switch from MathML to SVG is via`
        // svg if parent is either <annotation-xml> or MathML
        // text integration points.

        if (parent.namespaceURI === MATHML_NAMESPACE) {
          return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
        } // We only allow elements that are defined in SVG
        // spec. All others are disallowed in SVG namespace.

        return Boolean(ALL_SVG_TAGS[tagName]);
      }
      if (element.namespaceURI === MATHML_NAMESPACE) {
        // The only way to switch from HTML namespace to MathML
        // is via <math>. If it happens via any other tag, then
        // it should be killed.
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === 'math';
        } // The only way to switch from SVG to MathML is via
        // <math> and HTML integration points

        if (parent.namespaceURI === SVG_NAMESPACE) {
          return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
        } // We only allow elements that are defined in MathML
        // spec. All others are disallowed in MathML namespace.

        return Boolean(ALL_MATHML_TAGS[tagName]);
      }
      if (element.namespaceURI === HTML_NAMESPACE) {
        // The only way to switch from SVG to HTML is via
        // HTML integration points, and from MathML to HTML
        // is via MathML text integration points
        if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
          return false;
        }
        if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
          return false;
        } // We disallow tags that are specific for MathML
        // or SVG and should never appear in HTML namespace

        return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
      } // For XHTML and XML documents that support custom namespaces

      if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
        return true;
      } // The code should never reach this place (this means
      // that the element somehow got namespace that is not
      // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
      // Return false just in case.

      return false;
    };
    /**
     * _forceRemove
     *
     * @param  {Node} node a DOM node
     */

    var _forceRemove = function _forceRemove(node) {
      arrayPush(DOMPurify.removed, {
        element: node
      });
      try {
        // eslint-disable-next-line unicorn/prefer-dom-node-remove
        node.parentNode.removeChild(node);
      } catch (_) {
        try {
          node.outerHTML = emptyHTML;
        } catch (_) {
          node.remove();
        }
      }
    };
    /**
     * _removeAttribute
     *
     * @param  {String} name an Attribute name
     * @param  {Node} node a DOM node
     */

    var _removeAttribute = function _removeAttribute(name, node) {
      try {
        arrayPush(DOMPurify.removed, {
          attribute: node.getAttributeNode(name),
          from: node
        });
      } catch (_) {
        arrayPush(DOMPurify.removed, {
          attribute: null,
          from: node
        });
      }
      node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes

      if (name === 'is' && !ALLOWED_ATTR[name]) {
        if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
          try {
            _forceRemove(node);
          } catch (_) {}
        } else {
          try {
            node.setAttribute(name, '');
          } catch (_) {}
        }
      }
    };
    /**
     * _initDocument
     *
     * @param  {String} dirty a string of dirty markup
     * @return {Document} a DOM, filled with the dirty markup
     */

    var _initDocument = function _initDocument(dirty) {
      /* Create a HTML document */
      var doc;
      var leadingWhitespace;
      if (FORCE_BODY) {
        dirty = '<remove></remove>' + dirty;
      } else {
        /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
        var matches = stringMatch(dirty, /^[\r\n\t ]+/);
        leadingWhitespace = matches && matches[0];
      }
      if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
        // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
        dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
      }
      var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
      /*
       * Use the DOMParser API by default, fallback later if needs be
       * DOMParser not work for svg when has multiple root element.
       */

      if (NAMESPACE === HTML_NAMESPACE) {
        try {
          doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
        } catch (_) {}
      }
      /* Use createHTMLDocument in case DOMParser is not available */

      if (!doc || !doc.documentElement) {
        doc = implementation.createDocument(NAMESPACE, 'template', null);
        try {
          doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
        } catch (_) {// Syntax error if dirtyPayload is invalid xml
        }
      }
      var body = doc.body || doc.documentElement;
      if (dirty && leadingWhitespace) {
        body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
      }
      /* Work on whole document or just its body */

      if (NAMESPACE === HTML_NAMESPACE) {
        return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
      }
      return WHOLE_DOCUMENT ? doc.documentElement : body;
    };
    /**
     * _createIterator
     *
     * @param  {Document} root document/fragment to create iterator for
     * @return {Iterator} iterator instance
     */

    var _createIterator = function _createIterator(root) {
      return createNodeIterator.call(root.ownerDocument || root, root,
      // eslint-disable-next-line no-bitwise
      NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
    };
    /**
     * _isClobbered
     *
     * @param  {Node} elm element to check for clobbering attacks
     * @return {Boolean} true if clobbered, false if safe
     */

    var _isClobbered = function _isClobbered(elm) {
      return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
    };
    /**
     * _isNode
     *
     * @param  {Node} obj object to check whether it's a DOM node
     * @return {Boolean} true is object is a DOM node
     */

    var _isNode = function _isNode(object) {
      return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
    };
    /**
     * _executeHook
     * Execute user configurable hooks
     *
     * @param  {String} entryPoint  Name of the hook's entry point
     * @param  {Node} currentNode node to work on with the hook
     * @param  {Object} data additional hook parameters
     */

    var _executeHook = function _executeHook(entryPoint, currentNode, data) {
      if (!hooks[entryPoint]) {
        return;
      }
      arrayForEach(hooks[entryPoint], function (hook) {
        hook.call(DOMPurify, currentNode, data, CONFIG);
      });
    };
    /**
     * _sanitizeElements
     *
     * @protect nodeName
     * @protect textContent
     * @protect removeChild
     *
     * @param   {Node} currentNode to check for permission to exist
     * @return  {Boolean} true if node was killed, false if left alive
     */

    var _sanitizeElements = function _sanitizeElements(currentNode) {
      var content;
      /* Execute a hook if present */

      _executeHook('beforeSanitizeElements', currentNode, null);
      /* Check if element is clobbered or can clobber */

      if (_isClobbered(currentNode)) {
        _forceRemove(currentNode);
        return true;
      }
      /* Check if tagname contains Unicode */

      if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
        _forceRemove(currentNode);
        return true;
      }
      /* Now let's check the element's type and name */

      var tagName = transformCaseFunc(currentNode.nodeName);
      /* Execute a hook if present */

      _executeHook('uponSanitizeElement', currentNode, {
        tagName: tagName,
        allowedTags: ALLOWED_TAGS
      });
      /* Detect mXSS attempts abusing namespace confusion */

      if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
        _forceRemove(currentNode);
        return true;
      }
      /* Mitigate a problem with templates inside select */

      if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);
        return true;
      }
      /* Remove element if anything forbids its presence */

      if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
        /* Check if we have a custom element to handle */
        if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
        }
        /* Keep content except for bad-listed elements */

        if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
          var parentNode = getParentNode(currentNode) || currentNode.parentNode;
          var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
          if (childNodes && parentNode) {
            var childCount = childNodes.length;
            for (var i = childCount - 1; i >= 0; --i) {
              parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
            }
          }
        }
        _forceRemove(currentNode);
        return true;
      }
      /* Check whether element has a valid namespace */

      if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
        _forceRemove(currentNode);
        return true;
      }
      if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);
        return true;
      }
      /* Sanitize element content to be template-safe */

      if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
        /* Get the element's text content */
        content = currentNode.textContent;
        content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
        content = stringReplace(content, ERB_EXPR$1, ' ');
        content = stringReplace(content, TMPLIT_EXPR$1, ' ');
        if (currentNode.textContent !== content) {
          arrayPush(DOMPurify.removed, {
            element: currentNode.cloneNode()
          });
          currentNode.textContent = content;
        }
      }
      /* Execute a hook if present */

      _executeHook('afterSanitizeElements', currentNode, null);
      return false;
    };
    /**
     * _isValidAttribute
     *
     * @param  {string} lcTag Lowercase tag name of containing element.
     * @param  {string} lcName Lowercase attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid, otherwise false.
     */
    // eslint-disable-next-line complexity

    var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
      /* Make sure attribute cannot clobber */
      if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
        return false;
      }
      /* Allow valid data-* attributes: At least one character after "-"
          (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
          XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
          We don't need to check the value; it's always URI safe. */

      if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ;else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ;else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
        if (
        // First condition does a very basic check if a) it's basically a valid custom element tagname AND
        // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
        _basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) ||
        // Alternative, second condition checks if it's an `is`-attribute, AND
        // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ;else {
          return false;
        }
        /* Check value is safe. First, is attr inert? If so, is safe */
      } else if (URI_SAFE_ATTRIBUTES[lcName]) ;else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ;else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ;else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ;else if (!value) ;else {
        return false;
      }
      return true;
    };
    /**
     * _basicCustomElementCheck
     * checks if at least one dash is included in tagName, and it's not the first char
     * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
     * @param {string} tagName name of the tag of the node to sanitize
     */

    var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
      return tagName.indexOf('-') > 0;
    };
    /**
     * _sanitizeAttributes
     *
     * @protect attributes
     * @protect nodeName
     * @protect removeAttribute
     * @protect setAttribute
     *
     * @param  {Node} currentNode to sanitize
     */

    var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
      var attr;
      var value;
      var lcName;
      var l;
      /* Execute a hook if present */

      _executeHook('beforeSanitizeAttributes', currentNode, null);
      var attributes = currentNode.attributes;
      /* Check if we have attributes; if not we might have a text node */

      if (!attributes) {
        return;
      }
      var hookEvent = {
        attrName: '',
        attrValue: '',
        keepAttr: true,
        allowedAttributes: ALLOWED_ATTR
      };
      l = attributes.length;
      /* Go backwards over all attributes; safely remove bad ones */

      while (l--) {
        attr = attributes[l];
        var _attr = attr,
          name = _attr.name,
          namespaceURI = _attr.namespaceURI;
        value = name === 'value' ? attr.value : stringTrim(attr.value);
        lcName = transformCaseFunc(name);
        /* Execute a hook if present */

        hookEvent.attrName = lcName;
        hookEvent.attrValue = value;
        hookEvent.keepAttr = true;
        hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set

        _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
        value = hookEvent.attrValue;
        /* Did the hooks approve of the attribute? */

        if (hookEvent.forceKeepAttr) {
          continue;
        }
        /* Remove attribute */

        _removeAttribute(name, currentNode);
        /* Did the hooks approve of the attribute? */

        if (!hookEvent.keepAttr) {
          continue;
        }
        /* Work around a security issue in jQuery 3.0 */

        if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
          _removeAttribute(name, currentNode);
          continue;
        }
        /* Sanitize attribute content to be template-safe */

        if (SAFE_FOR_TEMPLATES) {
          value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
          value = stringReplace(value, ERB_EXPR$1, ' ');
          value = stringReplace(value, TMPLIT_EXPR$1, ' ');
        }
        /* Is `value` valid for this attribute? */

        var lcTag = transformCaseFunc(currentNode.nodeName);
        if (!_isValidAttribute(lcTag, lcName, value)) {
          continue;
        }
        /* Full DOM Clobbering protection via namespace isolation,
         * Prefix id and name attributes with `user-content-`
         */

        if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
          // Remove the attribute with this value
          _removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value

          value = SANITIZE_NAMED_PROPS_PREFIX + value;
        }
        /* Handle attributes that require Trusted Types */

        if (trustedTypesPolicy && _typeof(trustedTypes) === 'object' && typeof trustedTypes.getAttributeType === 'function') {
          if (namespaceURI) ;else {
            switch (trustedTypes.getAttributeType(lcTag, lcName)) {
              case 'TrustedHTML':
                value = trustedTypesPolicy.createHTML(value);
                break;
              case 'TrustedScriptURL':
                value = trustedTypesPolicy.createScriptURL(value);
                break;
            }
          }
        }
        /* Handle invalid data-* attribute set by try-catching it */

        try {
          if (namespaceURI) {
            currentNode.setAttributeNS(namespaceURI, name, value);
          } else {
            /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
            currentNode.setAttribute(name, value);
          }
          arrayPop(DOMPurify.removed);
        } catch (_) {}
      }
      /* Execute a hook if present */

      _executeHook('afterSanitizeAttributes', currentNode, null);
    };
    /**
     * _sanitizeShadowDOM
     *
     * @param  {DocumentFragment} fragment to iterate over recursively
     */

    var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
      var shadowNode;
      var shadowIterator = _createIterator(fragment);
      /* Execute a hook if present */

      _executeHook('beforeSanitizeShadowDOM', fragment, null);
      while (shadowNode = shadowIterator.nextNode()) {
        /* Execute a hook if present */
        _executeHook('uponSanitizeShadowNode', shadowNode, null);
        /* Sanitize tags and elements */

        if (_sanitizeElements(shadowNode)) {
          continue;
        }
        /* Deep shadow DOM detected */

        if (shadowNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(shadowNode.content);
        }
        /* Check attributes, sanitize if necessary */

        _sanitizeAttributes(shadowNode);
      }
      /* Execute a hook if present */

      _executeHook('afterSanitizeShadowDOM', fragment, null);
    };
    /**
     * Sanitize
     * Public method providing core sanitation functionality
     *
     * @param {String|Node} dirty string or DOM node
     * @param {Object} configuration object
     */
    // eslint-disable-next-line complexity

    DOMPurify.sanitize = function (dirty) {
      var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var body;
      var importedNode;
      var currentNode;
      var oldNode;
      var returnNode;
      /* Make sure we have a string to sanitize.
        DO NOT return early, as this will return the wrong type if
        the user has requested a DOM object rather than a string */

      IS_EMPTY_INPUT = !dirty;
      if (IS_EMPTY_INPUT) {
        dirty = '<!-->';
      }
      /* Stringify, in case dirty is an object */

      if (typeof dirty !== 'string' && !_isNode(dirty)) {
        // eslint-disable-next-line no-negated-condition
        if (typeof dirty.toString !== 'function') {
          throw typeErrorCreate('toString is not a function');
        } else {
          dirty = dirty.toString();
          if (typeof dirty !== 'string') {
            throw typeErrorCreate('dirty is not a string, aborting');
          }
        }
      }
      /* Check we can run. Otherwise fall back or ignore */

      if (!DOMPurify.isSupported) {
        if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
          if (typeof dirty === 'string') {
            return window.toStaticHTML(dirty);
          }
          if (_isNode(dirty)) {
            return window.toStaticHTML(dirty.outerHTML);
          }
        }
        return dirty;
      }
      /* Assign config vars */

      if (!SET_CONFIG) {
        _parseConfig(cfg);
      }
      /* Clean up removed elements */

      DOMPurify.removed = [];
      /* Check if dirty is correctly typed for IN_PLACE */

      if (typeof dirty === 'string') {
        IN_PLACE = false;
      }
      if (IN_PLACE) {
        /* Do some early pre-sanitization to avoid unsafe root nodes */
        if (dirty.nodeName) {
          var tagName = transformCaseFunc(dirty.nodeName);
          if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
            throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
          }
        }
      } else if (dirty instanceof Node) {
        /* If dirty is a DOM element, append to an empty document to avoid
           elements being stripped by the parser */
        body = _initDocument('<!---->');
        importedNode = body.ownerDocument.importNode(dirty, true);
        if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
          /* Node is already a body, use as is */
          body = importedNode;
        } else if (importedNode.nodeName === 'HTML') {
          body = importedNode;
        } else {
          // eslint-disable-next-line unicorn/prefer-dom-node-append
          body.appendChild(importedNode);
        }
      } else {
        /* Exit directly if we have nothing to do */
        if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
        // eslint-disable-next-line unicorn/prefer-includes
        dirty.indexOf('<') === -1) {
          return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
        }
        /* Initialize the document to work on */

        body = _initDocument(dirty);
        /* Check we have a DOM node from the data */

        if (!body) {
          return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
        }
      }
      /* Remove first element node (ours) if FORCE_BODY is set */

      if (body && FORCE_BODY) {
        _forceRemove(body.firstChild);
      }
      /* Get node iterator */

      var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
      /* Now start iterating over the created document */

      while (currentNode = nodeIterator.nextNode()) {
        /* Fix IE's strange behavior with manipulated textNodes #89 */
        if (currentNode.nodeType === 3 && currentNode === oldNode) {
          continue;
        }
        /* Sanitize tags and elements */

        if (_sanitizeElements(currentNode)) {
          continue;
        }
        /* Shadow DOM detected, sanitize it */

        if (currentNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(currentNode.content);
        }
        /* Check attributes, sanitize if necessary */

        _sanitizeAttributes(currentNode);
        oldNode = currentNode;
      }
      oldNode = null;
      /* If we sanitized `dirty` in-place, return it. */

      if (IN_PLACE) {
        return dirty;
      }
      /* Return sanitized string or DOM */

      if (RETURN_DOM) {
        if (RETURN_DOM_FRAGMENT) {
          returnNode = createDocumentFragment.call(body.ownerDocument);
          while (body.firstChild) {
            // eslint-disable-next-line unicorn/prefer-dom-node-append
            returnNode.appendChild(body.firstChild);
          }
        } else {
          returnNode = body;
        }
        if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmod) {
          /*
            AdoptNode() is not used because internal state is not reset
            (e.g. the past names map of a HTMLFormElement), this is safe
            in theory but we would rather not risk another attack vector.
            The state that is cloned by importNode() is explicitly defined
            by the specs.
          */
          returnNode = importNode.call(originalDocument, returnNode, true);
        }
        return returnNode;
      }
      var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
      /* Serialize doctype if allowed */

      if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
        serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
      }
      /* Sanitize final string template-safe */

      if (SAFE_FOR_TEMPLATES) {
        serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
        serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
        serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR$1, ' ');
      }
      return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
    };
    /**
     * Public method to set the configuration once
     * setConfig
     *
     * @param {Object} cfg configuration object
     */

    DOMPurify.setConfig = function (cfg) {
      _parseConfig(cfg);
      SET_CONFIG = true;
    };
    /**
     * Public method to remove the configuration
     * clearConfig
     *
     */

    DOMPurify.clearConfig = function () {
      CONFIG = null;
      SET_CONFIG = false;
    };
    /**
     * Public method to check if an attribute value is valid.
     * Uses last set config, if any. Otherwise, uses config defaults.
     * isValidAttribute
     *
     * @param  {string} tag Tag name of containing element.
     * @param  {string} attr Attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
     */

    DOMPurify.isValidAttribute = function (tag, attr, value) {
      /* Initialize shared config vars if necessary. */
      if (!CONFIG) {
        _parseConfig({});
      }
      var lcTag = transformCaseFunc(tag);
      var lcName = transformCaseFunc(attr);
      return _isValidAttribute(lcTag, lcName, value);
    };
    /**
     * AddHook
     * Public method to add DOMPurify hooks
     *
     * @param {String} entryPoint entry point for the hook to add
     * @param {Function} hookFunction function to execute
     */

    DOMPurify.addHook = function (entryPoint, hookFunction) {
      if (typeof hookFunction !== 'function') {
        return;
      }
      hooks[entryPoint] = hooks[entryPoint] || [];
      arrayPush(hooks[entryPoint], hookFunction);
    };
    /**
     * RemoveHook
     * Public method to remove a DOMPurify hook at a given entryPoint
     * (pops it from the stack of hooks if more are present)
     *
     * @param {String} entryPoint entry point for the hook to remove
     * @return {Function} removed(popped) hook
     */

    DOMPurify.removeHook = function (entryPoint) {
      if (hooks[entryPoint]) {
        return arrayPop(hooks[entryPoint]);
      }
    };
    /**
     * RemoveHooks
     * Public method to remove all DOMPurify hooks at a given entryPoint
     *
     * @param  {String} entryPoint entry point for the hooks to remove
     */

    DOMPurify.removeHooks = function (entryPoint) {
      if (hooks[entryPoint]) {
        hooks[entryPoint] = [];
      }
    };
    /**
     * RemoveAllHooks
     * Public method to remove all DOMPurify hooks
     *
     */

    DOMPurify.removeAllHooks = function () {
      hooks = {};
    };
    return DOMPurify;
  }
  var purify = createDOMPurify();
  return purify;
});

/***/ }),

/***/ 3429:
/***/ ((module, exports) => {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
 * @license MIT or GPL-2.0
 * @fileOverview Favico animations
 * @author Miroslav Magda, http://blog.ejci.net
 * @source: https://github.com/ejci/favico.js
 * @version 0.3.10
 */

/**
 * Create new favico instance
 * @param {Object} Options
 * @return {Object} Favico object
 * @example
 * var favico = new Favico({
 *    bgColor : '#d00',
 *    textColor : '#fff',
 *    fontFamily : 'sans-serif',
 *    fontStyle : 'bold',
 *    type : 'circle',
 *    position : 'down',
 *    animation : 'slide',
 *    elementId: false,
 *    element: null,
 *    dataUrl: function(url){},
 *    win: window
 * });
 */
(function () {
  var Favico = function Favico(opt) {
    'use strict';

    opt = opt ? opt : {};
    var _def = {
      bgColor: '#d00',
      textColor: '#fff',
      fontFamily: 'sans-serif',
      //Arial,Verdana,Times New Roman,serif,sans-serif,...
      fontStyle: 'bold',
      //normal,italic,oblique,bold,bolder,lighter,100,200,300,400,500,600,700,800,900
      type: 'circle',
      position: 'down',
      // down, up, left, leftup (upleft)
      animation: 'slide',
      elementId: false,
      element: null,
      dataUrl: false,
      win: window
    };
    var _opt, _orig, _h, _w, _canvas, _context, _img, _ready, _lastBadge, _running, _readyCb, _stop, _browser, _animTimeout, _drawTimeout, _doc;
    _browser = {};
    _browser.ff = typeof InstallTrigger != 'undefined';
    _browser.chrome = !!window.chrome;
    _browser.opera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
    _browser.ie = /*@cc_on!@*/false;
    _browser.safari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    _browser.supported = _browser.chrome || _browser.ff || _browser.opera;
    var _queue = [];
    _readyCb = function _readyCb() {};
    _ready = _stop = false;
    /**
     * Initialize favico
     */
    var init = function init() {
      //merge initial options
      _opt = merge(_def, opt);
      _opt.bgColor = hexToRgb(_opt.bgColor);
      _opt.textColor = hexToRgb(_opt.textColor);
      _opt.position = _opt.position.toLowerCase();
      _opt.animation = animation.types['' + _opt.animation] ? _opt.animation : _def.animation;
      _doc = _opt.win.document;
      var isUp = _opt.position.indexOf('up') > -1;
      var isLeft = _opt.position.indexOf('left') > -1;

      //transform the animations
      if (isUp || isLeft) {
        for (var a in animation.types) {
          for (var i = 0; i < animation.types[a].length; i++) {
            var step = animation.types[a][i];
            if (isUp) {
              if (step.y < 0.6) {
                step.y = step.y - 0.4;
              } else {
                step.y = step.y - 2 * step.y + (1 - step.w);
              }
            }
            if (isLeft) {
              if (step.x < 0.6) {
                step.x = step.x - 0.4;
              } else {
                step.x = step.x - 2 * step.x + (1 - step.h);
              }
            }
            animation.types[a][i] = step;
          }
        }
      }
      _opt.type = type['' + _opt.type] ? _opt.type : _def.type;
      _orig = link.getIcons();
      //create temp canvas
      _canvas = document.createElement('canvas');
      //create temp image
      _img = document.createElement('img');
      var lastIcon = _orig[_orig.length - 1];
      if (lastIcon.hasAttribute('href')) {
        _img.setAttribute('crossOrigin', 'anonymous');
        //get width/height
        _img.onload = function () {
          _h = _img.height > 0 ? _img.height : 32;
          _w = _img.width > 0 ? _img.width : 32;
          _canvas.height = _h;
          _canvas.width = _w;
          _context = _canvas.getContext('2d');
          icon.ready();
        };
        _img.setAttribute('src', lastIcon.getAttribute('href'));
      } else {
        _h = 32;
        _w = 32;
        _img.height = _h;
        _img.width = _w;
        _canvas.height = _h;
        _canvas.width = _w;
        _context = _canvas.getContext('2d');
        icon.ready();
      }
    };
    /**
     * Icon namespace
     */
    var icon = {};
    /**
     * Icon is ready (reset icon) and start animation (if ther is any)
     */
    icon.ready = function () {
      _ready = true;
      icon.reset();
      _readyCb();
    };
    /**
     * Reset icon to default state
     */
    icon.reset = function () {
      //reset
      if (!_ready) {
        return;
      }
      _queue = [];
      _lastBadge = false;
      _running = false;
      _context.clearRect(0, 0, _w, _h);
      _context.drawImage(_img, 0, 0, _w, _h);
      //_stop=true;
      link.setIcon(_canvas);
      //webcam('stop');
      //video('stop');
      window.clearTimeout(_animTimeout);
      window.clearTimeout(_drawTimeout);
    };
    /**
     * Start animation
     */
    icon.start = function () {
      if (!_ready || _running) {
        return;
      }
      var finished = function finished() {
        _lastBadge = _queue[0];
        _running = false;
        if (_queue.length > 0) {
          _queue.shift();
          icon.start();
        } else {}
      };
      if (_queue.length > 0) {
        _running = true;
        var run = function run() {
          // apply options for this animation
          ['type', 'animation', 'bgColor', 'textColor', 'fontFamily', 'fontStyle'].forEach(function (a) {
            if (a in _queue[0].options) {
              _opt[a] = _queue[0].options[a];
            }
          });
          animation.run(_queue[0].options, function () {
            finished();
          }, false);
        };
        if (_lastBadge) {
          animation.run(_lastBadge.options, function () {
            run();
          }, true);
        } else {
          run();
        }
      }
    };

    /**
     * Badge types
     */
    var type = {};
    var options = function options(opt) {
      opt.n = typeof opt.n === 'number' ? Math.abs(opt.n | 0) : opt.n;
      opt.x = _w * opt.x;
      opt.y = _h * opt.y;
      opt.w = _w * opt.w;
      opt.h = _h * opt.h;
      opt.len = ("" + opt.n).length;
      return opt;
    };
    /**
     * Generate circle
     * @param {Object} opt Badge options
     */
    type.circle = function (opt) {
      opt = options(opt);
      var more = false;
      if (opt.len === 2) {
        opt.x = opt.x - opt.w * 0.4;
        opt.w = opt.w * 1.4;
        more = true;
      } else if (opt.len >= 3) {
        opt.x = opt.x - opt.w * 0.65;
        opt.w = opt.w * 1.65;
        more = true;
      }
      _context.clearRect(0, 0, _w, _h);
      _context.drawImage(_img, 0, 0, _w, _h);
      _context.beginPath();
      _context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.85 : 1)) + "px " + _opt.fontFamily;
      _context.textAlign = 'center';
      if (more) {
        _context.moveTo(opt.x + opt.w / 2, opt.y);
        _context.lineTo(opt.x + opt.w - opt.h / 2, opt.y);
        _context.quadraticCurveTo(opt.x + opt.w, opt.y, opt.x + opt.w, opt.y + opt.h / 2);
        _context.lineTo(opt.x + opt.w, opt.y + opt.h - opt.h / 2);
        _context.quadraticCurveTo(opt.x + opt.w, opt.y + opt.h, opt.x + opt.w - opt.h / 2, opt.y + opt.h);
        _context.lineTo(opt.x + opt.h / 2, opt.y + opt.h);
        _context.quadraticCurveTo(opt.x, opt.y + opt.h, opt.x, opt.y + opt.h - opt.h / 2);
        _context.lineTo(opt.x, opt.y + opt.h / 2);
        _context.quadraticCurveTo(opt.x, opt.y, opt.x + opt.h / 2, opt.y);
      } else {
        _context.arc(opt.x + opt.w / 2, opt.y + opt.h / 2, opt.h / 2, 0, 2 * Math.PI);
      }
      _context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';
      _context.fill();
      _context.closePath();
      _context.beginPath();
      _context.stroke();
      _context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';
      //_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      if (typeof opt.n === 'number' && opt.n > 999) {
        _context.fillText((opt.n > 9999 ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
      } else {
        _context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      }
      _context.closePath();
    };
    /**
     * Generate rectangle
     * @param {Object} opt Badge options
     */
    type.rectangle = function (opt) {
      opt = options(opt);
      var more = false;
      if (opt.len === 2) {
        opt.x = opt.x - opt.w * 0.4;
        opt.w = opt.w * 1.4;
        more = true;
      } else if (opt.len >= 3) {
        opt.x = opt.x - opt.w * 0.65;
        opt.w = opt.w * 1.65;
        more = true;
      }
      _context.clearRect(0, 0, _w, _h);
      _context.drawImage(_img, 0, 0, _w, _h);
      _context.beginPath();
      _context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.9 : 1)) + "px " + _opt.fontFamily;
      _context.textAlign = 'center';
      _context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';
      _context.fillRect(opt.x, opt.y, opt.w, opt.h);
      _context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';
      //_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      if (typeof opt.n === 'number' && opt.n > 999) {
        _context.fillText((opt.n > 9999 ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
      } else {
        _context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      }
      _context.closePath();
    };

    /**
     * Set badge
     */
    var badge = function badge(number, opts) {
      opts = (typeof opts === 'string' ? {
        animation: opts
      } : opts) || {};
      _readyCb = function _readyCb() {
        try {
          if (typeof number === 'number' ? number > 0 : number !== '') {
            var q = {
              type: 'badge',
              options: {
                n: number
              }
            };
            if ('animation' in opts && animation.types['' + opts.animation]) {
              q.options.animation = '' + opts.animation;
            }
            if ('type' in opts && type['' + opts.type]) {
              q.options.type = '' + opts.type;
            }
            ['bgColor', 'textColor'].forEach(function (o) {
              if (o in opts) {
                q.options[o] = hexToRgb(opts[o]);
              }
            });
            ['fontStyle', 'fontFamily'].forEach(function (o) {
              if (o in opts) {
                q.options[o] = opts[o];
              }
            });
            _queue.push(q);
            if (_queue.length > 100) {
              throw new Error('Too many badges requests in queue.');
            }
            icon.start();
          } else {
            icon.reset();
          }
        } catch (e) {
          throw new Error('Error setting badge. Message: ' + e.message);
        }
      };
      if (_ready) {
        _readyCb();
      }
    };
    var setOpt = function setOpt(key, value) {
      var opts = key;
      if (!(value == null && Object.prototype.toString.call(key) == '[object Object]')) {
        opts = {};
        opts[key] = value;
      }
      var keys = Object.keys(opts);
      for (var i = 0; i < keys.length; i++) {
        if (keys[i] == 'bgColor' || keys[i] == 'textColor') {
          _opt[keys[i]] = hexToRgb(opts[keys[i]]);
        } else {
          _opt[keys[i]] = opts[keys[i]];
        }
      }
      _queue.push(_lastBadge);
      icon.start();
    };
    var link = {};
    /**
     * Get icons from HEAD tag or create a new <link> element
     */
    link.getIcons = function () {
      var elms = [];
      //get link element
      var getLinks = function getLinks() {
        var icons = [];
        var links = _doc.getElementsByTagName('head')[0].getElementsByTagName('link');
        for (var i = 0; i < links.length; i++) {
          if (/(^|\s)icon(\s|$)/i.test(links[i].getAttribute('rel'))) {
            icons.push(links[i]);
          }
        }
        return icons;
      };
      if (_opt.element) {
        elms = [_opt.element];
      } else if (_opt.elementId) {
        //if img element identified by elementId
        elms = [_doc.getElementById(_opt.elementId)];
        elms[0].setAttribute('href', elms[0].getAttribute('src'));
      } else {
        //if link element
        elms = getLinks();
        if (elms.length === 0) {
          elms = [_doc.createElement('link')];
          elms[0].setAttribute('rel', 'icon');
          _doc.getElementsByTagName('head')[0].appendChild(elms[0]);
        }
      }
      elms.forEach(function (item) {
        item.setAttribute('type', 'image/png');
      });
      return elms;
    };
    link.setIcon = function (canvas) {
      var url = canvas.toDataURL('image/png');
      link.setIconSrc(url);
    };
    link.setIconSrc = function (url) {
      if (_opt.dataUrl) {
        //if using custom exporter
        _opt.dataUrl(url);
      }
      if (_opt.element) {
        _opt.element.setAttribute('href', url);
        _opt.element.setAttribute('src', url);
      } else if (_opt.elementId) {
        //if is attached to element (image)
        var elm = _doc.getElementById(_opt.elementId);
        elm.setAttribute('href', url);
        elm.setAttribute('src', url);
      } else {
        //if is attached to fav icon
        if (_browser.ff || _browser.opera) {
          //for FF we need to "recreate" element, atach to dom and remove old <link>
          //var originalType = _orig.getAttribute('rel');
          var old = _orig[_orig.length - 1];
          var newIcon = _doc.createElement('link');
          _orig = [newIcon];
          //_orig.setAttribute('rel', originalType);
          if (_browser.opera) {
            newIcon.setAttribute('rel', 'icon');
          }
          newIcon.setAttribute('rel', 'icon');
          newIcon.setAttribute('type', 'image/png');
          _doc.getElementsByTagName('head')[0].appendChild(newIcon);
          newIcon.setAttribute('href', url);
          if (old.parentNode) {
            old.parentNode.removeChild(old);
          }
        } else {
          _orig.forEach(function (icon) {
            icon.setAttribute('href', url);
          });
        }
      }
    };

    //http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-5624139
    //HEX to RGB convertor
    function hexToRgb(hex) {
      var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
      hex = hex.replace(shorthandRegex, function (m, r, g, b) {
        return r + r + g + g + b + b;
      });
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : false;
    }

    /**
     * Merge options
     */
    function merge(def, opt) {
      var mergedOpt = {};
      var attrname;
      for (attrname in def) {
        mergedOpt[attrname] = def[attrname];
      }
      for (attrname in opt) {
        mergedOpt[attrname] = opt[attrname];
      }
      return mergedOpt;
    }

    /**
     * Cross-browser page visibility shim
     * http://stackoverflow.com/questions/12536562/detect-whether-a-window-is-visible
     */
    function isPageHidden() {
      return _doc.hidden || _doc.msHidden || _doc.webkitHidden || _doc.mozHidden;
    }

    /**
     * @namespace animation
     */
    var animation = {};
    /**
     * Animation "frame" duration
     */
    animation.duration = 40;
    /**
     * Animation types (none,fade,pop,slide)
     */
    animation.types = {};
    animation.types.fade = [{
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.0
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.2
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.3
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.4
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.5
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.6
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.7
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.8
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.9
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1.0
    }];
    animation.types.none = [{
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.pop = [{
      x: 1,
      y: 1,
      w: 0,
      h: 0,
      o: 1
    }, {
      x: 0.9,
      y: 0.9,
      w: 0.1,
      h: 0.1,
      o: 1
    }, {
      x: 0.8,
      y: 0.8,
      w: 0.2,
      h: 0.2,
      o: 1
    }, {
      x: 0.7,
      y: 0.7,
      w: 0.3,
      h: 0.3,
      o: 1
    }, {
      x: 0.6,
      y: 0.6,
      w: 0.4,
      h: 0.4,
      o: 1
    }, {
      x: 0.5,
      y: 0.5,
      w: 0.5,
      h: 0.5,
      o: 1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.popFade = [{
      x: 0.75,
      y: 0.75,
      w: 0,
      h: 0,
      o: 0
    }, {
      x: 0.65,
      y: 0.65,
      w: 0.1,
      h: 0.1,
      o: 0.2
    }, {
      x: 0.6,
      y: 0.6,
      w: 0.2,
      h: 0.2,
      o: 0.4
    }, {
      x: 0.55,
      y: 0.55,
      w: 0.3,
      h: 0.3,
      o: 0.6
    }, {
      x: 0.50,
      y: 0.50,
      w: 0.4,
      h: 0.4,
      o: 0.8
    }, {
      x: 0.45,
      y: 0.45,
      w: 0.5,
      h: 0.5,
      o: 0.9
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.slide = [{
      x: 0.4,
      y: 1,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.9,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.9,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.8,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.7,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.6,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.5,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    /**
     * Run animation
     * @param {Object} opt Animation options
     * @param {Object} cb Callabak after all steps are done
     * @param {Object} revert Reverse order? true|false
     * @param {Object} step Optional step number (frame bumber)
     */
    animation.run = function (opt, cb, revert, step) {
      var animationType = animation.types[isPageHidden() ? 'none' : _opt.animation];
      if (revert === true) {
        step = typeof step !== 'undefined' ? step : animationType.length - 1;
      } else {
        step = typeof step !== 'undefined' ? step : 0;
      }
      cb = cb ? cb : function () {};
      if (step < animationType.length && step >= 0) {
        type[_opt.type](merge(opt, animationType[step]));
        _animTimeout = setTimeout(function () {
          if (revert) {
            step = step - 1;
          } else {
            step = step + 1;
          }
          animation.run(opt, cb, revert, step);
        }, animation.duration);
        link.setIcon(_canvas);
      } else {
        cb();
        return;
      }
    };
    //auto init
    init();
    return {
      badge: badge,
      setOpt: setOpt,
      reset: icon.reset,
      browser: {
        supported: _browser.supported
      }
    };
  };

  // AMD / RequireJS
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
      return Favico;
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  }
  // CommonJS
  else {}
})();

/***/ }),

/***/ 8253:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.deinterlace = void 0;

/**
 * Deinterlace function from https://github.com/shachaf/jsgif
 */
var deinterlace = function deinterlace(pixels, width) {
  var newPixels = new Array(pixels.length);
  var rows = pixels.length / width;
  var cpRow = function cpRow(toRow, fromRow) {
    var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
    newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
  }; // See appendix E.

  var offsets = [0, 4, 2, 1];
  var steps = [8, 8, 4, 2];
  var fromRow = 0;
  for (var pass = 0; pass < 4; pass++) {
    for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
      cpRow(toRow, fromRow);
      fromRow++;
    }
  }
  return newPixels;
};
exports.deinterlace = deinterlace;

/***/ }),

/***/ 3960:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
var __webpack_unused_export__;


__webpack_unused_export__ = ({
  value: true
});
exports.zw = __webpack_unused_export__ = exports.vq = void 0;
var _gif = _interopRequireDefault(__webpack_require__(7119));
var _jsBinarySchemaParser = __webpack_require__(3966);
var _uint = __webpack_require__(459);
var _deinterlace = __webpack_require__(8253);
var _lzw = __webpack_require__(8756);
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
}
var parseGIF = function parseGIF(arrayBuffer) {
  var byteData = new Uint8Array(arrayBuffer);
  return (0, _jsBinarySchemaParser.parse)((0, _uint.buildStream)(byteData), _gif["default"]);
};
exports.vq = parseGIF;
var generatePatch = function generatePatch(image) {
  var totalPixels = image.pixels.length;
  var patchData = new Uint8ClampedArray(totalPixels * 4);
  for (var i = 0; i < totalPixels; i++) {
    var pos = i * 4;
    var colorIndex = image.pixels[i];
    var color = image.colorTable[colorIndex] || [0, 0, 0];
    patchData[pos] = color[0];
    patchData[pos + 1] = color[1];
    patchData[pos + 2] = color[2];
    patchData[pos + 3] = colorIndex !== image.transparentIndex ? 255 : 0;
  }
  return patchData;
};
var decompressFrame = function decompressFrame(frame, gct, buildImagePatch) {
  if (!frame.image) {
    console.warn('gif frame does not have associated image.');
    return;
  }
  var image = frame.image; // get the number of pixels

  var totalPixels = image.descriptor.width * image.descriptor.height; // do lzw decompression

  var pixels = (0, _lzw.lzw)(image.data.minCodeSize, image.data.blocks, totalPixels); // deal with interlacing if necessary

  if (image.descriptor.lct.interlaced) {
    pixels = (0, _deinterlace.deinterlace)(pixels, image.descriptor.width);
  }
  var resultImage = {
    pixels: pixels,
    dims: {
      top: frame.image.descriptor.top,
      left: frame.image.descriptor.left,
      width: frame.image.descriptor.width,
      height: frame.image.descriptor.height
    }
  }; // color table

  if (image.descriptor.lct && image.descriptor.lct.exists) {
    resultImage.colorTable = image.lct;
  } else {
    resultImage.colorTable = gct;
  } // add per frame relevant gce information

  if (frame.gce) {
    resultImage.delay = (frame.gce.delay || 10) * 10; // convert to ms

    resultImage.disposalType = frame.gce.extras.disposal; // transparency

    if (frame.gce.extras.transparentColorGiven) {
      resultImage.transparentIndex = frame.gce.transparentColorIndex;
    }
  } // create canvas usable imagedata if desired

  if (buildImagePatch) {
    resultImage.patch = generatePatch(resultImage);
  }
  return resultImage;
};
__webpack_unused_export__ = decompressFrame;
var decompressFrames = function decompressFrames(parsedGif, buildImagePatches) {
  return parsedGif.frames.filter(function (f) {
    return f.image;
  }).map(function (f) {
    return decompressFrame(f, parsedGif.gct, buildImagePatches);
  });
};
exports.zw = decompressFrames;

/***/ }),

/***/ 8756:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.lzw = void 0;

/**
 * javascript port of java LZW decompression
 * Original java author url: https://gist.github.com/devunwired/4479231
 */
var lzw = function lzw(minCodeSize, data, pixelCount) {
  var MAX_STACK_SIZE = 4096;
  var nullCode = -1;
  var npix = pixelCount;
  var available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, i, datum, data_size, first, top, bi, pi;
  var dstPixels = new Array(pixelCount);
  var prefix = new Array(MAX_STACK_SIZE);
  var suffix = new Array(MAX_STACK_SIZE);
  var pixelStack = new Array(MAX_STACK_SIZE + 1); // Initialize GIF data stream decoder.

  data_size = minCodeSize;
  clear = 1 << data_size;
  end_of_information = clear + 1;
  available = clear + 2;
  old_code = nullCode;
  code_size = data_size + 1;
  code_mask = (1 << code_size) - 1;
  for (code = 0; code < clear; code++) {
    prefix[code] = 0;
    suffix[code] = code;
  } // Decode GIF pixel stream.

  var datum, bits, count, first, top, pi, bi;
  datum = bits = count = first = top = pi = bi = 0;
  for (i = 0; i < npix;) {
    if (top === 0) {
      if (bits < code_size) {
        // get the next byte
        datum += data[bi] << bits;
        bits += 8;
        bi++;
        continue;
      } // Get the next code.

      code = datum & code_mask;
      datum >>= code_size;
      bits -= code_size; // Interpret the code

      if (code > available || code == end_of_information) {
        break;
      }
      if (code == clear) {
        // Reset decoder.
        code_size = data_size + 1;
        code_mask = (1 << code_size) - 1;
        available = clear + 2;
        old_code = nullCode;
        continue;
      }
      if (old_code == nullCode) {
        pixelStack[top++] = suffix[code];
        old_code = code;
        first = code;
        continue;
      }
      in_code = code;
      if (code == available) {
        pixelStack[top++] = first;
        code = old_code;
      }
      while (code > clear) {
        pixelStack[top++] = suffix[code];
        code = prefix[code];
      }
      first = suffix[code] & 0xff;
      pixelStack[top++] = first; // add a new string to the table, but only if space is available
      // if not, just continue with current table until a clear code is found
      // (deferred clear code implementation as per GIF spec)

      if (available < MAX_STACK_SIZE) {
        prefix[available] = old_code;
        suffix[available] = first;
        available++;
        if ((available & code_mask) === 0 && available < MAX_STACK_SIZE) {
          code_size++;
          code_mask += available;
        }
      }
      old_code = in_code;
    } // Pop a pixel off the pixel stack.

    top--;
    dstPixels[pi++] = pixelStack[top];
    i++;
  }
  for (i = pi; i < npix; i++) {
    dstPixels[i] = 0; // clear missing pixels
  }

  return dstPixels;
};
exports.lzw = lzw;

/***/ }),

/***/ 9114:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Mutation = __webpack_require__.g.MutationObserver || __webpack_require__.g.WebKitMutationObserver;
var scheduleDrain;
{
  if (Mutation) {
    var called = 0;
    var observer = new Mutation(nextTick);
    var element = __webpack_require__.g.document.createTextNode('');
    observer.observe(element, {
      characterData: true
    });
    scheduleDrain = function scheduleDrain() {
      element.data = called = ++called % 2;
    };
  } else if (!__webpack_require__.g.setImmediate && typeof __webpack_require__.g.MessageChannel !== 'undefined') {
    var channel = new __webpack_require__.g.MessageChannel();
    channel.port1.onmessage = nextTick;
    scheduleDrain = function scheduleDrain() {
      channel.port2.postMessage(0);
    };
  } else if ('document' in __webpack_require__.g && 'onreadystatechange' in __webpack_require__.g.document.createElement('script')) {
    scheduleDrain = function scheduleDrain() {
      // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
      // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
      var scriptEl = __webpack_require__.g.document.createElement('script');
      scriptEl.onreadystatechange = function () {
        nextTick();
        scriptEl.onreadystatechange = null;
        scriptEl.parentNode.removeChild(scriptEl);
        scriptEl = null;
      };
      __webpack_require__.g.document.documentElement.appendChild(scriptEl);
    };
  } else {
    scheduleDrain = function scheduleDrain() {
      setTimeout(nextTick, 0);
    };
  }
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
  draining = true;
  var i, oldQueue;
  var len = queue.length;
  while (len) {
    oldQueue = queue;
    queue = [];
    i = -1;
    while (++i < len) {
      oldQueue[i]();
    }
    len = queue.length;
  }
  draining = false;
}
module.exports = immediate;
function immediate(task) {
  if (queue.push(task) === 1 && !draining) {
    scheduleDrain();
  }
}

/***/ }),

/***/ 3966:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.loop = exports.conditional = exports.parse = void 0;
var parse = function parse(stream, schema) {
  var result = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : result;
  if (Array.isArray(schema)) {
    schema.forEach(function (partSchema) {
      return parse(stream, partSchema, result, parent);
    });
  } else if (typeof schema === 'function') {
    schema(stream, result, parent, parse);
  } else {
    var key = Object.keys(schema)[0];
    if (Array.isArray(schema[key])) {
      parent[key] = {};
      parse(stream, schema[key], result, parent[key]);
    } else {
      parent[key] = schema[key](stream, result, parent, parse);
    }
  }
  return result;
};
exports.parse = parse;
var conditional = function conditional(schema, conditionFunc) {
  return function (stream, result, parent, parse) {
    if (conditionFunc(stream, result, parent)) {
      parse(stream, schema, result, parent);
    }
  };
};
exports.conditional = conditional;
var loop = function loop(schema, continueFunc) {
  return function (stream, result, parent, parse) {
    var arr = [];
    var lastStreamPos = stream.pos;
    while (continueFunc(stream, result, parent)) {
      var newParent = {};
      parse(stream, schema, result, newParent); // cases when whole file is parsed but no termination is there and stream position is not getting updated as well
      // it falls into infinite recursion, null check to avoid the same

      if (stream.pos === lastStreamPos) {
        break;
      }
      lastStreamPos = stream.pos;
      arr.push(newParent);
    }
    return arr;
  };
};
exports.loop = loop;

/***/ }),

/***/ 459:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.readBits = exports.readArray = exports.readUnsigned = exports.readString = exports.peekBytes = exports.readBytes = exports.peekByte = exports.readByte = exports.buildStream = void 0;

// Default stream and parsers for Uint8TypedArray data type
var buildStream = function buildStream(uint8Data) {
  return {
    data: uint8Data,
    pos: 0
  };
};
exports.buildStream = buildStream;
var readByte = function readByte() {
  return function (stream) {
    return stream.data[stream.pos++];
  };
};
exports.readByte = readByte;
var peekByte = function peekByte() {
  var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  return function (stream) {
    return stream.data[stream.pos + offset];
  };
};
exports.peekByte = peekByte;
var readBytes = function readBytes(length) {
  return function (stream) {
    return stream.data.subarray(stream.pos, stream.pos += length);
  };
};
exports.readBytes = readBytes;
var peekBytes = function peekBytes(length) {
  return function (stream) {
    return stream.data.subarray(stream.pos, stream.pos + length);
  };
};
exports.peekBytes = peekBytes;
var readString = function readString(length) {
  return function (stream) {
    return Array.from(readBytes(length)(stream)).map(function (value) {
      return String.fromCharCode(value);
    }).join('');
  };
};
exports.readString = readString;
var readUnsigned = function readUnsigned(littleEndian) {
  return function (stream) {
    var bytes = readBytes(2)(stream);
    return littleEndian ? (bytes[1] << 8) + bytes[0] : (bytes[0] << 8) + bytes[1];
  };
};
exports.readUnsigned = readUnsigned;
var readArray = function readArray(byteSize, totalOrFunc) {
  return function (stream, result, parent) {
    var total = typeof totalOrFunc === 'function' ? totalOrFunc(stream, result, parent) : totalOrFunc;
    var parser = readBytes(byteSize);
    var arr = new Array(total);
    for (var i = 0; i < total; i++) {
      arr[i] = parser(stream);
    }
    return arr;
  };
};
exports.readArray = readArray;
var subBitsTotal = function subBitsTotal(bits, startIndex, length) {
  var result = 0;
  for (var i = 0; i < length; i++) {
    result += bits[startIndex + i] && Math.pow(2, length - i - 1);
  }
  return result;
};
var readBits = function readBits(schema) {
  return function (stream) {
    var _byte = readByte()(stream); // convert the byte to bit array

    var bits = new Array(8);
    for (var i = 0; i < 8; i++) {
      bits[7 - i] = !!(_byte & 1 << i);
    } // convert the bit array to values based on the schema

    return Object.keys(schema).reduce(function (res, key) {
      var def = schema[key];
      if (def.length) {
        res[key] = subBitsTotal(bits, def.index, def.length);
      } else {
        res[key] = bits[def.index];
      }
      return res;
    }, {});
  };
};
exports.readBits = readBits;

/***/ }),

/***/ 7119:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = void 0;
var _ = __webpack_require__(3966);
var _uint = __webpack_require__(459);

// a set of 0x00 terminated subblocks
var subBlocksSchema = {
  blocks: function blocks(stream) {
    var terminator = 0x00;
    var chunks = [];
    var streamSize = stream.data.length;
    var total = 0;
    for (var size = (0, _uint.readByte)()(stream); size !== terminator; size = (0, _uint.readByte)()(stream)) {
      // size becomes undefined for some case when file is corrupted and  terminator is not proper 
      // null check to avoid recursion
      if (!size) break; // catch corrupted files with no terminator

      if (stream.pos + size >= streamSize) {
        var availableSize = streamSize - stream.pos;
        chunks.push((0, _uint.readBytes)(availableSize)(stream));
        total += availableSize;
        break;
      }
      chunks.push((0, _uint.readBytes)(size)(stream));
      total += size;
    }
    var result = new Uint8Array(total);
    var offset = 0;
    for (var i = 0; i < chunks.length; i++) {
      result.set(chunks[i], offset);
      offset += chunks[i].length;
    }
    return result;
  }
}; // global control extension

var gceSchema = (0, _.conditional)({
  gce: [{
    codes: (0, _uint.readBytes)(2)
  }, {
    byteSize: (0, _uint.readByte)()
  }, {
    extras: (0, _uint.readBits)({
      future: {
        index: 0,
        length: 3
      },
      disposal: {
        index: 3,
        length: 3
      },
      userInput: {
        index: 6
      },
      transparentColorGiven: {
        index: 7
      }
    })
  }, {
    delay: (0, _uint.readUnsigned)(true)
  }, {
    transparentColorIndex: (0, _uint.readByte)()
  }, {
    terminator: (0, _uint.readByte)()
  }]
}, function (stream) {
  var codes = (0, _uint.peekBytes)(2)(stream);
  return codes[0] === 0x21 && codes[1] === 0xf9;
}); // image pipeline block

var imageSchema = (0, _.conditional)({
  image: [{
    code: (0, _uint.readByte)()
  }, {
    descriptor: [{
      left: (0, _uint.readUnsigned)(true)
    }, {
      top: (0, _uint.readUnsigned)(true)
    }, {
      width: (0, _uint.readUnsigned)(true)
    }, {
      height: (0, _uint.readUnsigned)(true)
    }, {
      lct: (0, _uint.readBits)({
        exists: {
          index: 0
        },
        interlaced: {
          index: 1
        },
        sort: {
          index: 2
        },
        future: {
          index: 3,
          length: 2
        },
        size: {
          index: 5,
          length: 3
        }
      })
    }]
  }, (0, _.conditional)({
    lct: (0, _uint.readArray)(3, function (stream, result, parent) {
      return Math.pow(2, parent.descriptor.lct.size + 1);
    })
  }, function (stream, result, parent) {
    return parent.descriptor.lct.exists;
  }), {
    data: [{
      minCodeSize: (0, _uint.readByte)()
    }, subBlocksSchema]
  }]
}, function (stream) {
  return (0, _uint.peekByte)()(stream) === 0x2c;
}); // plain text block

var textSchema = (0, _.conditional)({
  text: [{
    codes: (0, _uint.readBytes)(2)
  }, {
    blockSize: (0, _uint.readByte)()
  }, {
    preData: function preData(stream, result, parent) {
      return (0, _uint.readBytes)(parent.text.blockSize)(stream);
    }
  }, subBlocksSchema]
}, function (stream) {
  var codes = (0, _uint.peekBytes)(2)(stream);
  return codes[0] === 0x21 && codes[1] === 0x01;
}); // application block

var applicationSchema = (0, _.conditional)({
  application: [{
    codes: (0, _uint.readBytes)(2)
  }, {
    blockSize: (0, _uint.readByte)()
  }, {
    id: function id(stream, result, parent) {
      return (0, _uint.readString)(parent.blockSize)(stream);
    }
  }, subBlocksSchema]
}, function (stream) {
  var codes = (0, _uint.peekBytes)(2)(stream);
  return codes[0] === 0x21 && codes[1] === 0xff;
}); // comment block

var commentSchema = (0, _.conditional)({
  comment: [{
    codes: (0, _uint.readBytes)(2)
  }, subBlocksSchema]
}, function (stream) {
  var codes = (0, _uint.peekBytes)(2)(stream);
  return codes[0] === 0x21 && codes[1] === 0xfe;
});
var schema = [{
  header: [{
    signature: (0, _uint.readString)(3)
  }, {
    version: (0, _uint.readString)(3)
  }]
}, {
  lsd: [{
    width: (0, _uint.readUnsigned)(true)
  }, {
    height: (0, _uint.readUnsigned)(true)
  }, {
    gct: (0, _uint.readBits)({
      exists: {
        index: 0
      },
      resolution: {
        index: 1,
        length: 3
      },
      sort: {
        index: 4
      },
      size: {
        index: 5,
        length: 3
      }
    })
  }, {
    backgroundColorIndex: (0, _uint.readByte)()
  }, {
    pixelAspectRatio: (0, _uint.readByte)()
  }]
}, (0, _.conditional)({
  gct: (0, _uint.readArray)(3, function (stream, result) {
    return Math.pow(2, result.lsd.gct.size + 1);
  })
}, function (stream, result) {
  return result.lsd.gct.exists;
}),
// content frames
{
  frames: (0, _.loop)([gceSchema, applicationSchema, commentSchema, imageSchema, textSchema], function (stream) {
    var nextCode = (0, _uint.peekByte)()(stream); // rather than check for a terminator, we should check for the existence
    // of an ext or image block to avoid infinite loops
    //var terminator = 0x3B;
    //return nextCode !== terminator;

    return nextCode === 0x21 || nextCode === 0x2c;
  })
}];
var _default = schema;
exports["default"] = _default;

/***/ }),

/***/ 4677:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


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);
}
var immediate = __webpack_require__(9114);

/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
  if (typeof resolver !== 'function') {
    throw new TypeError('resolver must be a function');
  }
  this.state = PENDING;
  this.queue = [];
  this.outcome = void 0;
  if (resolver !== INTERNAL) {
    safelyResolveThenable(this, resolver);
  }
}
Promise.prototype["catch"] = function (onRejected) {
  return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
  if (typeof onFulfilled !== 'function' && this.state === FULFILLED || typeof onRejected !== 'function' && this.state === REJECTED) {
    return this;
  }
  var promise = new this.constructor(INTERNAL);
  if (this.state !== PENDING) {
    var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
    unwrap(promise, resolver, this.outcome);
  } else {
    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  }
  return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
  this.promise = promise;
  if (typeof onFulfilled === 'function') {
    this.onFulfilled = onFulfilled;
    this.callFulfilled = this.otherCallFulfilled;
  }
  if (typeof onRejected === 'function') {
    this.onRejected = onRejected;
    this.callRejected = this.otherCallRejected;
  }
}
QueueItem.prototype.callFulfilled = function (value) {
  handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
  unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
  handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
  unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
  immediate(function () {
    var returnValue;
    try {
      returnValue = func(value);
    } catch (e) {
      return handlers.reject(promise, e);
    }
    if (returnValue === promise) {
      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
    } else {
      handlers.resolve(promise, returnValue);
    }
  });
}
handlers.resolve = function (self, value) {
  var result = tryCatch(getThen, value);
  if (result.status === 'error') {
    return handlers.reject(self, result.value);
  }
  var thenable = result.value;
  if (thenable) {
    safelyResolveThenable(self, thenable);
  } else {
    self.state = FULFILLED;
    self.outcome = value;
    var i = -1;
    var len = self.queue.length;
    while (++i < len) {
      self.queue[i].callFulfilled(value);
    }
  }
  return self;
};
handlers.reject = function (self, error) {
  self.state = REJECTED;
  self.outcome = error;
  var i = -1;
  var len = self.queue.length;
  while (++i < len) {
    self.queue[i].callRejected(error);
  }
  return self;
};
function getThen(obj) {
  // Make sure we only access the accessor once as required by the spec
  var then = obj && obj.then;
  if (obj && (_typeof(obj) === 'object' || typeof obj === 'function') && typeof then === 'function') {
    return function appyThen() {
      then.apply(obj, arguments);
    };
  }
}
function safelyResolveThenable(self, thenable) {
  // Either fulfill, reject or reject with error
  var called = false;
  function onError(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.reject(self, value);
  }
  function onSuccess(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.resolve(self, value);
  }
  function tryToUnwrap() {
    thenable(onSuccess, onError);
  }
  var result = tryCatch(tryToUnwrap);
  if (result.status === 'error') {
    onError(result.value);
  }
}
function tryCatch(func, value) {
  var out = {};
  try {
    out.value = func(value);
    out.status = 'success';
  } catch (e) {
    out.status = 'error';
    out.value = e;
  }
  return out;
}
Promise.resolve = resolve;
function resolve(value) {
  if (value instanceof this) {
    return value;
  }
  return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
  var promise = new this(INTERNAL);
  return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
  var self = this;
  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
    return this.reject(new TypeError('must be an array'));
  }
  var len = iterable.length;
  var called = false;
  if (!len) {
    return this.resolve([]);
  }
  var values = new Array(len);
  var resolved = 0;
  var i = -1;
  var promise = new this(INTERNAL);
  while (++i < len) {
    allResolver(iterable[i], i);
  }
  return promise;
  function allResolver(value, i) {
    self.resolve(value).then(resolveFromAll, function (error) {
      if (!called) {
        called = true;
        handlers.reject(promise, error);
      }
    });
    function resolveFromAll(outValue) {
      values[i] = outValue;
      if (++resolved === len && !called) {
        called = true;
        handlers.resolve(promise, values);
      }
    }
  }
}
Promise.race = race;
function race(iterable) {
  var self = this;
  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
    return this.reject(new TypeError('must be an array'));
  }
  var len = iterable.length;
  var called = false;
  if (!len) {
    return this.resolve([]);
  }
  var i = -1;
  var promise = new this(INTERNAL);
  while (++i < len) {
    resolver(iterable[i]);
  }
  return promise;
  function resolver(value) {
    self.resolve(value).then(function (response) {
      if (!called) {
        called = true;
        handlers.resolve(promise, response);
      }
    }, function (error) {
      if (!called) {
        called = true;
        handlers.reject(promise, error);
      }
    });
  }
}

/***/ }),

/***/ 3968:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


if (typeof __webpack_require__.g.Promise !== 'function') {
  __webpack_require__.g.Promise = __webpack_require__(4677);
}

/***/ }),

/***/ 388:
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;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);
}
/*!
MIT License

Copyright (c) 2018 Arturas Molcanovas <a.molcanovas@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

(function (global, factory) {
  ( false ? 0 : _typeof(exports)) === 'object' && "object" !== 'undefined' ? factory(exports) :  true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
})(typeof self !== 'undefined' ? self : this, function (exports) {
  'use strict';

  var _driver = 'localforage-driver-memory';

  /*! *****************************************************************************
  Copyright (c) Microsoft Corporation. All rights reserved.
  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
    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  MERCHANTABLITY OR NON-INFRINGEMENT.
    See the Apache Version 2.0 License for specific language governing permissions
  and limitations under the License.
  ***************************************************************************** */

  function __values(o) {
    var m = typeof Symbol === "function" && o[Symbol.iterator],
      i = 0;
    if (m) return m.call(o);
    return {
      next: function next() {
        if (o && i >= o.length) o = void 0;
        return {
          value: o && o[i++],
          done: !o
        };
      }
    };
  }

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

  /**
   * Abstracts constructing a Blob object, so it also works in older
   * browsers that don't support the native Blob constructor. (i.e.
   * old QtWebKit versions, at least).
   * Abstracts constructing a Blob object, so it also works in older
   * browsers that don't support the native Blob constructor. (i.e.
   * old QtWebKit versions, at least).
   *
   * @param parts
   * @param properties
   */
  function createBlob(parts, properties) {
    /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
    parts = parts || [];
    properties = properties || {};
    try {
      return new Blob(parts, properties);
    } catch (e) {
      if (e.name !== 'TypeError') {
        throw e;
      }
      //tslint:disable-next-line:variable-name
      var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
      var builder = new Builder();
      for (var i = 0; i < parts.length; i += 1) {
        builder.append(parts[i]);
      }
      return builder.getBlob(properties.type);
    }
  }
  var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
  var SERIALIZED_MARKER_LENGTH = "__lfsc__:" /* SERIALIZED_MARKER */.length;
  var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + "arbf" /* TYPE_ARRAYBUFFER */.length;
  //tslint:disable:no-magic-numbers no-bitwise prefer-switch no-unbound-method
  var toString = Object.prototype.toString;
  function stringToBuffer(serializedString) {
    // Fill the string into a ArrayBuffer.
    var bufferLength = serializedString.length * 0.75;
    var len = serializedString.length;
    if (serializedString[serializedString.length - 1] === '=') {
      bufferLength--;
      if (serializedString[serializedString.length - 2] === '=') {
        bufferLength--;
      }
    }
    var buffer = new ArrayBuffer(bufferLength);
    var bytes = new Uint8Array(buffer);
    for (var i = 0, p = 0; i < len; i += 4) {
      var encoded1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i]);
      var encoded2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 1]);
      var encoded3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 2]);
      var encoded4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 3]);
      bytes[p++] = encoded1 << 2 | encoded2 >> 4;
      bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
      bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
    }
    return buffer;
  }
  /**
   * Converts a buffer to a string to store, serialized, in the backend
   * storage library.
   */
  function bufferToString(buffer) {
    // base64-arraybuffer
    var bytes = new Uint8Array(buffer);
    var base64String = '';
    for (var i = 0; i < bytes.length; i += 3) {
      /*jslint bitwise: true */
      base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i] >> 2];
      base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
      base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
      base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i + 2] & 63];
    }
    if (bytes.length % 3 === 2) {
      base64String = base64String.substring(0, base64String.length - 1) + '=';
    } else if (bytes.length % 3 === 1) {
      base64String = base64String.substring(0, base64String.length - 2) + '==';
    }
    return base64String;
  }
  /**
   * Serialize a value, afterwards executing a callback (which usually
   * instructs the `setItem()` callback/promise to be executed). This is how
   * we store binary data with localStorage.
   * @param value
   * @param callback
   */
  function serialize(value, callback) {
    var valueType = '';
    if (value) {
      valueType = toString.call(value);
    }
    // Cannot use `value instanceof ArrayBuffer` or such here, as these
    // checks fail when running the tests using casper.js...
    if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString.call(value.buffer) === '[object ArrayBuffer]')) {
      // Convert binary arrays to a string and prefix the string with
      // a special marker.
      var buffer = void 0;
      var marker = "__lfsc__:" /* SERIALIZED_MARKER */;
      if (value instanceof ArrayBuffer) {
        buffer = value;
        marker += "arbf" /* TYPE_ARRAYBUFFER */;
      } else {
        buffer = value.buffer;
        if (valueType === '[object Int8Array]') {
          marker += "si08" /* TYPE_INT8ARRAY */;
        } else if (valueType === '[object Uint8Array]') {
          marker += "ui08" /* TYPE_UINT8ARRAY */;
        } else if (valueType === '[object Uint8ClampedArray]') {
          marker += "uic8" /* TYPE_UINT8CLAMPEDARRAY */;
        } else if (valueType === '[object Int16Array]') {
          marker += "si16" /* TYPE_INT16ARRAY */;
        } else if (valueType === '[object Uint16Array]') {
          marker += "ur16" /* TYPE_UINT16ARRAY */;
        } else if (valueType === '[object Int32Array]') {
          marker += "si32" /* TYPE_INT32ARRAY */;
        } else if (valueType === '[object Uint32Array]') {
          marker += "ui32" /* TYPE_UINT32ARRAY */;
        } else if (valueType === '[object Float32Array]') {
          marker += "fl32" /* TYPE_FLOAT32ARRAY */;
        } else if (valueType === '[object Float64Array]') {
          marker += "fl64" /* TYPE_FLOAT64ARRAY */;
        } else {
          callback(new Error('Failed to get type for BinaryArray'));
        }
      }
      callback(marker + bufferToString(buffer));
    } else if (valueType === '[object Blob]') {
      // Convert the blob to a binaryArray and then to a string.
      var fileReader = new FileReader();
      fileReader.onload = function () {
        // Backwards-compatible prefix for the blob type.
        //tslint:disable-next-line:restrict-plus-operands
        var str = "~~local_forage_type~" /* BLOB_TYPE_PREFIX */ + value.type + "~" + bufferToString(this.result);
        callback("__lfsc__:" /* SERIALIZED_MARKER */ + "blob" /* TYPE_BLOB */ + str);
      };
      fileReader.readAsArrayBuffer(value);
    } else {
      try {
        callback(JSON.stringify(value));
      } catch (e) {
        console.error('Couldn\'t convert value into a JSON string: ', value);
        callback(null, e);
      }
    }
  }
  /**
   * Deserialize data we've inserted into a value column/field. We place
   * special markers into our strings to mark them as encoded; this isn't
   * as nice as a meta field, but it's the only sane thing we can do whilst
   * keeping localStorage support intact.
   *
   * Oftentimes this will just deserialize JSON content, but if we have a
   * special marker (SERIALIZED_MARKER, defined above), we will extract
   * some kind of arraybuffer/binary data/typed array out of the string.
   * @param value
   */
  function deserialize(value) {
    // If we haven't marked this string as being specially serialized (i.e.
    // something other than serialized JSON), we can just return it and be
    // done with it.
    if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== "__lfsc__:" /* SERIALIZED_MARKER */) {
      return JSON.parse(value);
    }
    // The following code deals with deserializing some kind of Blob or
    // TypedArray. First we separate out the type of data we're dealing
    // with from the data itself.
    var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
    var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
    var blobType;
    // Backwards-compatible blob type serialization strategy.
    // DBs created with older versions of localForage will simply not have the blob type.
    if (type === "blob" /* TYPE_BLOB */ && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
      var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
      blobType = matcher[1];
      serializedString = serializedString.substring(matcher[0].length);
    }
    var buffer = stringToBuffer(serializedString);
    // Return the right type based on the code/type set during
    // serialization.
    switch (type) {
      case "arbf" /* TYPE_ARRAYBUFFER */:
        return buffer;
      case "blob" /* TYPE_BLOB */:
        return createBlob([buffer], {
          type: blobType
        });
      case "si08" /* TYPE_INT8ARRAY */:
        return new Int8Array(buffer);
      case "ui08" /* TYPE_UINT8ARRAY */:
        return new Uint8Array(buffer);
      case "uic8" /* TYPE_UINT8CLAMPEDARRAY */:
        return new Uint8ClampedArray(buffer);
      case "si16" /* TYPE_INT16ARRAY */:
        return new Int16Array(buffer);
      case "ur16" /* TYPE_UINT16ARRAY */:
        return new Uint16Array(buffer);
      case "si32" /* TYPE_INT32ARRAY */:
        return new Int32Array(buffer);
      case "ui32" /* TYPE_UINT32ARRAY */:
        return new Uint32Array(buffer);
      case "fl32" /* TYPE_FLOAT32ARRAY */:
        return new Float32Array(buffer);
      case "fl64" /* TYPE_FLOAT64ARRAY */:
        return new Float64Array(buffer);
      default:
        throw new Error('Unkown type: ' + type);
    }
  }
  function clone(obj) {
    var e_1, _a;
    if (obj === null || _typeof(obj) !== 'object' || 'isActiveClone' in obj) {
      return obj;
    }
    var temp = obj instanceof Date ? new Date(obj) : obj.constructor();
    try {
      for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
        var key = _c.value;
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          obj['isActiveClone'] = null;
          temp[key] = clone(obj[key]);
          delete obj['isActiveClone'];
        }
      }
    } catch (e_1_1) {
      e_1 = {
        error: e_1_1
      };
    } finally {
      try {
        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    return temp;
  }
  function getKeyPrefix(options, defaultConfig) {
    return (options.name || defaultConfig.name) + "/" + (options.storeName || defaultConfig.storeName) + "/";
  }
  function executeCallback(promise, callback) {
    if (callback) {
      promise.then(function (result) {
        callback(null, result);
      }, function (error) {
        callback(error);
      });
    }
  }
  function getCallback() {
    var _args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      _args[_i] = arguments[_i];
    }
    if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
      return arguments[arguments.length - 1];
    }
  }

  //tslint:disable-next-line:no-ignored-initial-value
  function dropInstanceCommon(options, callback) {
    var _this = this;
    callback = getCallback.apply(this, arguments);
    options = typeof options !== 'function' && options || {};
    if (!options.name) {
      var currentConfig = this.config();
      options.name = options.name || currentConfig.name;
      options.storeName = options.storeName || currentConfig.storeName;
    }
    var promise;
    if (!options.name) {
      promise = Promise.reject('Invalid arguments');
    } else {
      promise = new Promise(function (resolve) {
        if (!options.storeName) {
          resolve(options.name + "/");
        } else {
          resolve(getKeyPrefix(options, _this._defaultConfig));
        }
      });
    }
    return {
      promise: promise,
      callback: callback
    };
  }
  function normaliseKey(key) {
    // Cast the key to a string, as that's all we can set as a key.
    if (typeof key !== 'string') {
      console.warn(key + " used as a key, but it is not a string.");
      key = String(key);
    }
    return key;
  }
  var serialiser = {
    bufferToString: bufferToString,
    deserialize: deserialize,
    serialize: serialize,
    stringToBuffer: stringToBuffer
  };
  var stores = {};
  /** @internal */
  var Store = /** @class */function () {
    function Store(kp) {
      this.kp = kp;
      this.data = {};
    }
    Store.resolve = function (kp) {
      if (!stores[kp]) {
        stores[kp] = new Store(kp);
      }
      return stores[kp];
    };
    Store.prototype.clear = function () {
      this.data = {};
    };
    Store.prototype.drop = function () {
      this.clear();
      delete stores[this.kp];
    };
    Store.prototype.get = function (key) {
      return this.data[key];
    };
    Store.prototype.key = function (idx) {
      return this.keys()[idx];
    };
    Store.prototype.keys = function () {
      return Object.keys(this.data);
    };
    Store.prototype.rm = function (k) {
      delete this.data[k];
    };
    Store.prototype.set = function (k, v) {
      this.data[k] = v;
    };
    return Store;
  }();
  function _initStorage(options) {
    var opts = options ? clone(options) : {};
    var kp = getKeyPrefix(opts, this._defaultConfig);
    var store = Store.resolve(kp);
    this._dbInfo = opts;
    this._dbInfo.serializer = serialiser;
    this._dbInfo.keyPrefix = kp;
    this._dbInfo.mStore = store;
    return Promise.resolve();
  }
  function clear(callback) {
    var _this = this;
    var promise = this.ready().then(function () {
      _this._dbInfo.mStore.clear();
    });
    executeCallback(promise, callback);
    return promise;
  }
  function dropInstance(_options, _cb) {
    var _a = dropInstanceCommon.apply(this, arguments),
      promise = _a.promise,
      callback = _a.callback;
    var outPromise = promise.then(function (keyPrefix) {
      Store.resolve(keyPrefix).drop();
    });
    executeCallback(outPromise, callback);
    return promise;
  }
  function getItem(key$, callback) {
    var _this = this;
    key$ = normaliseKey(key$);
    var promise = this.ready().then(function () {
      var result = _this._dbInfo.mStore.get(key$);
      // Deserialise if the result is not null or undefined
      return result == null ? null : _this._dbInfo.serializer.deserialize(result); //tslint:disable-line:triple-equals
    });

    executeCallback(promise, callback);
    return promise;
  }
  function iterate(iterator, callback) {
    var _this = this;
    var promise = this.ready().then(function () {
      var store = _this._dbInfo.mStore;
      var keys = store.keys();
      for (var i = 0; i < keys.length; i++) {
        var value = store.get(keys[i]);
        // If a result was found, parse it from the serialized
        // string into a JS object. If result isn't truthy, the
        // key is likely undefined and we'll pass it straight
        // to the iterator.
        if (value) {
          value = _this._dbInfo.serializer.deserialize(value);
        }
        value = iterator(value, keys[i], i + 1);
        if (value !== undefined) {
          return value;
        }
      }
    });
    executeCallback(promise, callback);
    return promise;
  }
  function key(idx, callback) {
    var _this = this;
    var promise = this.ready().then(function () {
      var result;
      try {
        result = _this._dbInfo.mStore.key(idx);
        if (result === undefined) {
          result = null;
        }
      } catch (_a) {
        result = null;
      }
      return result;
    });
    executeCallback(promise, callback);
    return promise;
  }
  function keys(callback) {
    var _this = this;
    var promise = this.ready().then(function () {
      return _this._dbInfo.mStore.keys();
    });
    executeCallback(promise, callback);
    return promise;
  }
  function length(callback) {
    var promise = this.keys().then(function (keys$) {
      return keys$.length;
    });
    executeCallback(promise, callback);
    return promise;
  }
  function removeItem(key$, callback) {
    var _this = this;
    key$ = normaliseKey(key$);
    var promise = this.ready().then(function () {
      _this._dbInfo.mStore.rm(key$);
    });
    executeCallback(promise, callback);
    return promise;
  }
  function setItem(key$, value, callback) {
    var _this = this;
    key$ = normaliseKey(key$);
    var promise = this.ready().then(function () {
      if (value === undefined) {
        value = null;
      }
      // Save the original value to pass to the callback.
      var originalValue = value;
      return new Promise(function (resolve, reject) {
        _this._dbInfo.serializer.serialize(value, function (value$, error) {
          if (error) {
            reject(error);
          } else {
            try {
              _this._dbInfo.mStore.set(key$, value$);
              resolve(originalValue);
            } catch (e) {
              reject(e);
            }
          }
        });
      });
    });
    executeCallback(promise, callback);
    return promise;
  }
  var _support = true;
  exports._support = _support;
  exports._driver = _driver;
  exports._initStorage = _initStorage;
  exports.clear = clear;
  exports.dropInstance = dropInstance;
  exports.getItem = getItem;
  exports.iterate = iterate;
  exports.key = key;
  exports.keys = keys;
  exports.length = length;
  exports.removeItem = removeItem;
  exports.setItem = setItem;
  Object.defineProperty(exports, '__esModule', {
    value: true
  });
});

/***/ }),

/***/ 829:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;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 (global, factory) {
  ( false ? 0 : _typeof(exports)) === 'object' && "object" !== 'undefined' ? factory(exports, __webpack_require__(4038)) :  true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(4038)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
})(this, function (exports, localforage) {
  'use strict';

  localforage = 'default' in localforage ? localforage['default'] : localforage;
  function getSerializerPromise(localForageInstance) {
    if (getSerializerPromise.result) {
      return getSerializerPromise.result;
    }
    if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {
      return Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));
    }
    getSerializerPromise.result = localForageInstance.getSerializer();
    return getSerializerPromise.result;
  }
  function executeCallback(promise, callback) {
    if (callback) {
      promise.then(function (result) {
        callback(null, result);
      }, function (error) {
        callback(error);
      });
    }
  }
  function forEachItem(items, keyFn, valueFn, loopFn) {
    function ensurePropGetterMethod(propFn, defaultPropName) {
      var propName = propFn || defaultPropName;
      if ((!propFn || typeof propFn !== 'function') && typeof propName === 'string') {
        propFn = function propFn(item) {
          return item[propName];
        };
      }
      return propFn;
    }
    var result = [];
    // http://stackoverflow.com/questions/4775722/check-if-object-is-array
    if (Object.prototype.toString.call(items) === '[object Array]') {
      keyFn = ensurePropGetterMethod(keyFn, 'key');
      valueFn = ensurePropGetterMethod(valueFn, 'value');
      for (var i = 0, len = items.length; i < len; i++) {
        var item = items[i];
        result.push(loopFn(keyFn(item), valueFn(item)));
      }
    } else {
      for (var prop in items) {
        if (items.hasOwnProperty(prop)) {
          result.push(loopFn(prop, items[prop]));
        }
      }
    }
    return result;
  }
  function setItemsIndexedDB(items, keyFn, valueFn, callback) {
    var localforageInstance = this;
    var promise = localforageInstance.ready().then(function () {
      return new Promise(function (resolve, reject) {
        // Inspired from @lu4 PR mozilla/localForage#318
        var dbInfo = localforageInstance._dbInfo;
        var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
        var store = transaction.objectStore(dbInfo.storeName);
        var lastError;
        transaction.oncomplete = function () {
          resolve(items);
        };
        transaction.onabort = transaction.onerror = function (event) {
          reject(lastError || event.target);
        };
        function requestOnError(evt) {
          var request = evt.target || this;
          lastError = request.error || request.transaction.error;
          reject(lastError);
        }
        forEachItem(items, keyFn, valueFn, function (key, value) {
          // The reason we don't _save_ null is because IE 10 does
          // not support saving the `null` type in IndexedDB. How
          // ironic, given the bug below!
          // See: https://github.com/mozilla/localForage/issues/161
          if (value === null) {
            value = undefined;
          }
          var request = store.put(value, key);
          request.onerror = requestOnError;
        });
      });
    });
    executeCallback(promise, callback);
    return promise;
  }
  function setItemsWebsql(items, keyFn, valueFn, callback) {
    var localforageInstance = this;
    var promise = new Promise(function (resolve, reject) {
      localforageInstance.ready().then(function () {
        return getSerializerPromise(localforageInstance);
      }).then(function (serializer) {
        // Inspired from @lu4 PR mozilla/localForage#318
        var dbInfo = localforageInstance._dbInfo;
        dbInfo.db.transaction(function (t) {
          var query = 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)';
          var itemPromises = forEachItem(items, keyFn, valueFn, function (key, value) {
            return new Promise(function (resolve, reject) {
              serializer.serialize(value, function (value, error) {
                if (error) {
                  reject(error);
                } else {
                  t.executeSql(query, [key, value], function () {
                    resolve();
                  }, function (t, error) {
                    reject(error);
                  });
                }
              });
            });
          });
          Promise.all(itemPromises).then(function () {
            resolve(items);
          }, reject);
        }, function (sqlError) {
          reject(sqlError);
        } /*, function() {
             if (resolving) {
                 resolve(items);
             }
          }*/);
      }).catch(reject);
    });
    executeCallback(promise, callback);
    return promise;
  }
  function setItemsGeneric(items, keyFn, valueFn, callback) {
    var localforageInstance = this;
    var itemPromises = forEachItem(items, keyFn, valueFn, function (key, value) {
      return localforageInstance.setItem(key, value);
    });
    var promise = Promise.all(itemPromises);
    executeCallback(promise, callback);
    return promise;
  }
  function localforageSetItems(items, keyFn, valueFn, callback) {
    var localforageInstance = this;
    var currentDriver = localforageInstance.driver();
    if (currentDriver === localforageInstance.INDEXEDDB) {
      return setItemsIndexedDB.call(localforageInstance, items, keyFn, valueFn, callback);
    } else if (currentDriver === localforageInstance.WEBSQL) {
      return setItemsWebsql.call(localforageInstance, items, keyFn, valueFn, callback);
    } else {
      return setItemsGeneric.call(localforageInstance, items, keyFn, valueFn, callback);
    }
  }
  function extendPrototype(localforage$$1) {
    var localforagePrototype = Object.getPrototypeOf(localforage$$1);
    if (localforagePrototype) {
      localforagePrototype.setItems = localforageSetItems;
      localforagePrototype.setItems.indexedDB = function () {
        return setItemsIndexedDB.apply(this, arguments);
      };
      localforagePrototype.setItems.websql = function () {
        return setItemsWebsql.apply(this, arguments);
      };
      localforagePrototype.setItems.generic = function () {
        return setItemsGeneric.apply(this, arguments);
      };
    }
  }
  var extendPrototypeResult = extendPrototype(localforage);
  exports.setItemsGeneric = setItemsGeneric;
  exports.localforageSetItems = localforageSetItems;
  exports.extendPrototype = extendPrototype;
  exports.extendPrototypeResult = extendPrototypeResult;
  Object.defineProperty(exports, '__esModule', {
    value: true
  });
});

/***/ }),

/***/ 5601:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var _interopRequireDefault = __webpack_require__(6049);
Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = createDriver;
var _regenerator = _interopRequireDefault(__webpack_require__(80));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(4662));
var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(8563));
var _utils = __webpack_require__(7891);
function createDriver(name, property) {
  var storage = (0, _utils.getStorage)();
  var support = !!(storage && storage[property]);
  var driver = support ? storage[property] : {
    clear: function clear() {},
    get: function get() {},
    remove: function remove() {},
    set: function set() {}
  };
  var _clear = driver.clear.bind(driver);
  var get = driver.get.bind(driver);
  var remove = driver.remove.bind(driver);
  var set = driver.set.bind(driver);
  return {
    _driver: name,
    _support: support,
    // eslint-disable-next-line no-underscore-dangle
    _initStorage: function _initStorage() {
      return Promise.resolve();
    },
    clear: function clear(callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _clear();
                if (callback) callback();
              case 2:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))();
    },
    iterate: function iterate(iterator, callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
        var items, keys;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return (0, _utils.usePromise)(get, null);
              case 2:
                items = _context2.sent;
                keys = Object.keys(items);
                keys.forEach(function (key, i) {
                  return iterator(items[key], key, i);
                });
                if (callback) callback();
              case 6:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))();
    },
    getItem: function getItem(key, callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
        var result;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.prev = 0;
                _context3.next = 3;
                return (0, _utils.usePromise)(get, key);
              case 3:
                result = _context3.sent;
                result = typeof key === 'string' ? result[key] : result;
                result = result === undefined ? null : result;
                if (callback) callback(null, result);
                return _context3.abrupt("return", result);
              case 10:
                _context3.prev = 10;
                _context3.t0 = _context3["catch"](0);
                if (callback) callback(_context3.t0);
                throw _context3.t0;
              case 14:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, null, [[0, 10]]);
      }))();
    },
    key: function key(n, callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
        var results, key;
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return (0, _utils.usePromise)(get, null);
              case 2:
                results = _context4.sent;
                key = Object.keys(results)[n];
                if (callback) callback(key);
                return _context4.abrupt("return", key);
              case 6:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }))();
    },
    keys: function keys(callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
        var results, keys;
        return _regenerator["default"].wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _context5.next = 2;
                return (0, _utils.usePromise)(get, null);
              case 2:
                results = _context5.sent;
                keys = Object.keys(results);
                if (callback) callback(keys);
                return _context5.abrupt("return", keys);
              case 6:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5);
      }))();
    },
    length: function length(callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
        var results, _Object$keys, length;
        return _regenerator["default"].wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.next = 2;
                return (0, _utils.usePromise)(get, null);
              case 2:
                results = _context6.sent;
                _Object$keys = Object.keys(results), length = _Object$keys.length;
                if (callback) callback(length);
                return _context6.abrupt("return", length);
              case 6:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6);
      }))();
    },
    removeItem: function removeItem(key, callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() {
        return _regenerator["default"].wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _context7.next = 2;
                return (0, _utils.usePromise)(remove, key);
              case 2:
                if (callback) callback();
              case 3:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7);
      }))();
    },
    setItem: function setItem(key, value, callback) {
      return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() {
        return _regenerator["default"].wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return (0, _utils.usePromise)(set, (0, _defineProperty2["default"])({}, key, value));
              case 2:
                if (callback) callback();
              case 3:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8);
      }))();
    }
  };
}

/***/ }),

/***/ 3710:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
var __webpack_unused_export__;


var _interopRequireDefault = __webpack_require__(6049);
__webpack_unused_export__ = ({
  value: true
});
exports.Z = void 0;
var _driver = _interopRequireDefault(__webpack_require__(5601));
var _default = (0, _driver["default"])('webExtensionLocalStorage', 'local');
exports.Z = _default;

/***/ }),

/***/ 7777:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
var __webpack_unused_export__;


var _interopRequireDefault = __webpack_require__(6049);
__webpack_unused_export__ = ({
  value: true
});
exports.Z = void 0;
var _driver = _interopRequireDefault(__webpack_require__(5601));
var _default = (0, _driver["default"])('webExtensionSyncStorage', 'sync');
exports.Z = _default;

/***/ }),

/***/ 7891:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.getStorage = getStorage;
exports.usePromise = usePromise;

/**
 * Need to invoke a function at runtime instead of import-time to make tests
 * pass with mocked browser and chrome objects
 */
function getStorage() {
  return typeof browser !== 'undefined' && browser.storage || typeof chrome !== 'undefined' && chrome.storage;
}
/**
 * Need to invoke a function at runtime instead of import-time to make tests
 * pass with mocked browser and chrome objects
 */

function usesPromises() {
  var storage = getStorage();
  try {
    return storage && storage.local.get && storage.local.get() && typeof storage.local.get().then === 'function';
  } catch (e) {
    return false;
  }
}
/**
 * Converts a callback-based API to a promise based API.
 * For now we assume that there is only one arg in addition to the callback
 */

function usePromise(fn, arg) {
  if (usesPromises()) {
    return fn(arg);
  }
  return new Promise(function (resolve) {
    fn(arg, function () {
      resolve.apply(void 0, arguments);
    });
  });
}

/***/ }),

/***/ 8137:
/***/ ((module, exports, __webpack_require__) => {

var __WEBPACK_AMD_DEFINE_RESULT__;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);
}
/* global window, exports, define */

!function () {
  'use strict';

  var re = {
    not_string: /[^s]/,
    not_bool: /[^t]/,
    not_type: /[^T]/,
    not_primitive: /[^v]/,
    number: /[diefg]/,
    numeric_arg: /[bcdiefguxX]/,
    json: /[j]/,
    not_json: /[^j]/,
    text: /^[^\x25]+/,
    modulo: /^\x25{2}/,
    placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
    key: /^([a-z_][a-z_\d]*)/i,
    key_access: /^\.([a-z_][a-z_\d]*)/i,
    index_access: /^\[(\d+)\]/,
    sign: /^[+-]/
  };
  function sprintf(key) {
    // `arguments` is not an array, but should be fine for this call
    return sprintf_format(sprintf_parse(key), arguments);
  }
  function vsprintf(fmt, argv) {
    return sprintf.apply(null, [fmt].concat(argv || []));
  }
  function sprintf_format(parse_tree, argv) {
    var cursor = 1,
      tree_length = parse_tree.length,
      arg,
      output = '',
      i,
      k,
      ph,
      pad,
      pad_character,
      pad_length,
      is_positive,
      sign;
    for (i = 0; i < tree_length; i++) {
      if (typeof parse_tree[i] === 'string') {
        output += parse_tree[i];
      } else if (_typeof(parse_tree[i]) === 'object') {
        ph = parse_tree[i]; // convenience purposes only
        if (ph.keys) {
          // keyword argument
          arg = argv[cursor];
          for (k = 0; k < ph.keys.length; k++) {
            if (arg == undefined) {
              throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
            }
            arg = arg[ph.keys[k]];
          }
        } else if (ph.param_no) {
          // positional argument (explicit)
          arg = argv[ph.param_no];
        } else {
          // positional argument (implicit)
          arg = argv[cursor++];
        }
        if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
          arg = arg();
        }
        if (re.numeric_arg.test(ph.type) && typeof arg !== 'number' && isNaN(arg)) {
          throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
        }
        if (re.number.test(ph.type)) {
          is_positive = arg >= 0;
        }
        switch (ph.type) {
          case 'b':
            arg = parseInt(arg, 10).toString(2);
            break;
          case 'c':
            arg = String.fromCharCode(parseInt(arg, 10));
            break;
          case 'd':
          case 'i':
            arg = parseInt(arg, 10);
            break;
          case 'j':
            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
            break;
          case 'e':
            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
            break;
          case 'f':
            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
            break;
          case 'g':
            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
            break;
          case 'o':
            arg = (parseInt(arg, 10) >>> 0).toString(8);
            break;
          case 's':
            arg = String(arg);
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;
          case 't':
            arg = String(!!arg);
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;
          case 'T':
            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;
          case 'u':
            arg = parseInt(arg, 10) >>> 0;
            break;
          case 'v':
            arg = arg.valueOf();
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;
          case 'x':
            arg = (parseInt(arg, 10) >>> 0).toString(16);
            break;
          case 'X':
            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
            break;
        }
        if (re.json.test(ph.type)) {
          output += arg;
        } else {
          if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
            sign = is_positive ? '+' : '-';
            arg = arg.toString().replace(re.sign, '');
          } else {
            sign = '';
          }
          pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
          pad_length = ph.width - (sign + arg).length;
          pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : '' : '';
          output += ph.align ? sign + arg + pad : pad_character === '0' ? sign + pad + arg : pad + sign + arg;
        }
      }
    }
    return output;
  }
  var sprintf_cache = Object.create(null);
  function sprintf_parse(fmt) {
    if (sprintf_cache[fmt]) {
      return sprintf_cache[fmt];
    }
    var _fmt = fmt,
      match,
      parse_tree = [],
      arg_names = 0;
    while (_fmt) {
      if ((match = re.text.exec(_fmt)) !== null) {
        parse_tree.push(match[0]);
      } else if ((match = re.modulo.exec(_fmt)) !== null) {
        parse_tree.push('%');
      } else if ((match = re.placeholder.exec(_fmt)) !== null) {
        if (match[2]) {
          arg_names |= 1;
          var field_list = [],
            replacement_field = match[2],
            field_match = [];
          if ((field_match = re.key.exec(replacement_field)) !== null) {
            field_list.push(field_match[1]);
            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
              if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                field_list.push(field_match[1]);
              } else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                field_list.push(field_match[1]);
              } else {
                throw new SyntaxError('[sprintf] failed to parse named argument key');
              }
            }
          } else {
            throw new SyntaxError('[sprintf] failed to parse named argument key');
          }
          match[2] = field_list;
        } else {
          arg_names |= 2;
        }
        if (arg_names === 3) {
          throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
        }
        parse_tree.push({
          placeholder: match[0],
          param_no: match[1],
          keys: match[2],
          sign: match[3],
          pad_char: match[4],
          align: match[5],
          width: match[6],
          precision: match[7],
          type: match[8]
        });
      } else {
        throw new SyntaxError('[sprintf] unexpected placeholder');
      }
      _fmt = _fmt.substring(match[0].length);
    }
    return sprintf_cache[fmt] = parse_tree;
  }

  /**
   * export to either browser or node.js
   */
  /* eslint-disable quote-props */
  if (true) {
    exports.sprintf = sprintf;
    exports.vsprintf = vsprintf;
  }
  if (typeof window !== 'undefined') {
    window['sprintf'] = sprintf;
    window['vsprintf'] = vsprintf;
    if (true) {
      !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
        return {
          'sprintf': sprintf,
          'vsprintf': vsprintf
        };
      }).call(exports, __webpack_require__, exports, module),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    }
  }
  /* eslint-enable quote-props */
}(); // eslint-disable-line

/***/ }),

/***/ 9265:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "default": () => (/* binding */ src)
});

;// CONCATENATED MODULE: ./node_modules/lodash-es/_freeGlobal.js
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);
}
/** Detect free variable `global` from Node.js. */
var freeGlobal = (typeof global === "undefined" ? "undefined" : _typeof(global)) == 'object' && global && global.Object === Object && global;
/* harmony default export */ const _freeGlobal = (freeGlobal);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_root.js
function _root_typeof(obj) {
  "@babel/helpers - typeof";

  return _root_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;
  }, _root_typeof(obj);
}


/** Detect free variable `self`. */
var freeSelf = (typeof self === "undefined" ? "undefined" : _root_typeof(self)) == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
/* harmony default export */ const _root = (root);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Symbol.js


/** Built-in value references. */
var _Symbol = _root.Symbol;
/* harmony default export */ const lodash_es_Symbol = (_Symbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getRawTag.js


/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _getRawTag_hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Built-in value references. */
var symToStringTag = lodash_es_Symbol ? lodash_es_Symbol.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = _getRawTag_hasOwnProperty.call(value, symToStringTag),
    tag = value[symToStringTag];
  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}
  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}
/* harmony default export */ const _getRawTag = (getRawTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_objectToString.js
/** Used for built-in method references. */
var _objectToString_objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var _objectToString_nativeObjectToString = _objectToString_objectProto.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString(value) {
  return _objectToString_nativeObjectToString.call(value);
}
/* harmony default export */ const _objectToString = (objectToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetTag.js




/** `Object#toString` result references. */
var nullTag = '[object Null]',
  undefinedTag = '[object Undefined]';

/** Built-in value references. */
var _baseGetTag_symToStringTag = lodash_es_Symbol ? lodash_es_Symbol.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return _baseGetTag_symToStringTag && _baseGetTag_symToStringTag in Object(value) ? _getRawTag(value) : _objectToString(value);
}
/* harmony default export */ const _baseGetTag = (baseGetTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isObject.js
function isObject_typeof(obj) {
  "@babel/helpers - typeof";

  return isObject_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;
  }, isObject_typeof(obj);
}
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = isObject_typeof(value);
  return value != null && (type == 'object' || type == 'function');
}
/* harmony default export */ const lodash_es_isObject = (isObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isFunction.js



/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
  funcTag = '[object Function]',
  genTag = '[object GeneratorFunction]',
  proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  if (!lodash_es_isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = _baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/* harmony default export */ const lodash_es_isFunction = (isFunction);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_coreJsData.js


/** Used to detect overreaching core-js shims. */
var coreJsData = _root['__core-js_shared__'];
/* harmony default export */ const _coreJsData = (coreJsData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isMasked.js


/** Used to detect methods masquerading as native. */
var maskSrcKey = function () {
  var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  return uid ? 'Symbol(src)_1.' + uid : '';
}();

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}
/* harmony default export */ const _isMasked = (isMasked);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_toSource.js
/** Used for built-in method references. */
var funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return func + '';
    } catch (e) {}
  }
  return '';
}
/* harmony default export */ const _toSource = (toSource);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNative.js





/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var _baseIsNative_funcProto = Function.prototype,
  _baseIsNative_objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var _baseIsNative_funcToString = _baseIsNative_funcProto.toString;

/** Used to check objects for own properties. */
var _baseIsNative_hasOwnProperty = _baseIsNative_objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' + _baseIsNative_funcToString.call(_baseIsNative_hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!lodash_es_isObject(value) || _isMasked(value)) {
    return false;
  }
  var pattern = lodash_es_isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(_toSource(value));
}
/* harmony default export */ const _baseIsNative = (baseIsNative);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getValue.js
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}
/* harmony default export */ const _getValue = (getValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getNative.js



/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = _getValue(object, key);
  return _baseIsNative(value) ? value : undefined;
}
/* harmony default export */ const _getNative = (getNative);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_defineProperty.js

var defineProperty = function () {
  try {
    var func = _getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}();
/* harmony default export */ const _defineProperty = (defineProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignValue.js


/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function baseAssignValue(object, key, value) {
  if (key == '__proto__' && _defineProperty) {
    _defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}
/* harmony default export */ const _baseAssignValue = (baseAssignValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/eq.js
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || value !== value && other !== other;
}
/* harmony default export */ const lodash_es_eq = (eq);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assignValue.js



/** Used for built-in method references. */
var _assignValue_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _assignValue_hasOwnProperty = _assignValue_objectProto.hasOwnProperty;

/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(_assignValue_hasOwnProperty.call(object, key) && lodash_es_eq(objValue, value)) || value === undefined && !(key in object)) {
    _baseAssignValue(object, key, value);
  }
}
/* harmony default export */ const _assignValue = (assignValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyObject.js



/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index = -1,
    length = props.length;
  while (++index < length) {
    var key = props[index];
    var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
    if (newValue === undefined) {
      newValue = source[key];
    }
    if (isNew) {
      _baseAssignValue(object, key, newValue);
    } else {
      _assignValue(object, key, newValue);
    }
  }
  return object;
}
/* harmony default export */ const _copyObject = (copyObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTimes.js
/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
    result = Array(n);
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}
/* harmony default export */ const _baseTimes = (baseTimes);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isObjectLike.js
function isObjectLike_typeof(obj) {
  "@babel/helpers - typeof";

  return isObjectLike_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;
  }, isObjectLike_typeof(obj);
}
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && isObjectLike_typeof(value) == 'object';
}
/* harmony default export */ const lodash_es_isObjectLike = (isObjectLike);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsArguments.js



/** `Object#toString` result references. */
var argsTag = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return lodash_es_isObjectLike(value) && _baseGetTag(value) == argsTag;
}
/* harmony default export */ const _baseIsArguments = (baseIsArguments);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArguments.js



/** Used for built-in method references. */
var isArguments_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var isArguments_hasOwnProperty = isArguments_objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = isArguments_objectProto.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = _baseIsArguments(function () {
  return arguments;
}()) ? _baseIsArguments : function (value) {
  return lodash_es_isObjectLike(value) && isArguments_hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
};
/* harmony default export */ const lodash_es_isArguments = (isArguments);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArray.js
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
/* harmony default export */ const lodash_es_isArray = (isArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/stubFalse.js
/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}
/* harmony default export */ const lodash_es_stubFalse = (stubFalse);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isBuffer.js
function isBuffer_typeof(obj) {
  "@babel/helpers - typeof";

  return isBuffer_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;
  }, isBuffer_typeof(obj);
}



/** Detect free variable `exports`. */
var freeExports = (typeof exports === "undefined" ? "undefined" : isBuffer_typeof(exports)) == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && (typeof module === "undefined" ? "undefined" : isBuffer_typeof(module)) == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || lodash_es_stubFalse;
/* harmony default export */ const lodash_es_isBuffer = (isBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIndex.js
function _isIndex_typeof(obj) {
  "@babel/helpers - typeof";

  return _isIndex_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;
  }, _isIndex_typeof(obj);
}
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  var type = _isIndex_typeof(value);
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
/* harmony default export */ const _isIndex = (isIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isLength.js
/** Used as references for various `Number` constants. */
var isLength_MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= isLength_MAX_SAFE_INTEGER;
}
/* harmony default export */ const lodash_es_isLength = (isLength);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsTypedArray.js




/** `Object#toString` result references. */
var _baseIsTypedArray_argsTag = '[object Arguments]',
  arrayTag = '[object Array]',
  boolTag = '[object Boolean]',
  dateTag = '[object Date]',
  errorTag = '[object Error]',
  _baseIsTypedArray_funcTag = '[object Function]',
  mapTag = '[object Map]',
  numberTag = '[object Number]',
  objectTag = '[object Object]',
  regexpTag = '[object RegExp]',
  setTag = '[object Set]',
  stringTag = '[object String]',
  weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
  dataViewTag = '[object DataView]',
  float32Tag = '[object Float32Array]',
  float64Tag = '[object Float64Array]',
  int8Tag = '[object Int8Array]',
  int16Tag = '[object Int16Array]',
  int32Tag = '[object Int32Array]',
  uint8Tag = '[object Uint8Array]',
  uint8ClampedTag = '[object Uint8ClampedArray]',
  uint16Tag = '[object Uint16Array]',
  uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[_baseIsTypedArray_argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[_baseIsTypedArray_funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return lodash_es_isObjectLike(value) && lodash_es_isLength(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
/* harmony default export */ const _baseIsTypedArray = (baseIsTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnary.js
/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function (value) {
    return func(value);
  };
}
/* harmony default export */ const _baseUnary = (baseUnary);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nodeUtil.js
function _nodeUtil_typeof(obj) {
  "@babel/helpers - typeof";

  return _nodeUtil_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;
  }, _nodeUtil_typeof(obj);
}


/** Detect free variable `exports`. */
var _nodeUtil_freeExports = (typeof exports === "undefined" ? "undefined" : _nodeUtil_typeof(exports)) == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var _nodeUtil_freeModule = _nodeUtil_freeExports && (typeof module === "undefined" ? "undefined" : _nodeUtil_typeof(module)) == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var _nodeUtil_moduleExports = _nodeUtil_freeModule && _nodeUtil_freeModule.exports === _nodeUtil_freeExports;

/** Detect free variable `process` from Node.js. */
var freeProcess = _nodeUtil_moduleExports && _freeGlobal.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = function () {
  try {
    // Use `util.types` for Node.js 10+.
    var types = _nodeUtil_freeModule && _nodeUtil_freeModule.require && _nodeUtil_freeModule.require('util').types;
    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}();
/* harmony default export */ const _nodeUtil = (nodeUtil);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isTypedArray.js




/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
/* harmony default export */ const lodash_es_isTypedArray = (isTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayLikeKeys.js







/** Used for built-in method references. */
var _arrayLikeKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _arrayLikeKeys_hasOwnProperty = _arrayLikeKeys_objectProto.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = lodash_es_isArray(value),
    isArg = !isArr && lodash_es_isArguments(value),
    isBuff = !isArr && !isArg && lodash_es_isBuffer(value),
    isType = !isArr && !isArg && !isBuff && lodash_es_isTypedArray(value),
    skipIndexes = isArr || isArg || isBuff || isType,
    result = skipIndexes ? _baseTimes(value.length, String) : [],
    length = result.length;
  for (var key in value) {
    if ((inherited || _arrayLikeKeys_hasOwnProperty.call(value, key)) && !(skipIndexes && (
    // Safari 9 has enumerable `arguments.length` in strict mode.
    key == 'length' ||
    // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == 'offset' || key == 'parent') ||
    // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
    // Skip index properties.
    _isIndex(key, length)))) {
      result.push(key);
    }
  }
  return result;
}
/* harmony default export */ const _arrayLikeKeys = (arrayLikeKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isPrototype.js
/** Used for built-in method references. */
var _isPrototype_objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
    proto = typeof Ctor == 'function' && Ctor.prototype || _isPrototype_objectProto;
  return value === proto;
}
/* harmony default export */ const _isPrototype = (isPrototype);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_overArg.js
/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function (arg) {
    return func(transform(arg));
  };
}
/* harmony default export */ const _overArg = (overArg);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeys.js


/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);
/* harmony default export */ const _nativeKeys = (nativeKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeys.js



/** Used for built-in method references. */
var _baseKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseKeys_hasOwnProperty = _baseKeys_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!_isPrototype(object)) {
    return _nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (_baseKeys_hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}
/* harmony default export */ const _baseKeys = (baseKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLike.js



/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && lodash_es_isLength(value.length) && !lodash_es_isFunction(value);
}
/* harmony default export */ const lodash_es_isArrayLike = (isArrayLike);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keys.js




/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
/* harmony default export */ const lodash_es_keys = (keys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssign.js



/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssign(object, source) {
  return object && _copyObject(source, lodash_es_keys(source), object);
}
/* harmony default export */ const _baseAssign = (baseAssign);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseCreate.js


/** Built-in value references. */
var objectCreate = Object.create;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */
var baseCreate = function () {
  function object() {}
  return function (proto) {
    if (!lodash_es_isObject(proto)) {
      return {};
    }
    if (objectCreate) {
      return objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object();
    object.prototype = undefined;
    return result;
  };
}();
/* harmony default export */ const _baseCreate = (baseCreate);
;// CONCATENATED MODULE: ./node_modules/lodash-es/create.js



/**
 * Creates an object that inherits from the `prototype` object. If a
 * `properties` object is given, its own enumerable string keyed properties
 * are assigned to the created object.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Object
 * @param {Object} prototype The object to inherit from.
 * @param {Object} [properties] The properties to assign to the object.
 * @returns {Object} Returns the new object.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * function Circle() {
 *   Shape.call(this);
 * }
 *
 * Circle.prototype = _.create(Shape.prototype, {
 *   'constructor': Circle
 * });
 *
 * var circle = new Circle;
 * circle instanceof Circle;
 * // => true
 *
 * circle instanceof Shape;
 * // => true
 */
function create(prototype, properties) {
  var result = _baseCreate(prototype);
  return properties == null ? result : _baseAssign(result, properties);
}
/* harmony default export */ const lodash_es_create = (create);
;// CONCATENATED MODULE: ./node_modules/lodash-es/identity.js
/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity(value) {
  return value;
}
/* harmony default export */ const lodash_es_identity = (identity);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_apply.js
/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);
    case 1:
      return func.call(thisArg, args[0]);
    case 2:
      return func.call(thisArg, args[0], args[1]);
    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
/* harmony default export */ const _apply = (apply);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_overRest.js


/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */
function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  return function () {
    var args = arguments,
      index = -1,
      length = nativeMax(args.length - start, 0),
      array = Array(length);
    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array);
    return _apply(func, this, otherArgs);
  };
}
/* harmony default export */ const _overRest = (overRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/constant.js
/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function () {
    return value;
  };
}
/* harmony default export */ const lodash_es_constant = (constant);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSetToString.js




/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var baseSetToString = !_defineProperty ? lodash_es_identity : function (func, string) {
  return _defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': lodash_es_constant(string),
    'writable': true
  });
};
/* harmony default export */ const _baseSetToString = (baseSetToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_shortOut.js
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
  HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */
function shortOut(func) {
  var count = 0,
    lastCalled = 0;
  return function () {
    var stamp = nativeNow(),
      remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(undefined, arguments);
  };
}
/* harmony default export */ const _shortOut = (shortOut);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToString.js



/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var setToString = _shortOut(_baseSetToString);
/* harmony default export */ const _setToString = (setToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRest.js




/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  return _setToString(_overRest(func, start, lodash_es_identity), func + '');
}
/* harmony default export */ const _baseRest = (baseRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIterateeCall.js
function _isIterateeCall_typeof(obj) {
  "@babel/helpers - typeof";

  return _isIterateeCall_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;
  }, _isIterateeCall_typeof(obj);
}





/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!lodash_es_isObject(object)) {
    return false;
  }
  var type = _isIterateeCall_typeof(index);
  if (type == 'number' ? lodash_es_isArrayLike(object) && _isIndex(index, object.length) : type == 'string' && index in object) {
    return lodash_es_eq(object[index], value);
  }
  return false;
}
/* harmony default export */ const _isIterateeCall = (isIterateeCall);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createAssigner.js



/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */
function createAssigner(assigner) {
  return _baseRest(function (object, sources) {
    var index = -1,
      length = sources.length,
      customizer = length > 1 ? sources[length - 1] : undefined,
      guard = length > 2 ? sources[2] : undefined;
    customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined;
    if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }
    object = Object(object);
    while (++index < length) {
      var source = sources[index];
      if (source) {
        assigner(object, source, index, customizer);
      }
    }
    return object;
  });
}
/* harmony default export */ const _createAssigner = (createAssigner);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeysIn.js
/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function nativeKeysIn(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}
/* harmony default export */ const _nativeKeysIn = (nativeKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeysIn.js




/** Used for built-in method references. */
var _baseKeysIn_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseKeysIn_hasOwnProperty = _baseKeysIn_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeysIn(object) {
  if (!lodash_es_isObject(object)) {
    return _nativeKeysIn(object);
  }
  var isProto = _isPrototype(object),
    result = [];
  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !_baseKeysIn_hasOwnProperty.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}
/* harmony default export */ const _baseKeysIn = (baseKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keysIn.js




/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */
function keysIn(object) {
  return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
/* harmony default export */ const lodash_es_keysIn = (keysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/assignIn.js




/**
 * This method is like `_.assign` except that it iterates over own and
 * inherited source properties.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @alias extend
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assign
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
 */
var assignIn = _createAssigner(function (object, source) {
  _copyObject(source, lodash_es_keysIn(source), object);
});
/* harmony default export */ const lodash_es_assignIn = (assignIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHas.js
/** Used for built-in method references. */
var _baseHas_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseHas_hasOwnProperty = _baseHas_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.has` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHas(object, key) {
  return object != null && _baseHas_hasOwnProperty.call(object, key);
}
/* harmony default export */ const _baseHas = (baseHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isSymbol.js
function isSymbol_typeof(obj) {
  "@babel/helpers - typeof";

  return isSymbol_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;
  }, isSymbol_typeof(obj);
}



/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return isSymbol_typeof(value) == 'symbol' || lodash_es_isObjectLike(value) && _baseGetTag(value) == symbolTag;
}
/* harmony default export */ const lodash_es_isSymbol = (isSymbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKey.js
function _isKey_typeof(obj) {
  "@babel/helpers - typeof";

  return _isKey_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;
  }, _isKey_typeof(obj);
}



/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function isKey(value, object) {
  if (lodash_es_isArray(value)) {
    return false;
  }
  var type = _isKey_typeof(value);
  if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || lodash_es_isSymbol(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
/* harmony default export */ const _isKey = (isKey);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeCreate.js


/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');
/* harmony default export */ const _nativeCreate = (nativeCreate);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashClear.js


/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  this.size = 0;
}
/* harmony default export */ const _hashClear = (hashClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashDelete.js
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}
/* harmony default export */ const _hashDelete = (hashDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashGet.js


/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var _hashGet_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _hashGet_hasOwnProperty = _hashGet_objectProto.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (_nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return _hashGet_hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/* harmony default export */ const _hashGet = (hashGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashHas.js


/** Used for built-in method references. */
var _hashHas_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _hashHas_hasOwnProperty = _hashHas_objectProto.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return _nativeCreate ? data[key] !== undefined : _hashHas_hasOwnProperty.call(data, key);
}
/* harmony default export */ const _hashHas = (hashHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashSet.js


/** Used to stand-in for `undefined` hash values. */
var _hashSet_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = _nativeCreate && value === undefined ? _hashSet_HASH_UNDEFINED : value;
  return this;
}
/* harmony default export */ const _hashSet = (hashSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Hash.js






/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
/* harmony default export */ const _Hash = (Hash);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheClear.js
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}
/* harmony default export */ const _listCacheClear = (listCacheClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assocIndexOf.js


/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (lodash_es_eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
/* harmony default export */ const _assocIndexOf = (assocIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheDelete.js


/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
    index = _assocIndexOf(data, key);
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}
/* harmony default export */ const _listCacheDelete = (listCacheDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheGet.js


/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
    index = _assocIndexOf(data, key);
  return index < 0 ? undefined : data[index][1];
}
/* harmony default export */ const _listCacheGet = (listCacheGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheHas.js


/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return _assocIndexOf(this.__data__, key) > -1;
}
/* harmony default export */ const _listCacheHas = (listCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheSet.js


/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
    index = _assocIndexOf(data, key);
  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
/* harmony default export */ const _listCacheSet = (listCacheSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_ListCache.js






/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
/* harmony default export */ const _ListCache = (ListCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Map.js



/* Built-in method references that are verified to be native. */
var _Map_Map = _getNative(_root, 'Map');
/* harmony default export */ const _Map = (_Map_Map);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheClear.js




/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new _Hash(),
    'map': new (_Map || _ListCache)(),
    'string': new _Hash()
  };
}
/* harmony default export */ const _mapCacheClear = (mapCacheClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKeyable.js
function _isKeyable_typeof(obj) {
  "@babel/helpers - typeof";

  return _isKeyable_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;
  }, _isKeyable_typeof(obj);
}
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = _isKeyable_typeof(value);
  return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
}
/* harmony default export */ const _isKeyable = (isKeyable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMapData.js


/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}
/* harmony default export */ const _getMapData = (getMapData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheDelete.js


/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = _getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}
/* harmony default export */ const _mapCacheDelete = (mapCacheDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheGet.js


/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return _getMapData(this, key).get(key);
}
/* harmony default export */ const _mapCacheGet = (mapCacheGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheHas.js


/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return _getMapData(this, key).has(key);
}
/* harmony default export */ const _mapCacheHas = (mapCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheSet.js


/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = _getMapData(this, key),
    size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}
/* harmony default export */ const _mapCacheSet = (mapCacheSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_MapCache.js






/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
/* harmony default export */ const _MapCache = (MapCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/memoize.js


/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize(func, resolver) {
  if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function memoized() {
    var args = arguments,
      key = resolver ? resolver.apply(this, args) : args[0],
      cache = memoized.cache;
    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize.Cache || _MapCache)();
  return memoized;
}

// Expose `MapCache`.
memoize.Cache = _MapCache;
/* harmony default export */ const lodash_es_memoize = (memoize);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_memoizeCapped.js


/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  var result = lodash_es_memoize(func, function (key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });
  var cache = result.cache;
  return result;
}
/* harmony default export */ const _memoizeCapped = (memoizeCapped);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stringToPath.js


/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath = _memoizeCapped(function (string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName, function (match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  });
  return result;
});
/* harmony default export */ const _stringToPath = (stringToPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayMap.js
/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length,
    result = Array(length);
  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}
/* harmony default export */ const _arrayMap = (arrayMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseToString.js





/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto = lodash_es_Symbol ? lodash_es_Symbol.prototype : undefined,
  symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (lodash_es_isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return _arrayMap(value, baseToString) + '';
  }
  if (lodash_es_isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = value + '';
  return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}
/* harmony default export */ const _baseToString = (baseToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toString.js


/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString_toString(value) {
  return value == null ? '' : _baseToString(value);
}
/* harmony default export */ const lodash_es_toString = (toString_toString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_castPath.js





/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function castPath(value, object) {
  if (lodash_es_isArray(value)) {
    return value;
  }
  return _isKey(value, object) ? [value] : _stringToPath(lodash_es_toString(value));
}
/* harmony default export */ const _castPath = (castPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_toKey.js


/** Used as references for various `Number` constants. */
var _toKey_INFINITY = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey(value) {
  if (typeof value == 'string' || lodash_es_isSymbol(value)) {
    return value;
  }
  var result = value + '';
  return result == '0' && 1 / value == -_toKey_INFINITY ? '-0' : result;
}
/* harmony default export */ const _toKey = (toKey);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hasPath.js







/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */
function hasPath(object, path, hasFunc) {
  path = _castPath(path, object);
  var index = -1,
    length = path.length,
    result = false;
  while (++index < length) {
    var key = _toKey(path[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && lodash_es_isLength(length) && _isIndex(key, length) && (lodash_es_isArray(object) || lodash_es_isArguments(object));
}
/* harmony default export */ const _hasPath = (hasPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/has.js



/**
 * Checks if `path` is a direct property of `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = { 'a': { 'b': 2 } };
 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.has(object, 'a');
 * // => true
 *
 * _.has(object, 'a.b');
 * // => true
 *
 * _.has(object, ['a', 'b']);
 * // => true
 *
 * _.has(other, 'a');
 * // => false
 */
function has(object, path) {
  return object != null && _hasPath(object, path, _baseHas);
}
/* harmony default export */ const lodash_es_has = (has);
;// CONCATENATED MODULE: ./node_modules/lodash-es/result.js




/**
 * This method is like `_.get` except that if the resolved value is a
 * function it's invoked with the `this` binding of its parent object and
 * its result is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to resolve.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
 *
 * _.result(object, 'a[0].b.c1');
 * // => 3
 *
 * _.result(object, 'a[0].b.c2');
 * // => 4
 *
 * _.result(object, 'a[0].b.c3', 'default');
 * // => 'default'
 *
 * _.result(object, 'a[0].b.c3', _.constant('default'));
 * // => 'default'
 */
function result(object, path, defaultValue) {
  path = _castPath(path, object);
  var index = -1,
    length = path.length;

  // Ensure the loop is entered when path is empty.
  if (!length) {
    length = 1;
    object = undefined;
  }
  while (++index < length) {
    var value = object == null ? undefined : object[_toKey(path[index])];
    if (value === undefined) {
      index = length;
      value = defaultValue;
    }
    object = lodash_es_isFunction(value) ? value.call(object) : value;
  }
  return object;
}
/* harmony default export */ const lodash_es_result = (result);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/helpers.js
function helpers_typeof(obj) {
  "@babel/helpers - typeof";

  return helpers_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;
  }, helpers_typeof(obj);
}
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 helpers_typeof(key) === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
  if (helpers_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (helpers_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
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 _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 && (helpers_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 _wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  _wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return _construct(Class, arguments, _getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return _setPrototypeOf(Wrapper, Class);
  };
  return _wrapNativeSuper(Class);
}
function _construct(Parent, args, Class) {
  if (_isNativeReflectConstruct()) {
    _construct = Reflect.construct.bind();
  } else {
    _construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) _setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return _construct.apply(null, arguments);
}
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 _isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return _setPrototypeOf(o, p);
}
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud






/**
 * Custom error for indicating timeouts
 * @namespace _converse
 */
var NotImplementedError = /*#__PURE__*/(/* unused pure expression or super */ null && (function (_Error) {
  _inherits(NotImplementedError, _Error);
  var _super = _createSuper(NotImplementedError);
  function NotImplementedError() {
    _classCallCheck(this, NotImplementedError);
    return _super.apply(this, arguments);
  }
  return _createClass(NotImplementedError);
}( /*#__PURE__*/_wrapNativeSuper(Error))));
function S4() {
  // Generate four random hex digits.
  return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
}
function guid() {
  // Generate a pseudo-GUID by concatenating random hexadecimal.
  return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}

// Helpers
// -------

// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
//
function inherits(protoProps, staticProps) {
  var parent = this;
  var child;

  // The constructor function for the new subclass is either defined by you
  // (the "constructor" property in your `extend` definition), or defaulted
  // by us to simply call the parent constructor.
  if (protoProps && lodash_es_has(protoProps, 'constructor')) {
    child = protoProps.constructor;
  } else {
    child = function child() {
      return parent.apply(this, arguments);
    };
  }

  // Add static properties to the constructor function, if supplied.
  lodash_es_assignIn(child, parent, staticProps);

  // Set the prototype chain to inherit from `parent`, without calling
  // `parent`'s constructor function and add the prototype properties.
  child.prototype = lodash_es_create(parent.prototype, protoProps);
  child.prototype.constructor = child;

  // Set a convenience property in case the parent's prototype is needed
  // later.
  child.__super__ = parent.prototype;
  return child;
}
function getResolveablePromise() {
  var wrapper = {
    isResolved: false,
    isPending: true,
    isRejected: false
  };
  var promise = new Promise(function (resolve, reject) {
    wrapper.resolve = resolve;
    wrapper.reject = reject;
  });
  Object.assign(promise, wrapper);
  promise.then(function (v) {
    promise.isResolved = true;
    promise.isPending = false;
    promise.isRejected = false;
    return v;
  }, function (e) {
    promise.isResolved = false;
    promise.isPending = false;
    promise.isRejected = true;
    throw e;
  });
  return promise;
}

// Throw an error when a URL is needed, and none is supplied.
function urlError() {
  throw new Error('A "url" property or function must be specified');
}

// Wrap an optional error callback with a fallback error event.
function wrapError(model, options) {
  var error = options.error;
  options.error = function (resp) {
    if (error) error.call(options.context, model, resp, options);
    model.trigger('error', model, resp, options);
  };
}

// Map from CRUD to HTTP for our default `sync` implementation.
var methodMap = {
  create: 'POST',
  update: 'PUT',
  patch: 'PATCH',
  delete: 'DELETE',
  read: 'GET'
};
function getSyncMethod(model) {
  var store = lodash_es_result(model, 'browserStorage') || lodash_es_result(model.collection, 'browserStorage');
  return store ? store.sync() : sync;
}

// sync
// ----

// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
function sync(method, model) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var type = methodMap[method];

  // Default JSON-request options.
  var params = {
    type: type,
    dataType: 'json'
  };

  // Ensure that we have a URL.
  if (!options.url) {
    params.url = lodash_es_result(model, 'url') || urlError();
  }

  // Ensure that we have the appropriate request data.
  if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
    params.contentType = 'application/json';
    params.data = JSON.stringify(options.attrs || model.toJSON(options));
  }

  // Don't process data on a non-GET request.
  if (params.type !== 'GET') {
    params.processData = false;
  }

  // Pass along `textStatus` and `errorThrown` from jQuery.
  var error = options.error;
  options.error = function (xhr, textStatus, errorThrown) {
    options.textStatus = textStatus;
    options.errorThrown = errorThrown;
    if (error) error.call(options.context, xhr, textStatus, errorThrown);
  };

  // Make the request, allowing the user to override any Ajax options.
  var xhr = options.xhr = ajax(lodash_es_assignIn(params, options));
  model.trigger('request', model, xhr, options);
  return xhr;
}
function ajax() {
  return fetch.apply(this, arguments);
}
;// CONCATENATED MODULE: ./node_modules/lodash-es/_DataView.js



/* Built-in method references that are verified to be native. */
var DataView = _getNative(_root, 'DataView');
/* harmony default export */ const _DataView = (DataView);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Promise.js



/* Built-in method references that are verified to be native. */
var _Promise_Promise = _getNative(_root, 'Promise');
/* harmony default export */ const _Promise = (_Promise_Promise);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Set.js



/* Built-in method references that are verified to be native. */
var _Set_Set = _getNative(_root, 'Set');
/* harmony default export */ const _Set = (_Set_Set);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_WeakMap.js



/* Built-in method references that are verified to be native. */
var _WeakMap_WeakMap = _getNative(_root, 'WeakMap');
/* harmony default export */ const _WeakMap = (_WeakMap_WeakMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getTag.js








/** `Object#toString` result references. */
var _getTag_mapTag = '[object Map]',
  _getTag_objectTag = '[object Object]',
  promiseTag = '[object Promise]',
  _getTag_setTag = '[object Set]',
  _getTag_weakMapTag = '[object WeakMap]';
var _getTag_dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = _toSource(_DataView),
  mapCtorString = _toSource(_Map),
  promiseCtorString = _toSource(_Promise),
  setCtorString = _toSource(_Set),
  weakMapCtorString = _toSource(_WeakMap);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = _baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != _getTag_dataViewTag || _Map && getTag(new _Map()) != _getTag_mapTag || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != _getTag_setTag || _WeakMap && getTag(new _WeakMap()) != _getTag_weakMapTag) {
  getTag = function getTag(value) {
    var result = _baseGetTag(value),
      Ctor = result == _getTag_objectTag ? value.constructor : undefined,
      ctorString = Ctor ? _toSource(Ctor) : '';
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return _getTag_dataViewTag;
        case mapCtorString:
          return _getTag_mapTag;
        case promiseCtorString:
          return promiseTag;
        case setCtorString:
          return _getTag_setTag;
        case weakMapCtorString:
          return _getTag_weakMapTag;
      }
    }
    return result;
  };
}
/* harmony default export */ const _getTag = (getTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isEmpty.js









/** `Object#toString` result references. */
var isEmpty_mapTag = '[object Map]',
  isEmpty_setTag = '[object Set]';

/** Used for built-in method references. */
var isEmpty_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var isEmpty_hasOwnProperty = isEmpty_objectProto.hasOwnProperty;

/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty(null);
 * // => true
 *
 * _.isEmpty(true);
 * // => true
 *
 * _.isEmpty(1);
 * // => true
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({ 'a': 1 });
 * // => false
 */
function isEmpty(value) {
  if (value == null) {
    return true;
  }
  if (lodash_es_isArrayLike(value) && (lodash_es_isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || lodash_es_isBuffer(value) || lodash_es_isTypedArray(value) || lodash_es_isArguments(value))) {
    return !value.length;
  }
  var tag = _getTag(value);
  if (tag == isEmpty_mapTag || tag == isEmpty_setTag) {
    return !value.size;
  }
  if (_isPrototype(value)) {
    return !_baseKeys(value).length;
  }
  for (var key in value) {
    if (isEmpty_hasOwnProperty.call(value, key)) {
      return false;
    }
  }
  return true;
}
/* harmony default export */ const lodash_es_isEmpty = (isEmpty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;

/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */
function trimmedEndIndex(string) {
  var index = string.length;
  while (index-- && reWhitespace.test(string.charAt(index))) {}
  return index;
}
/* harmony default export */ const _trimmedEndIndex = (trimmedEndIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTrim.js


/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;

/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */
function baseTrim(string) {
  return string ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
}
/* harmony default export */ const _baseTrim = (baseTrim);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toNumber.js




/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (lodash_es_isSymbol(value)) {
    return NAN;
  }
  if (lodash_es_isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = lodash_es_isObject(other) ? other + '' : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = _baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
/* harmony default export */ const lodash_es_toNumber = (toNumber);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toFinite.js


/** Used as references for various `Number` constants. */
var toFinite_INFINITY = 1 / 0,
  MAX_INTEGER = 1.7976931348623157e+308;

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = lodash_es_toNumber(value);
  if (value === toFinite_INFINITY || value === -toFinite_INFINITY) {
    var sign = value < 0 ? -1 : 1;
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}
/* harmony default export */ const lodash_es_toFinite = (toFinite);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toInteger.js


/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
function toInteger(value) {
  var result = lodash_es_toFinite(value),
    remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}
/* harmony default export */ const lodash_es_toInteger = (toInteger);
;// CONCATENATED MODULE: ./node_modules/lodash-es/before.js


/** Error message constants. */
var before_FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that invokes `func`, with the `this` binding and arguments
 * of the created function, while it's called less than `n` times. Subsequent
 * calls to the created function return the result of the last `func` invocation.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Function
 * @param {number} n The number of calls at which `func` is no longer invoked.
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * jQuery(element).on('click', _.before(5, addContactToList));
 * // => Allows adding up to 4 contacts to the list.
 */
function before(n, func) {
  var result;
  if (typeof func != 'function') {
    throw new TypeError(before_FUNC_ERROR_TEXT);
  }
  n = lodash_es_toInteger(n);
  return function () {
    if (--n > 0) {
      result = func.apply(this, arguments);
    }
    if (n <= 1) {
      func = undefined;
    }
    return result;
  };
}
/* harmony default export */ const lodash_es_before = (before);
;// CONCATENATED MODULE: ./node_modules/lodash-es/once.js


/**
 * Creates a function that is restricted to invoking `func` once. Repeat calls
 * to the function return the value of the first invocation. The `func` is
 * invoked with the `this` binding and arguments of the created function.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * var initialize = _.once(createApplication);
 * initialize();
 * initialize();
 * // => `createApplication` is invoked once
 */
function once(func) {
  return lodash_es_before(2, func);
}
/* harmony default export */ const lodash_es_once = (once);
;// CONCATENATED MODULE: ./node_modules/lodash-es/uniqueId.js


/** Used to generate unique IDs. */
var idCounter = 0;

/**
 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {string} [prefix=''] The value to prefix the ID with.
 * @returns {string} Returns the unique ID.
 * @example
 *
 * _.uniqueId('contact_');
 * // => 'contact_104'
 *
 * _.uniqueId();
 * // => '105'
 */
function uniqueId(prefix) {
  var id = ++idCounter;
  return lodash_es_toString(prefix) + id;
}
/* harmony default export */ const lodash_es_uniqueId = (uniqueId);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/events.js
function events_typeof(obj) {
  "@babel/helpers - typeof";

  return events_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;
  }, events_typeof(obj);
}
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.

// Events
// ------

// A module that can be mixed in to *any object* in order to provide it with
// a custom event channel. You may bind a callback to an event with `on` or
// remove with `off`; `trigger`-ing an event fires all callbacks in
// succession.
//
//     let object = {};
//     extend(object, Backbone.Events);
//     object.on('expand', function(){ alert('expanded'); });
//     object.trigger('expand');
//





var Events = {};

// Regular expression used to split event strings.
var eventSplitter = /\s+/;

// A private global variable to share between listeners and listenees.
var _listening;

// Iterates over the standard `event, callback` (as well as the fancy multiple
// space-separated events `"change blur", callback` and jQuery-style event
// maps `{event: callback}`).
var eventsApi = function eventsApi(iteratee, events, name, callback, opts) {
  var i = 0,
    names;
  if (name && events_typeof(name) === 'object') {
    // Handle event maps.
    if (callback !== undefined && 'context' in opts && opts.context === undefined) opts.context = callback;
    for (names = lodash_es_keys(name); i < names.length; i++) {
      events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
    }
  } else if (name && eventSplitter.test(name)) {
    // Handle space-separated event names by delegating them individually.
    for (names = name.split(eventSplitter); i < names.length; i++) {
      events = iteratee(events, names[i], callback, opts);
    }
  } else {
    // Finally, standard events.
    events = iteratee(events, name, callback, opts);
  }
  return events;
};

// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
Events.on = function (name, callback, context) {
  this._events = eventsApi(onApi, this._events || {}, name, callback, {
    context: context,
    ctx: this,
    listening: _listening
  });
  if (_listening) {
    var listeners = this._listeners || (this._listeners = {});
    listeners[_listening.id] = _listening;
    // Allow the listening to use a counter, instead of tracking
    // callbacks for library interop
    _listening.interop = false;
  }
  return this;
};

// Inversion-of-control versions of `on`. Tell *this* object to listen to
// an event in another object... keeping track of what it's listening to
// for easier unbinding later.
Events.listenTo = function (obj, name, callback) {
  if (!obj) return this;
  var id = obj._listenId || (obj._listenId = lodash_es_uniqueId('l'));
  var listeningTo = this._listeningTo || (this._listeningTo = {});
  var listening = _listening = listeningTo[id];

  // This object is not listening to any other events on `obj` yet.
  // Setup the necessary references to track the listening callbacks.
  if (!listening) {
    this._listenId || (this._listenId = lodash_es_uniqueId('l'));
    listening = _listening = listeningTo[id] = new Listening(this, obj);
  }

  // Bind callbacks on obj.
  var error = tryCatchOn(obj, name, callback, this);
  _listening = undefined;
  if (error) throw error;
  // If the target obj is not Backbone.Events, track events manually.
  if (listening.interop) listening.on(name, callback);
  return this;
};

// The reducing API that adds a callback to the `events` object.
var onApi = function onApi(events, name, callback, options) {
  if (callback) {
    var handlers = events[name] || (events[name] = []);
    var context = options.context,
      ctx = options.ctx,
      listening = options.listening;
    if (listening) listening.count++;
    handlers.push({
      callback: callback,
      context: context,
      ctx: context || ctx,
      listening: listening
    });
  }
  return events;
};

// An try-catch guarded #on function, to prevent poisoning the global
// `_listening` variable.
var tryCatchOn = function tryCatchOn(obj, name, callback, context) {
  try {
    obj.on(name, callback, context);
  } catch (e) {
    return e;
  }
};

// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
Events.off = function (name, callback, context) {
  if (!this._events) return this;
  this._events = eventsApi(offApi, this._events, name, callback, {
    context: context,
    listeners: this._listeners
  });
  return this;
};

// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
Events.stopListening = function (obj, name, callback) {
  var listeningTo = this._listeningTo;
  if (!listeningTo) return this;
  var ids = obj ? [obj._listenId] : lodash_es_keys(listeningTo);
  for (var i = 0; i < ids.length; i++) {
    var listening = listeningTo[ids[i]];

    // If listening doesn't exist, this object is not currently
    // listening to obj. Break out early.
    if (!listening) break;
    listening.obj.off(name, callback, this);
    if (listening.interop) listening.off(name, callback);
  }
  if (lodash_es_isEmpty(listeningTo)) this._listeningTo = undefined;
  return this;
};

// The reducing API that removes a callback from the `events` object.
var offApi = function offApi(events, name, callback, options) {
  if (!events) return;
  var context = options.context,
    listeners = options.listeners;
  var i = 0,
    names;

  // Delete all event listeners and "drop" events.
  if (!name && !context && !callback) {
    for (names = lodash_es_keys(listeners); i < names.length; i++) {
      listeners[names[i]].cleanup();
    }
    return;
  }
  names = name ? [name] : lodash_es_keys(events);
  for (; i < names.length; i++) {
    name = names[i];
    var handlers = events[name];

    // Bail out if there are no events stored.
    if (!handlers) {
      break;
    }

    // Find any remaining events.
    var remaining = [];
    for (var j = 0; j < handlers.length; j++) {
      var handler = handlers[j];
      if (callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context) {
        remaining.push(handler);
      } else {
        var listening = handler.listening;
        if (listening) listening.off(name, callback);
      }
    }

    // Replace events if there are any remaining.  Otherwise, clean up.
    if (remaining.length) {
      events[name] = remaining;
    } else {
      delete events[name];
    }
  }
  return events;
};

// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, its listener will be removed. If multiple events
// are passed in using the space-separated syntax, the handler will fire
// once for each event, not once for a combination of all events.
Events.once = function (name, callback, context) {
  // Map the event into a `{event: once}` object.
  var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
  if (typeof name === 'string' && (context === null || context === undefined)) callback = undefined;
  return this.on(events, callback, context);
};

// Inversion-of-control versions of `once`.
Events.listenToOnce = function (obj, name, callback) {
  // Map the event into a `{event: once}` object.
  var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
  return this.listenTo(obj, events);
};

// Reduces the event callbacks into a map of `{event: onceWrapper}`.
// `offer` unbinds the `onceWrapper` after it has been called.
var onceMap = function onceMap(map, name, callback, offer) {
  if (callback) {
    var _once = map[name] = lodash_es_once(function () {
      offer(name, _once);
      callback.apply(this, arguments);
    });
    _once._callback = callback;
  }
  return map;
};

// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
Events.trigger = function (name) {
  if (!this._events) return this;
  var length = Math.max(0, arguments.length - 1);
  var args = Array(length);
  for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
  eventsApi(triggerApi, this._events, name, undefined, args);
  return this;
};

// Handles triggering the appropriate event callbacks.
var triggerApi = function triggerApi(objEvents, name, callback, args) {
  if (objEvents) {
    var events = objEvents[name];
    var allEvents = objEvents.all;
    if (events && allEvents) allEvents = allEvents.slice();
    if (events) triggerEvents(events, args);
    if (allEvents) triggerEvents(allEvents, [name].concat(args));
  }
  return objEvents;
};

// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function triggerEvents(events, args) {
  var ev,
    i = -1;
  var l = events.length,
    a1 = args[0],
    a2 = args[1],
    a3 = args[2];
  switch (args.length) {
    case 0:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx);
      return;
    case 1:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);
      return;
    case 2:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);
      return;
    case 3:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
      return;
    default:
      while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
      return;
  }
};

// A listening class that tracks and cleans up memory bindings
// when all callbacks have been offed.
var Listening = function Listening(listener, obj) {
  this.id = listener._listenId;
  this.listener = listener;
  this.obj = obj;
  this.interop = true;
  this.count = 0;
  this._events = undefined;
};
Listening.prototype.on = Events.on;

// Offs a callback (or several).
// Uses an optimized counter if the listenee uses Backbone.Events.
// Otherwise, falls back to manual tracking to support events
// library interop.
Listening.prototype.off = function (name, callback) {
  var cleanup;
  if (this.interop) {
    this._events = eventsApi(offApi, this._events, name, callback, {
      context: undefined,
      listeners: undefined
    });
    cleanup = !this._events;
  } else {
    this.count--;
    cleanup = this.count === 0;
  }
  if (cleanup) this.cleanup();
};

// Cleans up memory bindings between the listener and the listenee.
Listening.prototype.cleanup = function () {
  delete this.listener._listeningTo[this.obj._listenId];
  if (!this.interop) delete this.obj._listeners[this.id];
};

// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackClear.js


/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new _ListCache();
  this.size = 0;
}
/* harmony default export */ const _stackClear = (stackClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackDelete.js
/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
    result = data['delete'](key);
  this.size = data.size;
  return result;
}
/* harmony default export */ const _stackDelete = (stackDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackGet.js
/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}
/* harmony default export */ const _stackGet = (stackGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackHas.js
/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}
/* harmony default export */ const _stackHas = (stackHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackSet.js




/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof _ListCache) {
    var pairs = data.__data__;
    if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new _MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}
/* harmony default export */ const _stackSet = (stackSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Stack.js







/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new _ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
/* harmony default export */ const _Stack = (Stack);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEach.js
/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}
/* harmony default export */ const _arrayEach = (arrayEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignIn.js



/**
 * The base implementation of `_.assignIn` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssignIn(object, source) {
  return object && _copyObject(source, lodash_es_keysIn(source), object);
}
/* harmony default export */ const _baseAssignIn = (baseAssignIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneBuffer.js
function _cloneBuffer_typeof(obj) {
  "@babel/helpers - typeof";

  return _cloneBuffer_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;
  }, _cloneBuffer_typeof(obj);
}


/** Detect free variable `exports`. */
var _cloneBuffer_freeExports = (typeof exports === "undefined" ? "undefined" : _cloneBuffer_typeof(exports)) == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var _cloneBuffer_freeModule = _cloneBuffer_freeExports && (typeof module === "undefined" ? "undefined" : _cloneBuffer_typeof(module)) == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var _cloneBuffer_moduleExports = _cloneBuffer_freeModule && _cloneBuffer_freeModule.exports === _cloneBuffer_freeExports;

/** Built-in value references. */
var _cloneBuffer_Buffer = _cloneBuffer_moduleExports ? _root.Buffer : undefined,
  allocUnsafe = _cloneBuffer_Buffer ? _cloneBuffer_Buffer.allocUnsafe : undefined;

/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */
function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }
  var length = buffer.length,
    result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  buffer.copy(result);
  return result;
}
/* harmony default export */ const _cloneBuffer = (cloneBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyArray.js
/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
    length = source.length;
  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}
/* harmony default export */ const _copyArray = (copyArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayFilter.js
/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length,
    resIndex = 0,
    result = [];
  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}
/* harmony default export */ const _arrayFilter = (arrayFilter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/stubArray.js
/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}
/* harmony default export */ const lodash_es_stubArray = (stubArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbols.js



/** Used for built-in method references. */
var _getSymbols_objectProto = Object.prototype;

/** Built-in value references. */
var _getSymbols_propertyIsEnumerable = _getSymbols_objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols ? lodash_es_stubArray : function (object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return _arrayFilter(nativeGetSymbols(object), function (symbol) {
    return _getSymbols_propertyIsEnumerable.call(object, symbol);
  });
};
/* harmony default export */ const _getSymbols = (getSymbols);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbols.js



/**
 * Copies own symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbols(source, object) {
  return _copyObject(source, _getSymbols(source), object);
}
/* harmony default export */ const _copySymbols = (copySymbols);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayPush.js
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
    length = values.length,
    offset = array.length;
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}
/* harmony default export */ const _arrayPush = (arrayPush);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getPrototype.js


/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
/* harmony default export */ const _getPrototype = (getPrototype);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbolsIn.js





/* Built-in method references for those with the same name as other `lodash` methods. */
var _getSymbolsIn_nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbolsIn = !_getSymbolsIn_nativeGetSymbols ? lodash_es_stubArray : function (object) {
  var result = [];
  while (object) {
    _arrayPush(result, _getSymbols(object));
    object = _getPrototype(object);
  }
  return result;
};
/* harmony default export */ const _getSymbolsIn = (getSymbolsIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbolsIn.js



/**
 * Copies own and inherited symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbolsIn(source, object) {
  return _copyObject(source, _getSymbolsIn(source), object);
}
/* harmony default export */ const _copySymbolsIn = (copySymbolsIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetAllKeys.js



/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return lodash_es_isArray(object) ? result : _arrayPush(result, symbolsFunc(object));
}
/* harmony default export */ const _baseGetAllKeys = (baseGetAllKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeys.js




/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return _baseGetAllKeys(object, lodash_es_keys, _getSymbols);
}
/* harmony default export */ const _getAllKeys = (getAllKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeysIn.js




/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeysIn(object) {
  return _baseGetAllKeys(object, lodash_es_keysIn, _getSymbolsIn);
}
/* harmony default export */ const _getAllKeysIn = (getAllKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneArray.js
/** Used for built-in method references. */
var _initCloneArray_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _initCloneArray_hasOwnProperty = _initCloneArray_objectProto.hasOwnProperty;

/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
function initCloneArray(array) {
  var length = array.length,
    result = new array.constructor(length);

  // Add properties assigned by `RegExp#exec`.
  if (length && typeof array[0] == 'string' && _initCloneArray_hasOwnProperty.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}
/* harmony default export */ const _initCloneArray = (initCloneArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Uint8Array.js


/** Built-in value references. */
var _Uint8Array_Uint8Array = _root.Uint8Array;
/* harmony default export */ const _Uint8Array = (_Uint8Array_Uint8Array);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneArrayBuffer.js


/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  return result;
}
/* harmony default export */ const _cloneArrayBuffer = (cloneArrayBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneDataView.js


/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */
function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/* harmony default export */ const _cloneDataView = (cloneDataView);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneRegExp.js
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;

/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */
function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}
/* harmony default export */ const _cloneRegExp = (cloneRegExp);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneSymbol.js


/** Used to convert symbols to primitives and strings. */
var _cloneSymbol_symbolProto = lodash_es_Symbol ? lodash_es_Symbol.prototype : undefined,
  symbolValueOf = _cloneSymbol_symbolProto ? _cloneSymbol_symbolProto.valueOf : undefined;

/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */
function cloneSymbol(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/* harmony default export */ const _cloneSymbol = (cloneSymbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneTypedArray.js


/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */
function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/* harmony default export */ const _cloneTypedArray = (cloneTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneByTag.js






/** `Object#toString` result references. */
var _initCloneByTag_boolTag = '[object Boolean]',
  _initCloneByTag_dateTag = '[object Date]',
  _initCloneByTag_mapTag = '[object Map]',
  _initCloneByTag_numberTag = '[object Number]',
  _initCloneByTag_regexpTag = '[object RegExp]',
  _initCloneByTag_setTag = '[object Set]',
  _initCloneByTag_stringTag = '[object String]',
  _initCloneByTag_symbolTag = '[object Symbol]';
var _initCloneByTag_arrayBufferTag = '[object ArrayBuffer]',
  _initCloneByTag_dataViewTag = '[object DataView]',
  _initCloneByTag_float32Tag = '[object Float32Array]',
  _initCloneByTag_float64Tag = '[object Float64Array]',
  _initCloneByTag_int8Tag = '[object Int8Array]',
  _initCloneByTag_int16Tag = '[object Int16Array]',
  _initCloneByTag_int32Tag = '[object Int32Array]',
  _initCloneByTag_uint8Tag = '[object Uint8Array]',
  _initCloneByTag_uint8ClampedTag = '[object Uint8ClampedArray]',
  _initCloneByTag_uint16Tag = '[object Uint16Array]',
  _initCloneByTag_uint32Tag = '[object Uint32Array]';

/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case _initCloneByTag_arrayBufferTag:
      return _cloneArrayBuffer(object);
    case _initCloneByTag_boolTag:
    case _initCloneByTag_dateTag:
      return new Ctor(+object);
    case _initCloneByTag_dataViewTag:
      return _cloneDataView(object, isDeep);
    case _initCloneByTag_float32Tag:
    case _initCloneByTag_float64Tag:
    case _initCloneByTag_int8Tag:
    case _initCloneByTag_int16Tag:
    case _initCloneByTag_int32Tag:
    case _initCloneByTag_uint8Tag:
    case _initCloneByTag_uint8ClampedTag:
    case _initCloneByTag_uint16Tag:
    case _initCloneByTag_uint32Tag:
      return _cloneTypedArray(object, isDeep);
    case _initCloneByTag_mapTag:
      return new Ctor();
    case _initCloneByTag_numberTag:
    case _initCloneByTag_stringTag:
      return new Ctor(object);
    case _initCloneByTag_regexpTag:
      return _cloneRegExp(object);
    case _initCloneByTag_setTag:
      return new Ctor();
    case _initCloneByTag_symbolTag:
      return _cloneSymbol(object);
  }
}
/* harmony default export */ const _initCloneByTag = (initCloneByTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneObject.js




/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneObject(object) {
  return typeof object.constructor == 'function' && !_isPrototype(object) ? _baseCreate(_getPrototype(object)) : {};
}
/* harmony default export */ const _initCloneObject = (initCloneObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMap.js



/** `Object#toString` result references. */
var _baseIsMap_mapTag = '[object Map]';

/**
 * The base implementation of `_.isMap` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 */
function baseIsMap(value) {
  return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsMap_mapTag;
}
/* harmony default export */ const _baseIsMap = (baseIsMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isMap.js




/* Node.js helper references. */
var nodeIsMap = _nodeUtil && _nodeUtil.isMap;

/**
 * Checks if `value` is classified as a `Map` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 * @example
 *
 * _.isMap(new Map);
 * // => true
 *
 * _.isMap(new WeakMap);
 * // => false
 */
var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
/* harmony default export */ const lodash_es_isMap = (isMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsSet.js



/** `Object#toString` result references. */
var _baseIsSet_setTag = '[object Set]';

/**
 * The base implementation of `_.isSet` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 */
function baseIsSet(value) {
  return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsSet_setTag;
}
/* harmony default export */ const _baseIsSet = (baseIsSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isSet.js




/* Node.js helper references. */
var nodeIsSet = _nodeUtil && _nodeUtil.isSet;

/**
 * Checks if `value` is classified as a `Set` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 * @example
 *
 * _.isSet(new Set);
 * // => true
 *
 * _.isSet(new WeakSet);
 * // => false
 */
var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
/* harmony default export */ const lodash_es_isSet = (isSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseClone.js























/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
  CLONE_FLAT_FLAG = 2,
  CLONE_SYMBOLS_FLAG = 4;

/** `Object#toString` result references. */
var _baseClone_argsTag = '[object Arguments]',
  _baseClone_arrayTag = '[object Array]',
  _baseClone_boolTag = '[object Boolean]',
  _baseClone_dateTag = '[object Date]',
  _baseClone_errorTag = '[object Error]',
  _baseClone_funcTag = '[object Function]',
  _baseClone_genTag = '[object GeneratorFunction]',
  _baseClone_mapTag = '[object Map]',
  _baseClone_numberTag = '[object Number]',
  _baseClone_objectTag = '[object Object]',
  _baseClone_regexpTag = '[object RegExp]',
  _baseClone_setTag = '[object Set]',
  _baseClone_stringTag = '[object String]',
  _baseClone_symbolTag = '[object Symbol]',
  _baseClone_weakMapTag = '[object WeakMap]';
var _baseClone_arrayBufferTag = '[object ArrayBuffer]',
  _baseClone_dataViewTag = '[object DataView]',
  _baseClone_float32Tag = '[object Float32Array]',
  _baseClone_float64Tag = '[object Float64Array]',
  _baseClone_int8Tag = '[object Int8Array]',
  _baseClone_int16Tag = '[object Int16Array]',
  _baseClone_int32Tag = '[object Int32Array]',
  _baseClone_uint8Tag = '[object Uint8Array]',
  _baseClone_uint8ClampedTag = '[object Uint8ClampedArray]',
  _baseClone_uint16Tag = '[object Uint16Array]',
  _baseClone_uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[_baseClone_argsTag] = cloneableTags[_baseClone_arrayTag] = cloneableTags[_baseClone_arrayBufferTag] = cloneableTags[_baseClone_dataViewTag] = cloneableTags[_baseClone_boolTag] = cloneableTags[_baseClone_dateTag] = cloneableTags[_baseClone_float32Tag] = cloneableTags[_baseClone_float64Tag] = cloneableTags[_baseClone_int8Tag] = cloneableTags[_baseClone_int16Tag] = cloneableTags[_baseClone_int32Tag] = cloneableTags[_baseClone_mapTag] = cloneableTags[_baseClone_numberTag] = cloneableTags[_baseClone_objectTag] = cloneableTags[_baseClone_regexpTag] = cloneableTags[_baseClone_setTag] = cloneableTags[_baseClone_stringTag] = cloneableTags[_baseClone_symbolTag] = cloneableTags[_baseClone_uint8Tag] = cloneableTags[_baseClone_uint8ClampedTag] = cloneableTags[_baseClone_uint16Tag] = cloneableTags[_baseClone_uint32Tag] = true;
cloneableTags[_baseClone_errorTag] = cloneableTags[_baseClone_funcTag] = cloneableTags[_baseClone_weakMapTag] = false;

/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
function baseClone(value, bitmask, customizer, key, object, stack) {
  var result,
    isDeep = bitmask & CLONE_DEEP_FLAG,
    isFlat = bitmask & CLONE_FLAT_FLAG,
    isFull = bitmask & CLONE_SYMBOLS_FLAG;
  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== undefined) {
    return result;
  }
  if (!lodash_es_isObject(value)) {
    return value;
  }
  var isArr = lodash_es_isArray(value);
  if (isArr) {
    result = _initCloneArray(value);
    if (!isDeep) {
      return _copyArray(value, result);
    }
  } else {
    var tag = _getTag(value),
      isFunc = tag == _baseClone_funcTag || tag == _baseClone_genTag;
    if (lodash_es_isBuffer(value)) {
      return _cloneBuffer(value, isDeep);
    }
    if (tag == _baseClone_objectTag || tag == _baseClone_argsTag || isFunc && !object) {
      result = isFlat || isFunc ? {} : _initCloneObject(value);
      if (!isDeep) {
        return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = _initCloneByTag(value, tag, isDeep);
    }
  }
  // Check for circular references and return its corresponding clone.
  stack || (stack = new _Stack());
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);
  if (lodash_es_isSet(value)) {
    value.forEach(function (subValue) {
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (lodash_es_isMap(value)) {
    value.forEach(function (subValue, key) {
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
    });
  }
  var keysFunc = isFull ? isFlat ? _getAllKeysIn : _getAllKeys : isFlat ? lodash_es_keysIn : lodash_es_keys;
  var props = isArr ? undefined : keysFunc(value);
  _arrayEach(props || value, function (subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    }
    // Recursively populate clone (susceptible to call stack limits).
    _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  });
  return result;
}
/* harmony default export */ const _baseClone = (baseClone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/clone.js


/** Used to compose bitmasks for cloning. */
var clone_CLONE_SYMBOLS_FLAG = 4;

/**
 * Creates a shallow clone of `value`.
 *
 * **Note:** This method is loosely based on the
 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
 * and supports cloning arrays, array buffers, booleans, date objects, maps,
 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
 * arrays. The own enumerable properties of `arguments` objects are cloned
 * as plain objects. An empty object is returned for uncloneable values such
 * as error objects, functions, DOM nodes, and WeakMaps.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to clone.
 * @returns {*} Returns the cloned value.
 * @see _.cloneDeep
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var shallow = _.clone(objects);
 * console.log(shallow[0] === objects[0]);
 * // => true
 */
function clone(value) {
  return _baseClone(value, clone_CLONE_SYMBOLS_FLAG);
}
/* harmony default export */ const lodash_es_clone = (clone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/defaults.js





/** Used for built-in method references. */
var defaults_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var defaults_hasOwnProperty = defaults_objectProto.hasOwnProperty;

/**
 * Assigns own and inherited enumerable string keyed properties of source
 * objects to the destination object for all destination properties that
 * resolve to `undefined`. Source objects are applied from left to right.
 * Once a property is set, additional values of the same property are ignored.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.defaultsDeep
 * @example
 *
 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
 * // => { 'a': 1, 'b': 2 }
 */
var defaults = _baseRest(function (object, sources) {
  object = Object(object);
  var index = -1;
  var length = sources.length;
  var guard = length > 2 ? sources[2] : undefined;
  if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
    length = 1;
  }
  while (++index < length) {
    var source = sources[index];
    var props = lodash_es_keysIn(source);
    var propsIndex = -1;
    var propsLength = props.length;
    while (++propsIndex < propsLength) {
      var key = props[propsIndex];
      var value = object[key];
      if (value === undefined || lodash_es_eq(value, defaults_objectProto[key]) && !defaults_hasOwnProperty.call(object, key)) {
        object[key] = source[key];
      }
    }
  }
  return object;
});
/* harmony default export */ const lodash_es_defaults = (defaults);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDelay.js
/** Error message constants. */
var _baseDelay_FUNC_ERROR_TEXT = 'Expected a function';

/**
 * The base implementation of `_.delay` and `_.defer` which accepts `args`
 * to provide to `func`.
 *
 * @private
 * @param {Function} func The function to delay.
 * @param {number} wait The number of milliseconds to delay invocation.
 * @param {Array} args The arguments to provide to `func`.
 * @returns {number|Object} Returns the timer id or timeout object.
 */
function baseDelay(func, wait, args) {
  if (typeof func != 'function') {
    throw new TypeError(_baseDelay_FUNC_ERROR_TEXT);
  }
  return setTimeout(function () {
    func.apply(undefined, args);
  }, wait);
}
/* harmony default export */ const _baseDelay = (baseDelay);
;// CONCATENATED MODULE: ./node_modules/lodash-es/defer.js



/**
 * Defers invoking the `func` until the current call stack has cleared. Any
 * additional arguments are provided to `func` when it's invoked.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to defer.
 * @param {...*} [args] The arguments to invoke `func` with.
 * @returns {number} Returns the timer id.
 * @example
 *
 * _.defer(function(text) {
 *   console.log(text);
 * }, 'deferred');
 * // => Logs 'deferred' after one millisecond.
 */
var defer = _baseRest(function (func, args) {
  return _baseDelay(func, 1, args);
});
/* harmony default export */ const lodash_es_defer = (defer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyOf.js
/**
 * The base implementation of `_.propertyOf` without support for deep paths.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyOf(object) {
  return function (key) {
    return object == null ? undefined : object[key];
  };
}
/* harmony default export */ const _basePropertyOf = (basePropertyOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_escapeHtmlChar.js


/** Used to map characters to HTML entities. */
var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
};

/**
 * Used by `_.escape` to convert characters to HTML entities.
 *
 * @private
 * @param {string} chr The matched character to escape.
 * @returns {string} Returns the escaped character.
 */
var escapeHtmlChar = _basePropertyOf(htmlEscapes);
/* harmony default export */ const _escapeHtmlChar = (escapeHtmlChar);
;// CONCATENATED MODULE: ./node_modules/lodash-es/escape.js



/** Used to match HTML entities and HTML characters. */
var reUnescapedHtml = /[&<>"']/g,
  reHasUnescapedHtml = RegExp(reUnescapedHtml.source);

/**
 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
 * corresponding HTML entities.
 *
 * **Note:** No other characters are escaped. To escape additional
 * characters use a third-party library like [_he_](https://mths.be/he).
 *
 * Though the ">" character is escaped for symmetry, characters like
 * ">" and "/" don't need escaping in HTML and have no special meaning
 * unless they're part of a tag or unquoted attribute value. See
 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
 * (under "semi-related fun fact") for more details.
 *
 * When working with HTML you should always
 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
 * XSS vectors.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category String
 * @param {string} [string=''] The string to escape.
 * @returns {string} Returns the escaped string.
 * @example
 *
 * _.escape('fred, barney, & pebbles');
 * // => 'fred, barney, &amp; pebbles'
 */
function escape_escape(string) {
  string = lodash_es_toString(string);
  return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, _escapeHtmlChar) : string;
}
/* harmony default export */ const lodash_es_escape = (escape_escape);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseFor.js
/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseFor(fromRight) {
  return function (object, iteratee, keysFunc) {
    var index = -1,
      iterable = Object(object),
      props = keysFunc(object),
      length = props.length;
    while (length--) {
      var key = props[fromRight ? length : ++index];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}
/* harmony default export */ const _createBaseFor = (createBaseFor);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFor.js


/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */
var baseFor = _createBaseFor();
/* harmony default export */ const _baseFor = (baseFor);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseForOwn.js



/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */
function baseForOwn(object, iteratee) {
  return object && _baseFor(object, iteratee, lodash_es_keys);
}
/* harmony default export */ const _baseForOwn = (baseForOwn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInverter.js


/**
 * The base implementation of `_.invert` and `_.invertBy` which inverts
 * `object` with values transformed by `iteratee` and set by `setter`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform values.
 * @param {Object} accumulator The initial inverted object.
 * @returns {Function} Returns `accumulator`.
 */
function baseInverter(object, setter, iteratee, accumulator) {
  _baseForOwn(object, function (value, key, object) {
    setter(accumulator, iteratee(value), key, object);
  });
  return accumulator;
}
/* harmony default export */ const _baseInverter = (baseInverter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createInverter.js


/**
 * Creates a function like `_.invertBy`.
 *
 * @private
 * @param {Function} setter The function to set accumulator values.
 * @param {Function} toIteratee The function to resolve iteratees.
 * @returns {Function} Returns the new inverter function.
 */
function createInverter(setter, toIteratee) {
  return function (object, iteratee) {
    return _baseInverter(object, setter, toIteratee(iteratee), {});
  };
}
/* harmony default export */ const _createInverter = (createInverter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/invert.js




/** Used for built-in method references. */
var invert_objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var invert_nativeObjectToString = invert_objectProto.toString;

/**
 * Creates an object composed of the inverted keys and values of `object`.
 * If `object` contains duplicate values, subsequent values overwrite
 * property assignments of previous values.
 *
 * @static
 * @memberOf _
 * @since 0.7.0
 * @category Object
 * @param {Object} object The object to invert.
 * @returns {Object} Returns the new inverted object.
 * @example
 *
 * var object = { 'a': 1, 'b': 2, 'c': 1 };
 *
 * _.invert(object);
 * // => { '1': 'c', '2': 'b' }
 */
var invert = _createInverter(function (result, value, key) {
  if (value != null && typeof value.toString != 'function') {
    value = invert_nativeObjectToString.call(value);
  }
  result[value] = key;
}, lodash_es_constant(lodash_es_identity));
/* harmony default export */ const lodash_es_invert = (invert);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var _setCacheAdd_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, _setCacheAdd_HASH_UNDEFINED);
  return this;
}
/* harmony default export */ const _setCacheAdd = (setCacheAdd);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheHas.js
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}
/* harmony default export */ const _setCacheHas = (setCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_SetCache.js




/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
    length = values == null ? 0 : values.length;
  this.__data__ = new _MapCache();
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
/* harmony default export */ const _SetCache = (SetCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySome.js
/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}
/* harmony default export */ const _arraySome = (arraySome);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cacheHas.js
/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}
/* harmony default export */ const _cacheHas = (cacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalArrays.js




/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
  COMPARE_UNORDERED_FLAG = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
    arrLength = array.length,
    othLength = other.length;
  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Check that cyclic values are equal.
  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }
  var index = -1,
    result = true,
    seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
      othValue = other[index];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!_arraySome(other, function (othValue, othIndex) {
        if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}
/* harmony default export */ const _equalArrays = (equalArrays);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapToArray.js
/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
    result = Array(map.size);
  map.forEach(function (value, key) {
    result[++index] = [key, value];
  });
  return result;
}
/* harmony default export */ const _mapToArray = (mapToArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToArray.js
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
    result = Array(set.size);
  set.forEach(function (value) {
    result[++index] = value;
  });
  return result;
}
/* harmony default export */ const _setToArray = (setToArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalByTag.js







/** Used to compose bitmasks for value comparisons. */
var _equalByTag_COMPARE_PARTIAL_FLAG = 1,
  _equalByTag_COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var _equalByTag_boolTag = '[object Boolean]',
  _equalByTag_dateTag = '[object Date]',
  _equalByTag_errorTag = '[object Error]',
  _equalByTag_mapTag = '[object Map]',
  _equalByTag_numberTag = '[object Number]',
  _equalByTag_regexpTag = '[object RegExp]',
  _equalByTag_setTag = '[object Set]',
  _equalByTag_stringTag = '[object String]',
  _equalByTag_symbolTag = '[object Symbol]';
var _equalByTag_arrayBufferTag = '[object ArrayBuffer]',
  _equalByTag_dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var _equalByTag_symbolProto = lodash_es_Symbol ? lodash_es_Symbol.prototype : undefined,
  _equalByTag_symbolValueOf = _equalByTag_symbolProto ? _equalByTag_symbolProto.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case _equalByTag_dataViewTag:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;
    case _equalByTag_arrayBufferTag:
      if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
        return false;
      }
      return true;
    case _equalByTag_boolTag:
    case _equalByTag_dateTag:
    case _equalByTag_numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return lodash_es_eq(+object, +other);
    case _equalByTag_errorTag:
      return object.name == other.name && object.message == other.message;
    case _equalByTag_regexpTag:
    case _equalByTag_stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == other + '';
    case _equalByTag_mapTag:
      var convert = _mapToArray;
    case _equalByTag_setTag:
      var isPartial = bitmask & _equalByTag_COMPARE_PARTIAL_FLAG;
      convert || (convert = _setToArray);
      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= _equalByTag_COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;
    case _equalByTag_symbolTag:
      if (_equalByTag_symbolValueOf) {
        return _equalByTag_symbolValueOf.call(object) == _equalByTag_symbolValueOf.call(other);
      }
  }
  return false;
}
/* harmony default export */ const _equalByTag = (equalByTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalObjects.js


/** Used to compose bitmasks for value comparisons. */
var _equalObjects_COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var _equalObjects_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _equalObjects_hasOwnProperty = _equalObjects_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & _equalObjects_COMPARE_PARTIAL_FLAG,
    objProps = _getAllKeys(object),
    objLength = objProps.length,
    othProps = _getAllKeys(other),
    othLength = othProps.length;
  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : _equalObjects_hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Check that cyclic values are equal.
  var objStacked = stack.get(object);
  var othStacked = stack.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);
  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
      othValue = other[key];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
      othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}
/* harmony default export */ const _equalObjects = (equalObjects);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqualDeep.js









/** Used to compose bitmasks for value comparisons. */
var _baseIsEqualDeep_COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var _baseIsEqualDeep_argsTag = '[object Arguments]',
  _baseIsEqualDeep_arrayTag = '[object Array]',
  _baseIsEqualDeep_objectTag = '[object Object]';

/** Used for built-in method references. */
var _baseIsEqualDeep_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseIsEqualDeep_hasOwnProperty = _baseIsEqualDeep_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = lodash_es_isArray(object),
    othIsArr = lodash_es_isArray(other),
    objTag = objIsArr ? _baseIsEqualDeep_arrayTag : _getTag(object),
    othTag = othIsArr ? _baseIsEqualDeep_arrayTag : _getTag(other);
  objTag = objTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : objTag;
  othTag = othTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : othTag;
  var objIsObj = objTag == _baseIsEqualDeep_objectTag,
    othIsObj = othTag == _baseIsEqualDeep_objectTag,
    isSameTag = objTag == othTag;
  if (isSameTag && lodash_es_isBuffer(object)) {
    if (!lodash_es_isBuffer(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new _Stack());
    return objIsArr || lodash_es_isTypedArray(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & _baseIsEqualDeep_COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && _baseIsEqualDeep_hasOwnProperty.call(object, '__wrapped__'),
      othIsWrapped = othIsObj && _baseIsEqualDeep_hasOwnProperty.call(other, '__wrapped__');
    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
        othUnwrapped = othIsWrapped ? other.value() : other;
      stack || (stack = new _Stack());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new _Stack());
  return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/* harmony default export */ const _baseIsEqualDeep = (baseIsEqualDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqual.js



/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || !lodash_es_isObjectLike(value) && !lodash_es_isObjectLike(other)) {
    return value !== value && other !== other;
  }
  return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/* harmony default export */ const _baseIsEqual = (baseIsEqual);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isEqual.js


/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent.
 *
 * **Note:** This method supports comparing arrays, array buffers, booleans,
 * date objects, error objects, maps, numbers, `Object` objects, regexes,
 * sets, strings, symbols, and typed arrays. `Object` objects are compared
 * by their own, not inherited, enumerable properties. Functions and DOM
 * nodes are compared by strict equality, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.isEqual(object, other);
 * // => true
 *
 * object === other;
 * // => false
 */
function isEqual(value, other) {
  return _baseIsEqual(value, other);
}
/* harmony default export */ const lodash_es_isEqual = (isEqual);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMatch.js



/** Used to compose bitmasks for value comparisons. */
var _baseIsMatch_COMPARE_PARTIAL_FLAG = 1,
  _baseIsMatch_COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */
function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
    length = index,
    noCustomizer = !customizer;
  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0],
      objValue = object[key],
      srcValue = data[1];
    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new _Stack();
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === undefined ? _baseIsEqual(srcValue, objValue, _baseIsMatch_COMPARE_PARTIAL_FLAG | _baseIsMatch_COMPARE_UNORDERED_FLAG, customizer, stack) : result)) {
        return false;
      }
    }
  }
  return true;
}
/* harmony default export */ const _baseIsMatch = (baseIsMatch);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isStrictComparable.js


/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */
function isStrictComparable(value) {
  return value === value && !lodash_es_isObject(value);
}
/* harmony default export */ const _isStrictComparable = (isStrictComparable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMatchData.js



/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */
function getMatchData(object) {
  var result = lodash_es_keys(object),
    length = result.length;
  while (length--) {
    var key = result[length],
      value = object[key];
    result[length] = [key, value, _isStrictComparable(value)];
  }
  return result;
}
/* harmony default export */ const _getMatchData = (getMatchData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_matchesStrictComparable.js
/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function (object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  };
}
/* harmony default export */ const _matchesStrictComparable = (matchesStrictComparable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatches.js




/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatches(source) {
  var matchData = _getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }
  return function (object) {
    return object === source || _baseIsMatch(object, source, matchData);
  };
}
/* harmony default export */ const _baseMatches = (baseMatches);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGet.js



/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function baseGet(object, path) {
  path = _castPath(path, object);
  var index = 0,
    length = path.length;
  while (object != null && index < length) {
    object = object[_toKey(path[index++])];
  }
  return index && index == length ? object : undefined;
}
/* harmony default export */ const _baseGet = (baseGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/get.js


/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get(object, path, defaultValue) {
  var result = object == null ? undefined : _baseGet(object, path);
  return result === undefined ? defaultValue : result;
}
/* harmony default export */ const lodash_es_get = (get);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHasIn.js
/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}
/* harmony default export */ const _baseHasIn = (baseHasIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/hasIn.js



/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */
function hasIn(object, path) {
  return object != null && _hasPath(object, path, _baseHasIn);
}
/* harmony default export */ const lodash_es_hasIn = (hasIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatchesProperty.js








/** Used to compose bitmasks for value comparisons. */
var _baseMatchesProperty_COMPARE_PARTIAL_FLAG = 1,
  _baseMatchesProperty_COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatchesProperty(path, srcValue) {
  if (_isKey(path) && _isStrictComparable(srcValue)) {
    return _matchesStrictComparable(_toKey(path), srcValue);
  }
  return function (object) {
    var objValue = lodash_es_get(object, path);
    return objValue === undefined && objValue === srcValue ? lodash_es_hasIn(object, path) : _baseIsEqual(srcValue, objValue, _baseMatchesProperty_COMPARE_PARTIAL_FLAG | _baseMatchesProperty_COMPARE_UNORDERED_FLAG);
  };
}
/* harmony default export */ const _baseMatchesProperty = (baseMatchesProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseProperty.js
/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function (object) {
    return object == null ? undefined : object[key];
  };
}
/* harmony default export */ const _baseProperty = (baseProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyDeep.js


/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyDeep(path) {
  return function (object) {
    return _baseGet(object, path);
  };
}
/* harmony default export */ const _basePropertyDeep = (basePropertyDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/property.js





/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */
function property(path) {
  return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}
/* harmony default export */ const lodash_es_property = (property);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIteratee.js
function _baseIteratee_typeof(obj) {
  "@babel/helpers - typeof";

  return _baseIteratee_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;
  }, _baseIteratee_typeof(obj);
}






/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */
function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }
  if (value == null) {
    return lodash_es_identity;
  }
  if (_baseIteratee_typeof(value) == 'object') {
    return lodash_es_isArray(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
  }
  return lodash_es_property(value);
}
/* harmony default export */ const _baseIteratee = (baseIteratee);
;// CONCATENATED MODULE: ./node_modules/lodash-es/iteratee.js



/** Used to compose bitmasks for cloning. */
var iteratee_CLONE_DEEP_FLAG = 1;

/**
 * Creates a function that invokes `func` with the arguments of the created
 * function. If `func` is a property name, the created function returns the
 * property value for a given element. If `func` is an array or object, the
 * created function returns `true` for elements that contain the equivalent
 * source properties, otherwise it returns `false`.
 *
 * @static
 * @since 4.0.0
 * @memberOf _
 * @category Util
 * @param {*} [func=_.identity] The value to convert to a callback.
 * @returns {Function} Returns the callback.
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': true },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.filter(users, _.iteratee(['user', 'fred']));
 * // => [{ 'user': 'fred', 'age': 40 }]
 *
 * // The `_.property` iteratee shorthand.
 * _.map(users, _.iteratee('user'));
 * // => ['barney', 'fred']
 *
 * // Create custom iteratee shorthands.
 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
 *   return !_.isRegExp(func) ? iteratee(func) : function(string) {
 *     return func.test(string);
 *   };
 * });
 *
 * _.filter(['abc', 'def'], /ef/);
 * // => ['def']
 */
function iteratee(func) {
  return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, iteratee_CLONE_DEEP_FLAG));
}
/* harmony default export */ const lodash_es_iteratee = (iteratee);
;// CONCATENATED MODULE: ./node_modules/lodash-es/last.js
/**
 * Gets the last element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @returns {*} Returns the last element of `array`.
 * @example
 *
 * _.last([1, 2, 3]);
 * // => 3
 */
function last(array) {
  var length = array == null ? 0 : array.length;
  return length ? array[length - 1] : undefined;
}
/* harmony default export */ const lodash_es_last = (last);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSlice.js
/**
 * The base implementation of `_.slice` without an iteratee call guard.
 *
 * @private
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function baseSlice(array, start, end) {
  var index = -1,
    length = array.length;
  if (start < 0) {
    start = -start > length ? 0 : length + start;
  }
  end = end > length ? length : end;
  if (end < 0) {
    end += length;
  }
  length = start > end ? 0 : end - start >>> 0;
  start >>>= 0;
  var result = Array(length);
  while (++index < length) {
    result[index] = array[index + start];
  }
  return result;
}
/* harmony default export */ const _baseSlice = (baseSlice);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_parent.js



/**
 * Gets the parent value at `path` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array} path The path to get the parent value of.
 * @returns {*} Returns the parent value.
 */
function _parent_parent(object, path) {
  return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
}
/* harmony default export */ const _parent = (_parent_parent);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnset.js





/**
 * The base implementation of `_.unset`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The property path to unset.
 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
 */
function baseUnset(object, path) {
  path = _castPath(path, object);
  object = _parent(object, path);
  return object == null || delete object[_toKey(lodash_es_last(path))];
}
/* harmony default export */ const _baseUnset = (baseUnset);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isPlainObject.js




/** `Object#toString` result references. */
var isPlainObject_objectTag = '[object Object]';

/** Used for built-in method references. */
var isPlainObject_funcProto = Function.prototype,
  isPlainObject_objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var isPlainObject_funcToString = isPlainObject_funcProto.toString;

/** Used to check objects for own properties. */
var isPlainObject_hasOwnProperty = isPlainObject_objectProto.hasOwnProperty;

/** Used to infer the `Object` constructor. */
var objectCtorString = isPlainObject_funcToString.call(Object);

/**
 * Checks if `value` is a plain object, that is, an object created by the
 * `Object` constructor or one with a `[[Prototype]]` of `null`.
 *
 * @static
 * @memberOf _
 * @since 0.8.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * _.isPlainObject(new Foo);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 *
 * _.isPlainObject(Object.create(null));
 * // => true
 */
function isPlainObject(value) {
  if (!lodash_es_isObjectLike(value) || _baseGetTag(value) != isPlainObject_objectTag) {
    return false;
  }
  var proto = _getPrototype(value);
  if (proto === null) {
    return true;
  }
  var Ctor = isPlainObject_hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  return typeof Ctor == 'function' && Ctor instanceof Ctor && isPlainObject_funcToString.call(Ctor) == objectCtorString;
}
/* harmony default export */ const lodash_es_isPlainObject = (isPlainObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_customOmitClone.js


/**
 * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
 * objects.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {string} key The key of the property to inspect.
 * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
 */
function customOmitClone(value) {
  return lodash_es_isPlainObject(value) ? undefined : value;
}
/* harmony default export */ const _customOmitClone = (customOmitClone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isFlattenable.js




/** Built-in value references. */
var spreadableSymbol = lodash_es_Symbol ? lodash_es_Symbol.isConcatSpreadable : undefined;

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return lodash_es_isArray(value) || lodash_es_isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
/* harmony default export */ const _isFlattenable = (isFlattenable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFlatten.js



/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
    length = array.length;
  predicate || (predicate = _isFlattenable);
  result || (result = []);
  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        _arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}
/* harmony default export */ const _baseFlatten = (baseFlatten);
;// CONCATENATED MODULE: ./node_modules/lodash-es/flatten.js


/**
 * Flattens `array` a single level deep.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flatten([1, [2, [3, [4]], 5]]);
 * // => [1, 2, [3, [4]], 5]
 */
function flatten(array) {
  var length = array == null ? 0 : array.length;
  return length ? _baseFlatten(array, 1) : [];
}
/* harmony default export */ const lodash_es_flatten = (flatten);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_flatRest.js




/**
 * A specialized version of `baseRest` which flattens the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @returns {Function} Returns the new function.
 */
function flatRest(func) {
  return _setToString(_overRest(func, undefined, lodash_es_flatten), func + '');
}
/* harmony default export */ const _flatRest = (flatRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/omit.js









/** Used to compose bitmasks for cloning. */
var omit_CLONE_DEEP_FLAG = 1,
  omit_CLONE_FLAT_FLAG = 2,
  omit_CLONE_SYMBOLS_FLAG = 4;

/**
 * The opposite of `_.pick`; this method creates an object composed of the
 * own and inherited enumerable property paths of `object` that are not omitted.
 *
 * **Note:** This method is considerably slower than `_.pick`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to omit.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.omit(object, ['a', 'c']);
 * // => { 'b': '2' }
 */
var omit = _flatRest(function (object, paths) {
  var result = {};
  if (object == null) {
    return result;
  }
  var isDeep = false;
  paths = _arrayMap(paths, function (path) {
    path = _castPath(path, object);
    isDeep || (isDeep = path.length > 1);
    return path;
  });
  _copyObject(object, _getAllKeysIn(object), result);
  if (isDeep) {
    result = _baseClone(result, omit_CLONE_DEEP_FLAG | omit_CLONE_FLAT_FLAG | omit_CLONE_SYMBOLS_FLAG, _customOmitClone);
  }
  var length = paths.length;
  while (length--) {
    _baseUnset(result, paths[length]);
  }
  return result;
});
/* harmony default export */ const lodash_es_omit = (omit);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSet.js






/**
 * The base implementation of `_.set`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The path of the property to set.
 * @param {*} value The value to set.
 * @param {Function} [customizer] The function to customize path creation.
 * @returns {Object} Returns `object`.
 */
function baseSet(object, path, value, customizer) {
  if (!lodash_es_isObject(object)) {
    return object;
  }
  path = _castPath(path, object);
  var index = -1,
    length = path.length,
    lastIndex = length - 1,
    nested = object;
  while (nested != null && ++index < length) {
    var key = _toKey(path[index]),
      newValue = value;
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      return object;
    }
    if (index != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : undefined;
      if (newValue === undefined) {
        newValue = lodash_es_isObject(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
      }
    }
    _assignValue(nested, key, newValue);
    nested = nested[key];
  }
  return object;
}
/* harmony default export */ const _baseSet = (baseSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePickBy.js




/**
 * The base implementation of  `_.pickBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @param {Function} predicate The function invoked per property.
 * @returns {Object} Returns the new object.
 */
function basePickBy(object, paths, predicate) {
  var index = -1,
    length = paths.length,
    result = {};
  while (++index < length) {
    var path = paths[index],
      value = _baseGet(object, path);
    if (predicate(value, path)) {
      _baseSet(result, _castPath(path, object), value);
    }
  }
  return result;
}
/* harmony default export */ const _basePickBy = (basePickBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePick.js



/**
 * The base implementation of `_.pick` without support for individual
 * property identifiers.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @returns {Object} Returns the new object.
 */
function basePick(object, paths) {
  return _basePickBy(object, paths, function (value, path) {
    return lodash_es_hasIn(object, path);
  });
}
/* harmony default export */ const _basePick = (basePick);
;// CONCATENATED MODULE: ./node_modules/lodash-es/pick.js



/**
 * Creates an object composed of the picked `object` properties.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to pick.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.pick(object, ['a', 'c']);
 * // => { 'a': 1, 'c': 3 }
 */
var pick = _flatRest(function (object, paths) {
  return object == null ? {} : _basePick(object, paths);
});
/* harmony default export */ const lodash_es_pick = (pick);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/model.js
function model_typeof(obj) {
  "@babel/helpers - typeof";

  return model_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;
  }, model_typeof(obj);
}
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.

// Model
// -----
// **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.

// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.

















var Model = function Model(attributes, options) {
  var attrs = attributes || {};
  options || (options = {});
  this.preinitialize.apply(this, arguments);
  this.cid = lodash_es_uniqueId(this.cidPrefix);
  this.attributes = {};
  if (options.collection) this.collection = options.collection;
  if (options.parse) attrs = this.parse(attrs, options) || {};
  var default_attrs = lodash_es_result(this, 'defaults');
  attrs = lodash_es_defaults(lodash_es_assignIn({}, default_attrs, attrs), default_attrs);
  this.set(attrs, options);
  this.changed = {};
  this.initialize.apply(this, arguments);
};
Model.extend = inherits;

// Attach all inheritable methods to the Model prototype.
Object.assign(Model.prototype, Events, {
  // A hash of attributes whose current and previous value differ.
  changed: null,
  // The value returned during the last failed validation.
  validationError: null,
  // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  // CouchDB users may want to set this to `"_id"`.
  idAttribute: 'id',
  // The prefix is used to create the client id which is used to identify models locally.
  // You may want to override this if you're experiencing name clashes with model ids.
  cidPrefix: 'c',
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Model.
  preinitialize: function preinitialize() {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function initialize() {},
  // Return a copy of the model's `attributes` object.
  toJSON: function toJSON(options) {
    return lodash_es_clone(this.attributes);
  },
  // Proxy `Backbone.sync` by default -- but override this if you need
  // custom syncing semantics for *this* particular model.
  sync: function sync(method, model, options) {
    return getSyncMethod(this)(method, model, options);
  },
  // Get the value of an attribute.
  get: function get(attr) {
    return this.attributes[attr];
  },
  keys: function keys() {
    return Object.keys(this.attributes);
  },
  values: function values() {
    return Object.values(this.attributes);
  },
  pairs: function pairs() {
    return this.entries();
  },
  entries: function entries() {
    return Object.entries(this.attributes);
  },
  invert: function invert() {
    return lodash_es_invert(this.attributes);
  },
  pick: function pick() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (args.length === 1 && Array.isArray(args[0])) {
      args = args[0];
    }
    return lodash_es_pick(this.attributes, args);
  },
  omit: function omit() {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    if (args.length === 1 && Array.isArray(args[0])) {
      args = args[0];
    }
    return lodash_es_omit(this.attributes, args);
  },
  isEmpty: function isEmpty() {
    return lodash_es_isEmpty(this.attributes);
  },
  // Get the HTML-escaped value of an attribute.
  escape: function escape(attr) {
    return lodash_es_escape(this.get(attr));
  },
  // Returns `true` if the attribute contains a value that is not null
  // or undefined.
  has: function has(attr) {
    return this.get(attr) != null;
  },
  // Special-cased proxy to lodash's `matches` method.
  matches: function matches(attrs) {
    return !!lodash_es_iteratee(attrs, this)(this.attributes);
  },
  // Set a hash of model attributes on the object, firing `"change"`. This is
  // the core primitive operation of a model, updating the data and notifying
  // anyone who needs to know about the change in state. The heart of the beast.
  set: function set(key, val, options) {
    if (key == null) return this;

    // Handle both `"key", value` and `{key: value}` -style arguments.
    var attrs;
    if (model_typeof(key) === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }
    options || (options = {});

    // Run validation.
    if (!this._validate(attrs, options)) return false;

    // Extract attributes and options.
    var unset = options.unset;
    var silent = options.silent;
    var changes = [];
    var changing = this._changing;
    this._changing = true;
    if (!changing) {
      this._previousAttributes = lodash_es_clone(this.attributes);
      this.changed = {};
    }
    var current = this.attributes;
    var changed = this.changed;
    var prev = this._previousAttributes;

    // For each `set` attribute, update or delete the current value.
    for (var attr in attrs) {
      val = attrs[attr];
      if (!lodash_es_isEqual(current[attr], val)) changes.push(attr);
      if (!lodash_es_isEqual(prev[attr], val)) {
        changed[attr] = val;
      } else {
        delete changed[attr];
      }
      unset ? delete current[attr] : current[attr] = val;
    }

    // Update the `id`.
    if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

    // Trigger all relevant attribute changes.
    if (!silent) {
      if (changes.length) this._pending = options;
      for (var i = 0; i < changes.length; i++) {
        this.trigger('change:' + changes[i], this, current[changes[i]], options);
      }
    }

    // You might be wondering why there's a `while` loop here. Changes can
    // be recursively nested within `"change"` events.
    if (changing) return this;
    if (!silent) {
      while (this._pending) {
        options = this._pending;
        this._pending = false;
        this.trigger('change', this, options);
      }
    }
    this._pending = false;
    this._changing = false;
    return this;
  },
  // Remove an attribute from the model, firing `"change"`. `unset` is a noop
  // if the attribute doesn't exist.
  unset: function unset(attr, options) {
    return this.set(attr, undefined, lodash_es_assignIn({}, options, {
      unset: true
    }));
  },
  // Clear all attributes on the model, firing `"change"`.
  clear: function clear(options) {
    var attrs = {};
    for (var key in this.attributes) attrs[key] = undefined;
    return this.set(attrs, lodash_es_assignIn({}, options, {
      unset: true
    }));
  },
  // Determine if the model has changed since the last `"change"` event.
  // If you specify an attribute name, determine if that attribute has changed.
  hasChanged: function hasChanged(attr) {
    if (attr == null) return !lodash_es_isEmpty(this.changed);
    return lodash_es_has(this.changed, attr);
  },
  // Return an object containing all the attributes that have changed, or
  // false if there are no changed attributes. Useful for determining what
  // parts of a view need to be updated and/or what attributes need to be
  // persisted to the server. Unset attributes will be set to undefined.
  // You can also pass an attributes object to diff against the model,
  // determining if there *would be* a change.
  changedAttributes: function changedAttributes(diff) {
    if (!diff) return this.hasChanged() ? lodash_es_clone(this.changed) : false;
    var old = this._changing ? this._previousAttributes : this.attributes;
    var changed = {};
    var hasChanged;
    for (var attr in diff) {
      var val = diff[attr];
      if (lodash_es_isEqual(old[attr], val)) continue;
      changed[attr] = val;
      hasChanged = true;
    }
    return hasChanged ? changed : false;
  },
  // Get the previous value of an attribute, recorded at the time the last
  // `"change"` event was fired.
  previous: function previous(attr) {
    if (attr == null || !this._previousAttributes) return null;
    return this._previousAttributes[attr];
  },
  // Get all of the attributes of the model at the time of the previous
  // `"change"` event.
  previousAttributes: function previousAttributes() {
    return lodash_es_clone(this._previousAttributes);
  },
  // Fetch the model from the server, merging the response with the model's
  // local attributes. Any changed attributes will trigger a "change" event.
  fetch: function fetch(options) {
    options = lodash_es_assignIn({
      parse: true
    }, options);
    var model = this;
    var success = options.success;
    options.success = function (resp) {
      var serverAttrs = options.parse ? model.parse(resp, options) : resp;
      if (!model.set(serverAttrs, options)) return false;
      if (success) success.call(options.context, model, resp, options);
      model.trigger('sync', model, resp, options);
    };
    wrapError(this, options);
    return this.sync('read', this, options);
  },
  // Set a hash of model attributes, and sync the model to the server.
  // If the server returns an attributes hash that differs, the model's
  // state will be `set` again.
  save: function save(key, val, options) {
    // Handle both `"key", value` and `{key: value}` -style arguments.
    var attrs;
    if (key == null || model_typeof(key) === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }
    options = lodash_es_assignIn({
      validate: true,
      parse: true
    }, options);
    var wait = options.wait;
    var return_promise = options.promise;
    var promise = return_promise && getResolveablePromise();

    // If we're not waiting and attributes exist, save acts as
    // `set(attr).save(null, opts)` with validation. Otherwise, check if
    // the model will be valid when the attributes, if any, are set.
    if (attrs && !wait) {
      if (!this.set(attrs, options)) return false;
    } else if (!this._validate(attrs, options)) {
      return false;
    }

    // After a successful server-side save, the client is (optionally)
    // updated with the server-side state.
    var model = this;
    var success = options.success;
    var error = options.error;
    var attributes = this.attributes;
    options.success = function (resp) {
      // Ensure attributes are restored during synchronous saves.
      model.attributes = attributes;
      var serverAttrs = options.parse ? model.parse(resp, options) : resp;
      if (wait) serverAttrs = lodash_es_assignIn({}, attrs, serverAttrs);
      if (serverAttrs && !model.set(serverAttrs, options)) return false;
      if (success) success.call(options.context, model, resp, options);
      model.trigger('sync', model, resp, options);
      return_promise && promise.resolve();
    };
    options.error = function (model, e, options) {
      error && error.call(options.context, model, e, options);
      return_promise && promise.reject(e);
    };
    wrapError(this, options);

    // Set temporary attributes if `{wait: true}` to properly find new ids.
    if (attrs && wait) this.attributes = lodash_es_assignIn({}, attributes, attrs);
    var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
    if (method === 'patch' && !options.attrs) options.attrs = attrs;
    var xhr = this.sync(method, this, options);

    // Restore attributes.
    this.attributes = attributes;
    if (return_promise) {
      return promise;
    } else {
      return xhr;
    }
  },
  // Destroy this model on the server if it was already persisted.
  // Optimistically removes the model from its collection, if it has one.
  // If `wait: true` is passed, waits for the server to respond before removal.
  destroy: function destroy(options) {
    options = options ? lodash_es_clone(options) : {};
    var model = this;
    var success = options.success;
    var wait = options.wait;
    var destroy = function destroy() {
      model.stopListening();
      model.trigger('destroy', model, model.collection, options);
    };
    options.success = function (resp) {
      if (wait) destroy();
      if (success) success.call(options.context, model, resp, options);
      if (!model.isNew()) model.trigger('sync', model, resp, options);
    };
    var xhr = false;
    if (this.isNew()) {
      lodash_es_defer(options.success);
    } else {
      wrapError(this, options);
      xhr = this.sync('delete', this, options);
    }
    if (!wait) destroy();
    return xhr;
  },
  // Default URL for the model's representation on the server -- if you're
  // using Backbone's restful methods, override this to change the endpoint
  // that will be called.
  url: function url() {
    var base = lodash_es_result(this, 'urlRoot') || lodash_es_result(this.collection, 'url') || urlError();
    if (this.isNew()) return base;
    var id = this.get(this.idAttribute);
    return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
  },
  // **parse** converts a response into the hash of attributes to be `set` on
  // the model. The default implementation is just to pass the response along.
  parse: function parse(resp, options) {
    return resp;
  },
  // Create a new model with identical attributes to this one.
  clone: function clone() {
    return new this.constructor(this.attributes);
  },
  // A model is new if it has never been saved to the server, and lacks an id.
  isNew: function isNew() {
    return !this.has(this.idAttribute);
  },
  // Check if the model is currently in a valid state.
  isValid: function isValid(options) {
    return this._validate({}, lodash_es_assignIn({}, options, {
      validate: true
    }));
  },
  // Run validation against the next complete set of model attributes,
  // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
  _validate: function _validate(attrs, options) {
    if (!options.validate || !this.validate) return true;
    attrs = lodash_es_assignIn({}, this.attributes, attrs);
    var error = this.validationError = this.validate(attrs, options) || null;
    if (!error) return true;
    this.trigger('invalid', this, error, lodash_es_assignIn(options, {
      validationError: error
    }));
    return false;
  }
});
;// CONCATENATED MODULE: external "strophe"
const external_strophe_namespaceObject = strophe;
;// CONCATENATED MODULE: ./src/headless/shared/constants.js

var BOSH_WAIT = 59;
var VERSION_NAME = "v10.1.8";
var STATUS_WEIGHTS = {
  offline: 6,
  unavailable: 5,
  xa: 4,
  away: 3,
  dnd: 2,
  chat: 1,
  // We don't differentiate between "chat" and "online"
  online: 1
};
var ANONYMOUS = 'anonymous';
var CLOSED = 'closed';
var EXTERNAL = 'external';
var LOGIN = 'login';
var LOGOUT = 'logout';
var OPENED = 'opened';
var PREBIND = 'prebind';
var SUCCESS = 'success';
var FAILURE = 'failure';

// Generated from css/images/user.svg
var DEFAULT_IMAGE_TYPE = 'image/svg+xml';
var DEFAULT_IMAGE = 'PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==';

// XEP-0085 Chat states
// https =//xmpp.org/extensions/xep-0085.html
var INACTIVE = 'inactive';
var ACTIVE = 'active';
var COMPOSING = 'composing';
var PAUSED = 'paused';
var GONE = 'gone';

// Chat types
var PRIVATE_CHAT_TYPE = 'chatbox';
var CHATROOMS_TYPE = 'chatroom';
var HEADLINES_TYPE = 'headline';
var CONTROLBOX_TYPE = 'controlbox';
var CONNECTION_STATUS = {};
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.ATTACHED] = 'ATTACHED';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.AUTHENTICATING] = 'AUTHENTICATING';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.AUTHFAIL] = 'AUTHFAIL';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.CONNECTED] = 'CONNECTED';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.CONNECTING] = 'CONNECTING';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.CONNFAIL] = 'CONNFAIL';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.DISCONNECTED] = 'DISCONNECTED';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.DISCONNECTING] = 'DISCONNECTING';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.ERROR] = 'ERROR';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.RECONNECTING] = 'RECONNECTING';
CONNECTION_STATUS[external_strophe_namespaceObject.Strophe.Status.REDIRECT] = 'REDIRECT';

// Add Strophe Namespaces
external_strophe_namespaceObject.Strophe.addNamespace('ACTIVITY', 'http://jabber.org/protocol/activity');
external_strophe_namespaceObject.Strophe.addNamespace('CARBONS', 'urn:xmpp:carbons:2');
external_strophe_namespaceObject.Strophe.addNamespace('CHATSTATES', 'http://jabber.org/protocol/chatstates');
external_strophe_namespaceObject.Strophe.addNamespace('CSI', 'urn:xmpp:csi:0');
external_strophe_namespaceObject.Strophe.addNamespace('DELAY', 'urn:xmpp:delay');
external_strophe_namespaceObject.Strophe.addNamespace('EME', 'urn:xmpp:eme:0');
external_strophe_namespaceObject.Strophe.addNamespace('FASTEN', 'urn:xmpp:fasten:0');
external_strophe_namespaceObject.Strophe.addNamespace('FORWARD', 'urn:xmpp:forward:0');
external_strophe_namespaceObject.Strophe.addNamespace('HINTS', 'urn:xmpp:hints');
external_strophe_namespaceObject.Strophe.addNamespace('HTTPUPLOAD', 'urn:xmpp:http:upload:0');
external_strophe_namespaceObject.Strophe.addNamespace('MAM', 'urn:xmpp:mam:2');
external_strophe_namespaceObject.Strophe.addNamespace('MARKERS', 'urn:xmpp:chat-markers:0');
external_strophe_namespaceObject.Strophe.addNamespace('MENTIONS', 'urn:xmpp:mmn:0');
external_strophe_namespaceObject.Strophe.addNamespace('MESSAGE_CORRECT', 'urn:xmpp:message-correct:0');
external_strophe_namespaceObject.Strophe.addNamespace('MODERATE', 'urn:xmpp:message-moderate:0');
external_strophe_namespaceObject.Strophe.addNamespace('NICK', 'http://jabber.org/protocol/nick');
external_strophe_namespaceObject.Strophe.addNamespace('OCCUPANTID', 'urn:xmpp:occupant-id:0');
external_strophe_namespaceObject.Strophe.addNamespace('OMEMO', 'eu.siacs.conversations.axolotl');
external_strophe_namespaceObject.Strophe.addNamespace('OUTOFBAND', 'jabber:x:oob');
external_strophe_namespaceObject.Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
external_strophe_namespaceObject.Strophe.addNamespace('RAI', 'urn:xmpp:rai:0');
external_strophe_namespaceObject.Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts');
external_strophe_namespaceObject.Strophe.addNamespace('REFERENCE', 'urn:xmpp:reference:0');
external_strophe_namespaceObject.Strophe.addNamespace('REGISTER', 'jabber:iq:register');
external_strophe_namespaceObject.Strophe.addNamespace('RETRACT', 'urn:xmpp:message-retract:0');
external_strophe_namespaceObject.Strophe.addNamespace('ROSTERX', 'http://jabber.org/protocol/rosterx');
external_strophe_namespaceObject.Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
external_strophe_namespaceObject.Strophe.addNamespace('SID', 'urn:xmpp:sid:0');
external_strophe_namespaceObject.Strophe.addNamespace('SPOILER', 'urn:xmpp:spoiler:0');
external_strophe_namespaceObject.Strophe.addNamespace('STANZAS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
external_strophe_namespaceObject.Strophe.addNamespace('STYLING', 'urn:xmpp:styling:0');
external_strophe_namespaceObject.Strophe.addNamespace('VCARD', 'vcard-temp');
external_strophe_namespaceObject.Strophe.addNamespace('VCARDUPDATE', 'vcard-temp:x:update');
external_strophe_namespaceObject.Strophe.addNamespace('XFORM', 'jabber:x:data');
external_strophe_namespaceObject.Strophe.addNamespace('XHTML', 'http://www.w3.org/1999/xhtml');

// Core plugins are whitelisted automatically
// These are just the @converse/headless plugins, for the full converse,
// the other plugins are whitelisted in src/consts.js
var CORE_PLUGINS = ['converse-adhoc', 'converse-bookmarks', 'converse-bosh', 'converse-caps', 'converse-chat', 'converse-chatboxes', 'converse-disco', 'converse-emoji', 'converse-headlines', 'converse-mam', 'converse-muc', 'converse-ping', 'converse-pubsub', 'converse-roster', 'converse-smacks', 'converse-status', 'converse-vcard'];
var URL_PARSE_OPTIONS = {
  'start': /(\b|_)(?:([a-z][a-z0-9.+-]*:\/\/)|xmpp:|mailto:|www\.)/gi
};
var CHAT_STATES = ['active', 'composing', 'gone', 'inactive', 'paused'];
var KEYCODES = {
  TAB: 9,
  ENTER: 13,
  SHIFT: 16,
  CTRL: 17,
  ALT: 18,
  ESCAPE: 27,
  LEFT_ARROW: 37,
  UP_ARROW: 38,
  RIGHT_ARROW: 39,
  DOWN_ARROW: 40,
  FORWARD_SLASH: 47,
  AT: 50,
  META: 91,
  META_RIGHT: 93
};
// EXTERNAL MODULE: ./node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(8137);
;// CONCATENATED MODULE: ./src/headless/shared/i18n.js


/**
 * @namespace i18n
 */
/* harmony default export */ const i18n = ({
  initialize: function initialize() {},
  /**
   * Overridable string wrapper method which can be used to provide i18n
   * support.
   *
   * The default implementation in @converse/headless simply calls sprintf
   * with the passed in arguments.
   *
   * If you install the full version of Converse, then this method gets
   * overwritten in src/i18n/index.js to return a translated string.
   * @method __
   * @private
   * @memberOf i18n
   * @param { String } str
   */
  __: function __() {
    return sprintf.sprintf.apply(void 0, arguments);
  }
});
// EXTERNAL MODULE: ./node_modules/dompurify/dist/purify.js
var purify = __webpack_require__(1754);
var purify_default = /*#__PURE__*/__webpack_require__.n(purify);
;// CONCATENATED MODULE: ./node_modules/lodash-es/compact.js
/**
 * Creates an array with all falsey values removed. The values `false`, `null`,
 * `0`, `""`, `undefined`, and `NaN` are falsey.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to compact.
 * @returns {Array} Returns the new array of filtered values.
 * @example
 *
 * _.compact([0, 1, false, 2, '', 3]);
 * // => [1, 2, 3]
 */
function compact(array) {
  var index = -1,
    length = array == null ? 0 : array.length,
    resIndex = 0,
    result = [];
  while (++index < length) {
    var value = array[index];
    if (value) {
      result[resIndex++] = value;
    }
  }
  return result;
}
/* harmony default export */ const lodash_es_compact = (compact);
;// CONCATENATED MODULE: external "sizzle"
const external_sizzle_namespaceObject = sizzle;
var external_sizzle_default = /*#__PURE__*/__webpack_require__.n(external_sizzle_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@converse/openpromise/openpromise.js
function getOpenPromise() {
  var wrapper = {
    isResolved: false,
    isPending: true,
    isRejected: false
  };
  var promise = new Promise(function (resolve, reject) {
    wrapper.resolve = resolve;
    wrapper.reject = reject;
  });
  Object.assign(promise, wrapper);
  promise.then(function (v) {
    promise.isResolved = true;
    promise.isPending = false;
    promise.isRejected = false;
    return v;
  }, function (e) {
    promise.isResolved = false;
    promise.isPending = false;
    promise.isRejected = true;
    throw e;
  });
  return promise;
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/constants.js
/**
 * @typedef { Object } ConfigurationSettings
 * Converse's core configuration values
 * @property { Boolean } [allow_non_roster_messaging=false]
 * @property { Boolean } [allow_url_history_change=true]
 * @property { String } [assets_path='/dist']
 * @property { ('login'|'prebind'|'anonymous'|'external') } [authentication='login']
 * @property { Boolean } [auto_login=false] - Currently only used in connection with anonymous login
 * @property { Boolean } [reuse_scram_keys=false] - Save SCRAM keys after login to allow for future auto login
 * @property { Boolean } [auto_reconnect=true]
 * @property { Array<String>} [blacklisted_plugins]
 * @property { Boolean } [clear_cache_on_logout=false]
 * @property { Object } [connection_options]
 * @property { String } [credentials_url] - URL from where login credentials can be fetched
 * @property { Boolean } [discover_connection_methods=true]
 * @property { RegExp } [geouri_regex]
 * @property { RegExp } [geouri_replacement='https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2']
 * @property { String } [i18n]
 * @property { String } [jid]
 * @property { Boolean } [keepalive=true]
 * @property { ('debug'|'info'|'eror') } [loglevel='info']
 * @property { Array<String> } [locales]
 * @property { String } [nickname]
 * @property { String } [password]
 * @property { ('IndexedDB'|'localStorage') } [persistent_store='IndexedDB']
 * @property { String } [rid]
 * @property { Element } [root=window.document]
 * @property { String } [sid]
 * @property { Boolean } [singleton=false]
 * @property { Boolean } [strict_plugin_dependencies=false]
 * @property { ('overlayed'|'fullscreen'|'mobile') } [view_mode='overlayed']
 * @property { String } [websocket_url]
 * @property { Array<String>} [whitelisted_plugins]
 */
var DEFAULT_SETTINGS = {
  allow_non_roster_messaging: false,
  allow_url_history_change: true,
  assets_path: '/dist',
  authentication: 'login',
  // Available values are "login", "prebind", "anonymous" and "external".
  auto_login: false,
  // Currently only used in connection with anonymous login
  reuse_scram_keys: false,
  auto_reconnect: true,
  blacklisted_plugins: [],
  clear_cache_on_logout: false,
  connection_options: {},
  credentials_url: null,
  // URL from where login credentials can be fetched
  discover_connection_methods: true,
  geouri_regex: /https\:\/\/www.openstreetmap.org\/.*#map=[0-9]+\/([\-0-9.]+)\/([\-0-9.]+)\S*/g,
  geouri_replacement: 'https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2',
  i18n: undefined,
  jid: undefined,
  keepalive: true,
  loglevel: 'info',
  locales: ['af', 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'eo', 'es', 'eu', 'fa', 'fi', 'fr', 'gl', 'he', 'hi', 'hu', 'id', 'it', 'ja', 'lt', 'mr', 'nb', 'nl', 'oc', 'pl', 'pt', 'pt_BR', 'ro', 'ru', 'sv', 'th', 'tr', 'ug', 'uk', 'vi', 'zh_CN', 'zh_TW'],
  nickname: undefined,
  password: undefined,
  persistent_store: 'IndexedDB',
  rid: undefined,
  root: window.document,
  sid: undefined,
  singleton: false,
  strict_plugin_dependencies: false,
  stanza_timeout: 20000,
  view_mode: 'overlayed',
  // Choices are 'overlayed', 'fullscreen', 'mobile'
  websocket_url: undefined,
  whitelisted_plugins: []
};
// EXTERNAL MODULE: ./node_modules/localforage-driver-memory/_bundle/umd.js
var umd = __webpack_require__(388);
;// CONCATENATED MODULE: ./node_modules/lodash-es/cloneDeep.js


/** Used to compose bitmasks for cloning. */
var cloneDeep_CLONE_DEEP_FLAG = 1,
  cloneDeep_CLONE_SYMBOLS_FLAG = 4;

/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function cloneDeep(value) {
  return _baseClone(value, cloneDeep_CLONE_DEEP_FLAG | cloneDeep_CLONE_SYMBOLS_FLAG);
}
/* harmony default export */ const lodash_es_cloneDeep = (cloneDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isString.js




/** `Object#toString` result references. */
var isString_stringTag = '[object String]';

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */
function isString(value) {
  return typeof value == 'string' || !lodash_es_isArray(value) && lodash_es_isObjectLike(value) && _baseGetTag(value) == isString_stringTag;
}
/* harmony default export */ const lodash_es_isString = (isString);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/idb.js
function getIDB() {
  /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
  try {
    if (typeof indexedDB !== 'undefined') {
      return indexedDB;
    }
    if (typeof webkitIndexedDB !== 'undefined') {
      return webkitIndexedDB;
    }
    if (typeof mozIndexedDB !== 'undefined') {
      return mozIndexedDB;
    }
    if (typeof OIndexedDB !== 'undefined') {
      return OIndexedDB;
    }
    if (typeof msIndexedDB !== 'undefined') {
      return msIndexedDB;
    }
  } catch (e) {
    return;
  }
}
var idb = getIDB();
/* harmony default export */ const utils_idb = (idb);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isIndexedDBValid.js

function isIndexedDBValid() {
  try {
    // Initialize IndexedDB; fall back to vendor-prefixed versions
    // if needed.
    if (!utils_idb || !utils_idb.open) {
      return false;
    }
    // We mimic PouchDB here;
    //
    // We test for openDatabase because IE Mobile identifies itself
    // as Safari. Oh the lulz...
    var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
    var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;

    // Safari <10.1 does not meet our requirements for IDB support
    // (see: https://github.com/pouchdb/pouchdb/issues/5572).
    // Safari 10.1 shipped with fetch, we can use that to detect it.
    // Note: this creates issues with `window.fetch` polyfills and
    // overrides; see:
    // https://github.com/localForage/localForage/issues/856
    return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
    // some outdated implementations of IDB that appear on Samsung
    // and HTC Android devices <4.4 are missing IDBKeyRange
    // See: https://github.com/mozilla/localForage/issues/128
    // See: https://github.com/mozilla/localForage/issues/272
    typeof IDBKeyRange !== 'undefined';
  } catch (e) {
    return false;
  }
}
/* harmony default export */ const utils_isIndexedDBValid = (isIndexedDBValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/createBlob.js
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
  /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  parts = parts || [];
  properties = properties || {};
  try {
    return new Blob(parts, properties);
  } catch (e) {
    if (e.name !== 'TypeError') {
      throw e;
    }
    var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
    var builder = new Builder();
    for (var i = 0; i < parts.length; i += 1) {
      builder.append(parts[i]);
    }
    return builder.getBlob(properties.type);
  }
}
/* harmony default export */ const utils_createBlob = (createBlob);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/promise.js
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
  // In the "nopromises" build this will just throw if you don't have
  // a global promise object, but it would throw anyway later.
  __webpack_require__(3968);
}
/* harmony default export */ const utils_promise = (Promise);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/executeCallback.js
function executeCallback(promise, callback) {
  if (callback) {
    promise.then(function (result) {
      callback(null, result);
    }, function (error) {
      callback(error);
    });
  }
}
/* harmony default export */ const utils_executeCallback = (executeCallback);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/executeTwoCallbacks.js
function executeTwoCallbacks(promise, callback, errorCallback) {
  if (typeof callback === 'function') {
    promise.then(callback);
  }
  if (typeof errorCallback === 'function') {
    promise.catch(errorCallback);
  }
}
/* harmony default export */ const utils_executeTwoCallbacks = (executeTwoCallbacks);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/normalizeKey.js
function normalizeKey(key) {
  // Cast the key to a string, as that's all we can set as a key.
  if (typeof key !== 'string') {
    console.warn("".concat(key, " used as a key, but it is not a string."));
    key = String(key);
  }
  return key;
}
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/getCallback.js
function getCallback() {
  if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
    return arguments[arguments.length - 1];
  }
}
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/indexeddb.js









// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).

var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts = {};
var indexeddb_toString = Object.prototype.toString;

// Transaction Modes
var READ_ONLY = 'readonly';
var READ_WRITE = 'readwrite';

// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
  var length = bin.length;
  var buf = new ArrayBuffer(length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < length; i++) {
    arr[i] = bin.charCodeAt(i);
  }
  return buf;
}

//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
  return new utils_promise(function (resolve) {
    var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
    var blob = utils_createBlob(['']);
    txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
    txn.onabort = function (e) {
      // If the transaction aborts now its due to not being able to
      // write to the database, likely due to the disk being full
      e.preventDefault();
      e.stopPropagation();
      resolve(false);
    };
    txn.oncomplete = function () {
      var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
      var matchedEdge = navigator.userAgent.match(/Edge\//);
      // MS Edge pretends to be Chrome 42:
      // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
      resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
    };
  }).catch(function () {
    return false; // error, so assume unsupported
  });
}

function _checkBlobSupport(idb) {
  if (typeof supportsBlobs === 'boolean') {
    return utils_promise.resolve(supportsBlobs);
  }
  return _checkBlobSupportWithoutCaching(idb).then(function (value) {
    supportsBlobs = value;
    return supportsBlobs;
  });
}
function _deferReadiness(dbInfo) {
  var dbContext = dbContexts[dbInfo.name];

  // Create a deferred object representing the current database operation.
  var deferredOperation = {};
  deferredOperation.promise = new utils_promise(function (resolve, reject) {
    deferredOperation.resolve = resolve;
    deferredOperation.reject = reject;
  });

  // Enqueue the deferred operation.
  dbContext.deferredOperations.push(deferredOperation);

  // Chain its promise to the database readiness.
  if (!dbContext.dbReady) {
    dbContext.dbReady = deferredOperation.promise;
  } else {
    dbContext.dbReady = dbContext.dbReady.then(function () {
      return deferredOperation.promise;
    });
  }
}
function _advanceReadiness(dbInfo) {
  var dbContext = dbContexts[dbInfo.name];

  // Dequeue a deferred operation.
  var deferredOperation = dbContext.deferredOperations.pop();

  // Resolve its promise (which is part of the database readiness
  // chain of promises).
  if (deferredOperation) {
    deferredOperation.resolve();
    return deferredOperation.promise;
  }
}
function _rejectReadiness(dbInfo, err) {
  var dbContext = dbContexts[dbInfo.name];

  // Dequeue a deferred operation.
  var deferredOperation = dbContext.deferredOperations.pop();

  // Reject its promise (which is part of the database readiness
  // chain of promises).
  if (deferredOperation) {
    deferredOperation.reject(err);
    return deferredOperation.promise;
  }
}
function _getConnection(dbInfo, upgradeNeeded) {
  return new utils_promise(function (resolve, reject) {
    dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
    if (dbInfo.db) {
      if (upgradeNeeded) {
        _deferReadiness(dbInfo);
        dbInfo.db.close();
      } else {
        return resolve(dbInfo.db);
      }
    }
    var dbArgs = [dbInfo.name];
    if (upgradeNeeded) {
      dbArgs.push(dbInfo.version);
    }
    var openreq = utils_idb.open.apply(utils_idb, dbArgs);
    if (upgradeNeeded) {
      openreq.onupgradeneeded = function (e) {
        var db = openreq.result;
        try {
          db.createObjectStore(dbInfo.storeName);
          if (e.oldVersion <= 1) {
            // Added when support for blob shims was added
            db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
          }
        } catch (ex) {
          if (ex.name === 'ConstraintError') {
            console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
          } else {
            throw ex;
          }
        }
      };
    }
    openreq.onerror = function (e) {
      e.preventDefault();
      reject(openreq.error);
    };
    openreq.onsuccess = function () {
      var db = openreq.result;
      db.onversionchange = function (e) {
        // Triggered when the database is modified (e.g. adding an objectStore) or
        // deleted (even when initiated by other sessions in different tabs).
        // Closing the connection here prevents those operations from being blocked.
        // If the database is accessed again later by this instance, the connection
        // will be reopened or the database recreated as needed.
        e.target.close();
      };
      resolve(db);
      _advanceReadiness(dbInfo);
    };
  });
}
function _getOriginalConnection(dbInfo) {
  return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
  return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
  if (!dbInfo.db) {
    return true;
  }
  var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
  var isDowngrade = dbInfo.version < dbInfo.db.version;
  var isUpgrade = dbInfo.version > dbInfo.db.version;
  if (isDowngrade) {
    // If the version is not the default one
    // then warn for impossible downgrade.
    if (dbInfo.version !== defaultVersion) {
      console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
    }
    // Align the versions to prevent errors.
    dbInfo.version = dbInfo.db.version;
  }
  if (isUpgrade || isNewStore) {
    // If the store is new then increment the version (if needed).
    // This will trigger an "upgradeneeded" event which is required
    // for creating a store.
    if (isNewStore) {
      var incVersion = dbInfo.db.version + 1;
      if (incVersion > dbInfo.version) {
        dbInfo.version = incVersion;
      }
    }
    return true;
  }
  return false;
}

// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
  return new utils_promise(function (resolve, reject) {
    var reader = new FileReader();
    reader.onerror = reject;
    reader.onloadend = function (e) {
      var base64 = btoa(e.target.result || '');
      resolve({
        __local_forage_encoded_blob: true,
        data: base64,
        type: blob.type
      });
    };
    reader.readAsBinaryString(blob);
  });
}

// decode an encoded blob
function _decodeBlob(encodedBlob) {
  var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
  return utils_createBlob([arrayBuff], {
    type: encodedBlob.type
  });
}

// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
  return value && value.__local_forage_encoded_blob;
}

// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
  var self = this;
  var promise = self._initReady().then(function () {
    var dbContext = dbContexts[self._dbInfo.name];
    if (dbContext && dbContext.dbReady) {
      return dbContext.dbReady;
    }
  });
  utils_executeTwoCallbacks(promise, callback, callback);
  return promise;
}

// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
  _deferReadiness(dbInfo);
  var dbContext = dbContexts[dbInfo.name];
  var forages = dbContext.forages;
  for (var i = 0; i < forages.length; i++) {
    var forage = forages[i];
    if (forage._dbInfo.db) {
      forage._dbInfo.db.close();
      forage._dbInfo.db = null;
    }
  }
  dbInfo.db = null;
  return _getOriginalConnection(dbInfo).then(function (db) {
    dbInfo.db = db;
    if (_isUpgradeNeeded(dbInfo)) {
      // Reopen the database for upgrading.
      return _getUpgradedConnection(dbInfo);
    }
    return db;
  }).then(function (db) {
    // store the latest db reference
    // in case the db was upgraded
    dbInfo.db = dbContext.db = db;
    for (var i = 0; i < forages.length; i++) {
      forages[i]._dbInfo.db = db;
    }
  }).catch(function (err) {
    _rejectReadiness(dbInfo, err);
    throw err;
  });
}

// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
  if (retries === undefined) {
    retries = 1;
  }
  try {
    var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
    callback(null, tx);
  } catch (err) {
    if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
      return utils_promise.resolve().then(function () {
        if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
          // increase the db version, to create the new ObjectStore
          if (dbInfo.db) {
            dbInfo.version = dbInfo.db.version + 1;
          }
          // Reopen the database for upgrading.
          return _getUpgradedConnection(dbInfo);
        }
      }).then(function () {
        return _tryReconnect(dbInfo).then(function () {
          createTransaction(dbInfo, mode, callback, retries - 1);
        });
      }).catch(callback);
    }
    callback(err);
  }
}
function createDbContext() {
  return {
    // Running localForages sharing a database.
    forages: [],
    // Shared database.
    db: null,
    // Database readiness (promise).
    dbReady: null,
    // Deferred operations on the database.
    deferredOperations: []
  };
}

// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
  var self = this;
  var dbInfo = {
    db: null
  };
  if (options) {
    for (var i in options) {
      dbInfo[i] = options[i];
    }
  }

  // Get the current context of the database;
  var dbContext = dbContexts[dbInfo.name];

  // ...or create a new context.
  if (!dbContext) {
    dbContext = createDbContext();
    // Register the new context in the global container.
    dbContexts[dbInfo.name] = dbContext;
  }

  // Register itself as a running localForage in the current context.
  dbContext.forages.push(self);

  // Replace the default `ready()` function with the specialized one.
  if (!self._initReady) {
    self._initReady = self.ready;
    self.ready = _fullyReady;
  }

  // Create an array of initialization states of the related localForages.
  var initPromises = [];
  function ignoreErrors() {
    // Don't handle errors here,
    // just makes sure related localForages aren't pending.
    return utils_promise.resolve();
  }
  for (var j = 0; j < dbContext.forages.length; j++) {
    var forage = dbContext.forages[j];
    if (forage !== self) {
      // Don't wait for itself...
      initPromises.push(forage._initReady().catch(ignoreErrors));
    }
  }

  // Take a snapshot of the related localForages.
  var forages = dbContext.forages.slice(0);

  // Initialize the connection process only when
  // all the related localForages aren't pending.
  return utils_promise.all(initPromises).then(function () {
    dbInfo.db = dbContext.db;
    // Get the connection or open a new one without upgrade.
    return _getOriginalConnection(dbInfo);
  }).then(function (db) {
    dbInfo.db = db;
    if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
      // Reopen the database for upgrading.
      return _getUpgradedConnection(dbInfo);
    }
    return db;
  }).then(function (db) {
    dbInfo.db = dbContext.db = db;
    self._dbInfo = dbInfo;
    // Share the final connection amongst related localForages.
    for (var k = 0; k < forages.length; k++) {
      var forage = forages[k];
      if (forage !== self) {
        // Self is already up-to-date.
        forage._dbInfo.db = dbInfo.db;
        forage._dbInfo.version = dbInfo.version;
      }
    }
  });
}
function getItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var req = store.get(key);
          req.onsuccess = function () {
            var value = req.result;
            if (value === undefined) {
              value = null;
            }
            if (_isEncodedBlob(value)) {
              value = _decodeBlob(value);
            }
            resolve(value);
          };
          req.onerror = function () {
            reject(req.error);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Iterate over all items stored in database.
function iterate(iterator, callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var req = store.openCursor();
          var iterationNumber = 1;
          req.onsuccess = function () {
            var cursor = req.result;
            if (cursor) {
              var value = cursor.value;
              if (_isEncodedBlob(value)) {
                value = _decodeBlob(value);
              }
              var result = iterator(value, cursor.key, iterationNumber++);

              // when the iterator callback returns any
              // (non-`undefined`) value, then we stop
              // the iteration immediately
              if (result !== void 0) {
                resolve(result);
              } else {
                cursor.continue();
              }
            } else {
              resolve();
            }
          };
          req.onerror = function () {
            reject(req.error);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function setItem(key, value, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    var dbInfo;
    self.ready().then(function () {
      dbInfo = self._dbInfo;
      if (indexeddb_toString.call(value) === '[object Blob]') {
        return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
          if (blobSupport) {
            return value;
          }
          return _encodeBlob(value);
        });
      }
      return value;
    }).then(function (value) {
      createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);

          // The reason we don't _save_ null is because IE 10 does
          // not support saving the `null` type in IndexedDB. How
          // ironic, given the bug below!
          // See: https://github.com/mozilla/localForage/issues/161
          if (value === null) {
            value = undefined;
          }
          var req = store.put(value, key);
          transaction.oncomplete = function () {
            // Cast to undefined so the value passed to
            // callback/promise is the same as what one would get out
            // of `getItem()` later. This leads to some weirdness
            // (setItem('foo', undefined) will return `null`), but
            // it's not my fault localStorage is our baseline and that
            // it's weird.
            if (value === undefined) {
              value = null;
            }
            resolve(value);
          };
          transaction.onabort = transaction.onerror = function () {
            var err = req.error ? req.error : req.transaction.error;
            reject(err);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function removeItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          // We use a Grunt task to make this safe for IE and some
          // versions of Android (including those used by Cordova).
          // Normally IE won't like `.delete()` and will insist on
          // using `['delete']()`, but we have a build step that
          // fixes this for us now.
          var req = store.delete(key);
          transaction.oncomplete = function () {
            resolve();
          };
          transaction.onerror = function () {
            reject(req.error);
          };

          // The request will be also be aborted if we've exceeded our storage
          // space.
          transaction.onabort = function () {
            var err = req.error ? req.error : req.transaction.error;
            reject(err);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function clear(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var req = store.clear();
          transaction.oncomplete = function () {
            resolve();
          };
          transaction.onabort = transaction.onerror = function () {
            var err = req.error ? req.error : req.transaction.error;
            reject(err);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function indexeddb_length(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var req = store.count();
          req.onsuccess = function () {
            resolve(req.result);
          };
          req.onerror = function () {
            reject(req.error);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function key(n, callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    if (n < 0) {
      resolve(null);
      return;
    }
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var advanced = false;
          var req = store.openKeyCursor();
          req.onsuccess = function () {
            var cursor = req.result;
            if (!cursor) {
              // this means there weren't enough keys
              resolve(null);
              return;
            }
            if (n === 0) {
              // We have the first key, return it if that's what they
              // wanted.
              resolve(cursor.key);
            } else {
              if (!advanced) {
                // Otherwise, ask the cursor to skip ahead n
                // records.
                advanced = true;
                cursor.advance(n);
              } else {
                // When we get here, we've got the nth key.
                resolve(cursor.key);
              }
            }
          };
          req.onerror = function () {
            reject(req.error);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function indexeddb_keys(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
        if (err) {
          return reject(err);
        }
        try {
          var store = transaction.objectStore(self._dbInfo.storeName);
          var req = store.openKeyCursor();
          var keys = [];
          req.onsuccess = function () {
            var cursor = req.result;
            if (!cursor) {
              resolve(keys);
              return;
            }
            keys.push(cursor.key);
            cursor.continue();
          };
          req.onerror = function () {
            reject(req.error);
          };
        } catch (e) {
          reject(e);
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function dropInstance(options, callback) {
  callback = getCallback.apply(this, arguments);
  var currentConfig = this.config();
  options = typeof options !== 'function' && options || {};
  if (!options.name) {
    options.name = options.name || currentConfig.name;
    options.storeName = options.storeName || currentConfig.storeName;
  }
  var self = this;
  var promise;
  if (!options.name) {
    promise = utils_promise.reject('Invalid arguments');
  } else {
    var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
    var dbPromise = isCurrentDb ? utils_promise.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
      var dbContext = dbContexts[options.name];
      var forages = dbContext.forages;
      dbContext.db = db;
      for (var i = 0; i < forages.length; i++) {
        forages[i]._dbInfo.db = db;
      }
      return db;
    });
    if (!options.storeName) {
      promise = dbPromise.then(function (db) {
        _deferReadiness(options);
        var dbContext = dbContexts[options.name];
        var forages = dbContext.forages;
        db.close();
        for (var i = 0; i < forages.length; i++) {
          var forage = forages[i];
          forage._dbInfo.db = null;
        }
        var dropDBPromise = new utils_promise(function (resolve, reject) {
          var req = utils_idb.deleteDatabase(options.name);
          req.onerror = function () {
            var db = req.result;
            if (db) {
              db.close();
            }
            reject(req.error);
          };
          req.onblocked = function () {
            // Closing all open connections in onversionchange handler should prevent this situation, but if
            // we do get here, it just means the request remains pending - eventually it will succeed or error
            console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
          };
          req.onsuccess = function () {
            var db = req.result;
            if (db) {
              db.close();
            }
            resolve(db);
          };
        });
        return dropDBPromise.then(function (db) {
          dbContext.db = db;
          for (var i = 0; i < forages.length; i++) {
            var _forage = forages[i];
            _advanceReadiness(_forage._dbInfo);
          }
        }).catch(function (err) {
          (_rejectReadiness(options, err) || utils_promise.resolve()).catch(function () {});
          throw err;
        });
      });
    } else {
      promise = dbPromise.then(function (db) {
        if (!db.objectStoreNames.contains(options.storeName)) {
          return;
        }
        var newVersion = db.version + 1;
        _deferReadiness(options);
        var dbContext = dbContexts[options.name];
        var forages = dbContext.forages;
        db.close();
        for (var i = 0; i < forages.length; i++) {
          var forage = forages[i];
          forage._dbInfo.db = null;
          forage._dbInfo.version = newVersion;
        }
        var dropObjectPromise = new utils_promise(function (resolve, reject) {
          var req = utils_idb.open(options.name, newVersion);
          req.onerror = function (err) {
            var db = req.result;
            db.close();
            reject(err);
          };
          req.onupgradeneeded = function () {
            var db = req.result;
            db.deleteObjectStore(options.storeName);
          };
          req.onsuccess = function () {
            var db = req.result;
            db.close();
            resolve(db);
          };
        });
        return dropObjectPromise.then(function (db) {
          dbContext.db = db;
          for (var j = 0; j < forages.length; j++) {
            var _forage2 = forages[j];
            _forage2._dbInfo.db = db;
            _advanceReadiness(_forage2._dbInfo);
          }
        }).catch(function (err) {
          (_rejectReadiness(options, err) || utils_promise.resolve()).catch(function () {});
          throw err;
        });
      });
    }
  }
  utils_executeCallback(promise, callback);
  return promise;
}
var asyncStorage = {
  _driver: 'asyncStorage',
  _initStorage: _initStorage,
  _support: utils_isIndexedDBValid(),
  iterate: iterate,
  getItem: getItem,
  setItem: setItem,
  removeItem: removeItem,
  clear: clear,
  length: indexeddb_length,
  key: key,
  keys: indexeddb_keys,
  dropInstance: dropInstance
};
/* harmony default export */ const indexeddb = (asyncStorage);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isWebSQLValid.js
function isWebSQLValid() {
  return typeof openDatabase === 'function';
}
/* harmony default export */ const utils_isWebSQLValid = (isWebSQLValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/serializer.js
/* eslint-disable no-bitwise */


// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;

// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var serializer_toString = Object.prototype.toString;
function stringToBuffer(serializedString) {
  // Fill the string into a ArrayBuffer.
  var bufferLength = serializedString.length * 0.75;
  var len = serializedString.length;
  var i;
  var p = 0;
  var encoded1, encoded2, encoded3, encoded4;
  if (serializedString[serializedString.length - 1] === '=') {
    bufferLength--;
    if (serializedString[serializedString.length - 2] === '=') {
      bufferLength--;
    }
  }
  var buffer = new ArrayBuffer(bufferLength);
  var bytes = new Uint8Array(buffer);
  for (i = 0; i < len; i += 4) {
    encoded1 = BASE_CHARS.indexOf(serializedString[i]);
    encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
    encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
    encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);

    /*jslint bitwise: true */
    bytes[p++] = encoded1 << 2 | encoded2 >> 4;
    bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
    bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  }
  return buffer;
}

// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
  // base64-arraybuffer
  var bytes = new Uint8Array(buffer);
  var base64String = '';
  var i;
  for (i = 0; i < bytes.length; i += 3) {
    /*jslint bitwise: true */
    base64String += BASE_CHARS[bytes[i] >> 2];
    base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
    base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
    base64String += BASE_CHARS[bytes[i + 2] & 63];
  }
  if (bytes.length % 3 === 2) {
    base64String = base64String.substring(0, base64String.length - 1) + '=';
  } else if (bytes.length % 3 === 1) {
    base64String = base64String.substring(0, base64String.length - 2) + '==';
  }
  return base64String;
}

// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
  var valueType = '';
  if (value) {
    valueType = serializer_toString.call(value);
  }

  // Cannot use `value instanceof ArrayBuffer` or such here, as these
  // checks fail when running the tests using casper.js...
  //
  // TODO: See why those tests fail and use a better solution.
  if (value && (valueType === '[object ArrayBuffer]' || value.buffer && serializer_toString.call(value.buffer) === '[object ArrayBuffer]')) {
    // Convert binary arrays to a string and prefix the string with
    // a special marker.
    var buffer;
    var marker = SERIALIZED_MARKER;
    if (value instanceof ArrayBuffer) {
      buffer = value;
      marker += TYPE_ARRAYBUFFER;
    } else {
      buffer = value.buffer;
      if (valueType === '[object Int8Array]') {
        marker += TYPE_INT8ARRAY;
      } else if (valueType === '[object Uint8Array]') {
        marker += TYPE_UINT8ARRAY;
      } else if (valueType === '[object Uint8ClampedArray]') {
        marker += TYPE_UINT8CLAMPEDARRAY;
      } else if (valueType === '[object Int16Array]') {
        marker += TYPE_INT16ARRAY;
      } else if (valueType === '[object Uint16Array]') {
        marker += TYPE_UINT16ARRAY;
      } else if (valueType === '[object Int32Array]') {
        marker += TYPE_INT32ARRAY;
      } else if (valueType === '[object Uint32Array]') {
        marker += TYPE_UINT32ARRAY;
      } else if (valueType === '[object Float32Array]') {
        marker += TYPE_FLOAT32ARRAY;
      } else if (valueType === '[object Float64Array]') {
        marker += TYPE_FLOAT64ARRAY;
      } else {
        callback(new Error('Failed to get type for BinaryArray'));
      }
    }
    callback(marker + bufferToString(buffer));
  } else if (valueType === '[object Blob]') {
    // Conver the blob to a binaryArray and then to a string.
    var fileReader = new FileReader();
    fileReader.onload = function () {
      // Backwards-compatible prefix for the blob type.
      var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
      callback(SERIALIZED_MARKER + TYPE_BLOB + str);
    };
    fileReader.readAsArrayBuffer(value);
  } else {
    try {
      callback(JSON.stringify(value));
    } catch (e) {
      console.error("Couldn't convert value into a JSON string: ", value);
      callback(null, e);
    }
  }
}

// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
  // If we haven't marked this string as being specially serialized (i.e.
  // something other than serialized JSON), we can just return it and be
  // done with it.
  if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
    return JSON.parse(value);
  }

  // The following code deals with deserializing some kind of Blob or
  // TypedArray. First we separate out the type of data we're dealing
  // with from the data itself.
  var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
  var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
  var blobType;
  // Backwards-compatible blob type serialization strategy.
  // DBs created with older versions of localForage will simply not have the blob type.
  if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
    var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
    blobType = matcher[1];
    serializedString = serializedString.substring(matcher[0].length);
  }
  var buffer = stringToBuffer(serializedString);

  // Return the right type based on the code/type set during
  // serialization.
  switch (type) {
    case TYPE_ARRAYBUFFER:
      return buffer;
    case TYPE_BLOB:
      return utils_createBlob([buffer], {
        type: blobType
      });
    case TYPE_INT8ARRAY:
      return new Int8Array(buffer);
    case TYPE_UINT8ARRAY:
      return new Uint8Array(buffer);
    case TYPE_UINT8CLAMPEDARRAY:
      return new Uint8ClampedArray(buffer);
    case TYPE_INT16ARRAY:
      return new Int16Array(buffer);
    case TYPE_UINT16ARRAY:
      return new Uint16Array(buffer);
    case TYPE_INT32ARRAY:
      return new Int32Array(buffer);
    case TYPE_UINT32ARRAY:
      return new Uint32Array(buffer);
    case TYPE_FLOAT32ARRAY:
      return new Float32Array(buffer);
    case TYPE_FLOAT64ARRAY:
      return new Float64Array(buffer);
    default:
      throw new Error('Unkown type: ' + type);
  }
}
var localforageSerializer = {
  serialize: serialize,
  deserialize: deserialize,
  stringToBuffer: stringToBuffer,
  bufferToString: bufferToString
};
/* harmony default export */ const serializer = (localforageSerializer);
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/websql.js







/*
 * Includes code from:
 *
 * base64-arraybuffer
 * https://github.com/niklasvh/base64-arraybuffer
 *
 * Copyright (c) 2012 Niklas von Hertzen
 * Licensed under the MIT license.
 */

function createDbTable(t, dbInfo, callback, errorCallback) {
  t.executeSql("CREATE TABLE IF NOT EXISTS ".concat(dbInfo.storeName, " ") + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}

// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function websql_initStorage(options) {
  var self = this;
  var dbInfo = {
    db: null
  };
  if (options) {
    for (var i in options) {
      dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
    }
  }
  var dbInfoPromise = new utils_promise(function (resolve, reject) {
    // Open the database; the openDatabase API will automatically
    // create it for us if it doesn't exist.
    try {
      dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
    } catch (e) {
      return reject(e);
    }

    // Create our key/value table if it doesn't exist.
    dbInfo.db.transaction(function (t) {
      createDbTable(t, dbInfo, function () {
        self._dbInfo = dbInfo;
        resolve();
      }, function (t, error) {
        reject(error);
      });
    }, reject);
  });
  dbInfo.serializer = serializer;
  return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
  t.executeSql(sqlStatement, args, callback, function (t, error) {
    if (error.code === error.SYNTAX_ERR) {
      t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
        if (!results.rows.length) {
          // if the table is missing (was deleted)
          // re-create it table and retry
          createDbTable(t, dbInfo, function () {
            t.executeSql(sqlStatement, args, callback, errorCallback);
          }, errorCallback);
        } else {
          errorCallback(t, error);
        }
      }, errorCallback);
    } else {
      errorCallback(t, error);
    }
  }, errorCallback);
}
function websql_getItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "SELECT * FROM ".concat(dbInfo.storeName, " WHERE key = ? LIMIT 1"), [key], function (t, results) {
          var result = results.rows.length ? results.rows.item(0).value : null;

          // Check to see if this is serialized content we need to
          // unpack.
          if (result) {
            result = dbInfo.serializer.deserialize(result);
          }
          resolve(result);
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function websql_iterate(iterator, callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "SELECT * FROM ".concat(dbInfo.storeName), [], function (t, results) {
          var rows = results.rows;
          var length = rows.length;
          for (var i = 0; i < length; i++) {
            var item = rows.item(i);
            var result = item.value;

            // Check to see if this is serialized content
            // we need to unpack.
            if (result) {
              result = dbInfo.serializer.deserialize(result);
            }
            result = iterator(result, item.key, i + 1);

            // void(0) prevents problems with redefinition
            // of `undefined`.
            if (result !== void 0) {
              resolve(result);
              return;
            }
          }
          resolve();
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function _setItem(key, value, callback, retriesLeft) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      // The localStorage API doesn't return undefined values in an
      // "expected" way, so undefined is always cast to null in all
      // drivers. See: https://github.com/mozilla/localForage/pull/42
      if (value === undefined) {
        value = null;
      }

      // Save the original value to pass to the callback.
      var originalValue = value;
      var dbInfo = self._dbInfo;
      dbInfo.serializer.serialize(value, function (value, error) {
        if (error) {
          reject(error);
        } else {
          dbInfo.db.transaction(function (t) {
            tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO ".concat(dbInfo.storeName, " ") + '(key, value) VALUES (?, ?)', [key, value], function () {
              resolve(originalValue);
            }, function (t, error) {
              reject(error);
            });
          }, function (sqlError) {
            // The transaction failed; check
            // to see if it's a quota error.
            if (sqlError.code === sqlError.QUOTA_ERR) {
              // We reject the callback outright for now, but
              // it's worth trying to re-run the transaction.
              // Even if the user accepts the prompt to use
              // more storage on Safari, this error will
              // be called.
              //
              // Try to re-run the transaction.
              if (retriesLeft > 0) {
                resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
                return;
              }
              reject(sqlError);
            }
          });
        }
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function websql_setItem(key, value, callback) {
  return _setItem.apply(this, [key, value, callback, 1]);
}
function websql_removeItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "DELETE FROM ".concat(dbInfo.storeName, " WHERE key = ?"), [key], function () {
          resolve();
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function websql_clear(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "DELETE FROM ".concat(dbInfo.storeName), [], function () {
          resolve();
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function websql_length(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        // Ahhh, SQL makes this one soooooo easy.
        tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM ".concat(dbInfo.storeName), [], function (t, results) {
          var result = results.rows.item(0).c;
          resolve(result);
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function websql_key(n, callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "SELECT key FROM ".concat(dbInfo.storeName, " WHERE id = ? LIMIT 1"), [n + 1], function (t, results) {
          var result = results.rows.length ? results.rows.item(0).key : null;
          resolve(result);
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function websql_keys(callback) {
  var self = this;
  var promise = new utils_promise(function (resolve, reject) {
    self.ready().then(function () {
      var dbInfo = self._dbInfo;
      dbInfo.db.transaction(function (t) {
        tryExecuteSql(t, dbInfo, "SELECT key FROM ".concat(dbInfo.storeName), [], function (t, results) {
          var keys = [];
          for (var i = 0; i < results.rows.length; i++) {
            keys.push(results.rows.item(i).key);
          }
          resolve(keys);
        }, function (t, error) {
          reject(error);
        });
      });
    }).catch(reject);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
  return new utils_promise(function (resolve, reject) {
    db.transaction(function (t) {
      t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
        var storeNames = [];
        for (var i = 0; i < results.rows.length; i++) {
          storeNames.push(results.rows.item(i).name);
        }
        resolve({
          db: db,
          storeNames: storeNames
        });
      }, function (t, error) {
        reject(error);
      });
    }, function (sqlError) {
      reject(sqlError);
    });
  });
}
function websql_dropInstance(options, callback) {
  callback = getCallback.apply(this, arguments);
  var currentConfig = this.config();
  options = typeof options !== 'function' && options || {};
  if (!options.name) {
    options.name = options.name || currentConfig.name;
    options.storeName = options.storeName || currentConfig.storeName;
  }
  var self = this;
  var promise;
  if (!options.name) {
    promise = utils_promise.reject('Invalid arguments');
  } else {
    promise = new utils_promise(function (resolve) {
      var db;
      if (options.name === currentConfig.name) {
        // use the db reference of the current instance
        db = self._dbInfo.db;
      } else {
        db = openDatabase(options.name, '', '', 0);
      }
      if (!options.storeName) {
        // drop all database tables
        resolve(getAllStoreNames(db));
      } else {
        resolve({
          db: db,
          storeNames: [options.storeName]
        });
      }
    }).then(function (operationInfo) {
      return new utils_promise(function (resolve, reject) {
        operationInfo.db.transaction(function (t) {
          function dropTable(storeName) {
            return new utils_promise(function (resolve, reject) {
              t.executeSql("DROP TABLE IF EXISTS ".concat(storeName), [], function () {
                resolve();
              }, function (t, error) {
                reject(error);
              });
            });
          }
          var operations = [];
          for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
            operations.push(dropTable(operationInfo.storeNames[i]));
          }
          utils_promise.all(operations).then(function () {
            resolve();
          }).catch(function (e) {
            reject(e);
          });
        }, function (sqlError) {
          reject(sqlError);
        });
      });
    });
  }
  utils_executeCallback(promise, callback);
  return promise;
}
var webSQLStorage = {
  _driver: 'webSQLStorage',
  _initStorage: websql_initStorage,
  _support: utils_isWebSQLValid(),
  iterate: websql_iterate,
  getItem: websql_getItem,
  setItem: websql_setItem,
  removeItem: websql_removeItem,
  clear: websql_clear,
  length: websql_length,
  key: websql_key,
  keys: websql_keys,
  dropInstance: websql_dropInstance
};
/* harmony default export */ const websql = (webSQLStorage);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isLocalStorageValid.js
function isLocalStorageValid() {
  try {
    return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
    // in IE8 typeof localStorage.setItem === 'object'
    !!localStorage.setItem;
  } catch (e) {
    return false;
  }
}
/* harmony default export */ const utils_isLocalStorageValid = (isLocalStorageValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/localstorage.js
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).







function _getKeyPrefix(options, defaultConfig) {
  var keyPrefix = options.name + '/';
  if (options.storeName !== defaultConfig.storeName) {
    keyPrefix += options.storeName + '/';
  }
  return keyPrefix;
}

// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
  var localStorageTestKey = '_localforage_support_test';
  try {
    localStorage.setItem(localStorageTestKey, true);
    localStorage.removeItem(localStorageTestKey);
    return false;
  } catch (e) {
    return true;
  }
}

// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
  return !checkIfLocalStorageThrows() || localStorage.length > 0;
}

// Config the localStorage backend, using options set in the config.
function localstorage_initStorage(options) {
  var self = this;
  var dbInfo = {};
  if (options) {
    for (var i in options) {
      dbInfo[i] = options[i];
    }
  }
  dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
  if (!_isLocalStorageUsable()) {
    return utils_promise.reject();
  }
  self._dbInfo = dbInfo;
  dbInfo.serializer = serializer;
  return utils_promise.resolve();
}

// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function localstorage_clear(callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var keyPrefix = self._dbInfo.keyPrefix;
    for (var i = localStorage.length - 1; i >= 0; i--) {
      var key = localStorage.key(i);
      if (key.indexOf(keyPrefix) === 0) {
        localStorage.removeItem(key);
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function localstorage_getItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = self.ready().then(function () {
    var dbInfo = self._dbInfo;
    var result = localStorage.getItem(dbInfo.keyPrefix + key);

    // If a result was found, parse it from the serialized
    // string into a JS object. If result isn't truthy, the key
    // is likely undefined and we'll pass it straight to the
    // callback.
    if (result) {
      result = dbInfo.serializer.deserialize(result);
    }
    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Iterate over all items in the store.
function localstorage_iterate(iterator, callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var dbInfo = self._dbInfo;
    var keyPrefix = dbInfo.keyPrefix;
    var keyPrefixLength = keyPrefix.length;
    var length = localStorage.length;

    // We use a dedicated iterator instead of the `i` variable below
    // so other keys we fetch in localStorage aren't counted in
    // the `iterationNumber` argument passed to the `iterate()`
    // callback.
    //
    // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
    var iterationNumber = 1;
    for (var i = 0; i < length; i++) {
      var key = localStorage.key(i);
      if (key.indexOf(keyPrefix) !== 0) {
        continue;
      }
      var value = localStorage.getItem(key);

      // If a result was found, parse it from the serialized
      // string into a JS object. If result isn't truthy, the
      // key is likely undefined and we'll pass it straight
      // to the iterator.
      if (value) {
        value = dbInfo.serializer.deserialize(value);
      }
      value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
      if (value !== void 0) {
        return value;
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Same as localStorage's key() method, except takes a callback.
function localstorage_key(n, callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var dbInfo = self._dbInfo;
    var result;
    try {
      result = localStorage.key(n);
    } catch (error) {
      result = null;
    }

    // Remove the prefix from the key, if a key is found.
    if (result) {
      result = result.substring(dbInfo.keyPrefix.length);
    }
    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function localstorage_keys(callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var dbInfo = self._dbInfo;
    var length = localStorage.length;
    var keys = [];
    for (var i = 0; i < length; i++) {
      var itemKey = localStorage.key(i);
      if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
        keys.push(itemKey.substring(dbInfo.keyPrefix.length));
      }
    }
    return keys;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Supply the number of keys in the datastore to the callback function.
function localstorage_length(callback) {
  var self = this;
  var promise = self.keys().then(function (keys) {
    return keys.length;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Remove an item from the store, nice and simple.
function localstorage_removeItem(key, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = self.ready().then(function () {
    var dbInfo = self._dbInfo;
    localStorage.removeItem(dbInfo.keyPrefix + key);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function localstorage_setItem(key, value, callback) {
  var self = this;
  key = normalizeKey(key);
  var promise = self.ready().then(function () {
    // Convert undefined values to null.
    // https://github.com/mozilla/localForage/pull/42
    if (value === undefined) {
      value = null;
    }

    // Save the original value to pass to the callback.
    var originalValue = value;
    return new utils_promise(function (resolve, reject) {
      var dbInfo = self._dbInfo;
      dbInfo.serializer.serialize(value, function (value, error) {
        if (error) {
          reject(error);
        } else {
          try {
            localStorage.setItem(dbInfo.keyPrefix + key, value);
            resolve(originalValue);
          } catch (e) {
            // localStorage capacity exceeded.
            // TODO: Make this a specific error/event.
            if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
              reject(e);
            }
            reject(e);
          }
        }
      });
    });
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function localstorage_dropInstance(options, callback) {
  callback = getCallback.apply(this, arguments);
  options = typeof options !== 'function' && options || {};
  if (!options.name) {
    var currentConfig = this.config();
    options.name = options.name || currentConfig.name;
    options.storeName = options.storeName || currentConfig.storeName;
  }
  var self = this;
  var promise;
  if (!options.name) {
    promise = utils_promise.reject('Invalid arguments');
  } else {
    promise = new utils_promise(function (resolve) {
      if (!options.storeName) {
        resolve("".concat(options.name, "/"));
      } else {
        resolve(_getKeyPrefix(options, self._defaultConfig));
      }
    }).then(function (keyPrefix) {
      for (var i = localStorage.length - 1; i >= 0; i--) {
        var key = localStorage.key(i);
        if (key.indexOf(keyPrefix) === 0) {
          localStorage.removeItem(key);
        }
      }
    });
  }
  utils_executeCallback(promise, callback);
  return promise;
}
var localStorageWrapper = {
  _driver: 'localStorageWrapper',
  _initStorage: localstorage_initStorage,
  _support: utils_isLocalStorageValid(),
  iterate: localstorage_iterate,
  getItem: localstorage_getItem,
  setItem: localstorage_setItem,
  removeItem: localstorage_removeItem,
  clear: localstorage_clear,
  length: localstorage_length,
  key: localstorage_key,
  keys: localstorage_keys,
  dropInstance: localstorage_dropInstance
};
/* harmony default export */ const localstorage = (localStorageWrapper);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/includes.js
var sameValue = function sameValue(x, y) {
  return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
  var len = array.length;
  var i = 0;
  while (i < len) {
    if (sameValue(array[i], searchElement)) {
      return true;
    }
    i++;
  }
  return false;
};
/* harmony default export */ const utils_includes = (includes);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isArray.js
var isArray_isArray = Array.isArray || function (arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
};
/* harmony default export */ const utils_isArray = (isArray_isArray);
;// CONCATENATED MODULE: ./node_modules/localforage/src/localforage.js
function localforage_typeof(obj) {
  "@babel/helpers - typeof";

  return localforage_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;
  }, localforage_typeof(obj);
}
function localforage_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function localforage_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, localforage_toPropertyKey(descriptor.key), descriptor);
  }
}
function localforage_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) localforage_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) localforage_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function localforage_toPropertyKey(arg) {
  var key = localforage_toPrimitive(arg, "string");
  return localforage_typeof(key) === "symbol" ? key : String(key);
}
function localforage_toPrimitive(input, hint) {
  if (localforage_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (localforage_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}










// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
  INDEXEDDB: indexeddb,
  WEBSQL: websql,
  LOCALSTORAGE: localstorage
};
var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
var OptionalDriverMethods = ['dropInstance'];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
var DefaultConfig = {
  description: '',
  driver: DefaultDriverOrder.slice(),
  name: 'localforage',
  // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
  // we can use without a prompt.
  size: 4980736,
  storeName: 'keyvaluepairs',
  version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
  localForageInstance[libraryMethod] = function () {
    var _args = arguments;
    return localForageInstance.ready().then(function () {
      return localForageInstance[libraryMethod].apply(localForageInstance, _args);
    });
  };
}
function extend() {
  for (var i = 1; i < arguments.length; i++) {
    var arg = arguments[i];
    if (arg) {
      for (var key in arg) {
        if (arg.hasOwnProperty(key)) {
          if (utils_isArray(arg[key])) {
            arguments[0][key] = arg[key].slice();
          } else {
            arguments[0][key] = arg[key];
          }
        }
      }
    }
  }
  return arguments[0];
}
var LocalForage = /*#__PURE__*/function () {
  function LocalForage(options) {
    localforage_classCallCheck(this, LocalForage);
    for (var driverTypeKey in DefaultDrivers) {
      if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
        var driver = DefaultDrivers[driverTypeKey];
        var driverName = driver._driver;
        this[driverTypeKey] = driverName;
        if (!DefinedDrivers[driverName]) {
          // we don't need to wait for the promise,
          // since the default drivers can be defined
          // in a blocking manner
          this.defineDriver(driver);
        }
      }
    }
    this._defaultConfig = extend({}, DefaultConfig);
    this._config = extend({}, this._defaultConfig, options);
    this._driverSet = null;
    this._initDriver = null;
    this._ready = false;
    this._dbInfo = null;
    this._wrapLibraryMethodsWithReady();
    this.setDriver(this._config.driver).catch(function () {});
  }

  // Set any config values for localForage; can be called anytime before
  // the first API call (e.g. `getItem`, `setItem`).
  // We loop through options so we don't overwrite existing config
  // values.
  localforage_createClass(LocalForage, [{
    key: "config",
    value: function config(options) {
      // If the options argument is an object, we use it to set values.
      // Otherwise, we return either a specified config value or all
      // config values.
      if (localforage_typeof(options) === 'object') {
        // If localforage is ready and fully initialized, we can't set
        // any new configuration values. Instead, we return an error.
        if (this._ready) {
          return new Error("Can't call config() after localforage " + 'has been used.');
        }
        for (var i in options) {
          if (i === 'storeName') {
            options[i] = options[i].replace(/\W/g, '_');
          }
          if (i === 'version' && typeof options[i] !== 'number') {
            return new Error('Database version must be a number.');
          }
          this._config[i] = options[i];
        }

        // after all config options are set and
        // the driver option is used, try setting it
        if ('driver' in options && options.driver) {
          return this.setDriver(this._config.driver);
        }
        return true;
      } else if (typeof options === 'string') {
        return this._config[options];
      } else {
        return this._config;
      }
    }

    // Used to define a custom driver, shared across all instances of
    // localForage.
  }, {
    key: "defineDriver",
    value: function defineDriver(driverObject, callback, errorCallback) {
      var promise = new utils_promise(function (resolve, reject) {
        try {
          var driverName = driverObject._driver;
          var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');

          // A driver name should be defined and not overlap with the
          // library-defined, default drivers.
          if (!driverObject._driver) {
            reject(complianceError);
            return;
          }
          var driverMethods = LibraryMethods.concat('_initStorage');
          for (var i = 0, len = driverMethods.length; i < len; i++) {
            var driverMethodName = driverMethods[i];

            // when the property is there,
            // it should be a method even when optional
            var isRequired = !utils_includes(OptionalDriverMethods, driverMethodName);
            if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
              reject(complianceError);
              return;
            }
          }
          var configureMissingMethods = function configureMissingMethods() {
            var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
              return function () {
                var error = new Error("Method ".concat(methodName, " is not implemented by the current driver"));
                var promise = utils_promise.reject(error);
                utils_executeCallback(promise, arguments[arguments.length - 1]);
                return promise;
              };
            };
            for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
              var optionalDriverMethod = OptionalDriverMethods[_i];
              if (!driverObject[optionalDriverMethod]) {
                driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
              }
            }
          };
          configureMissingMethods();
          var setDriverSupport = function setDriverSupport(support) {
            if (DefinedDrivers[driverName]) {
              console.info("Redefining LocalForage driver: ".concat(driverName));
            }
            DefinedDrivers[driverName] = driverObject;
            DriverSupport[driverName] = support;
            // don't use a then, so that we can define
            // drivers that have simple _support methods
            // in a blocking manner
            resolve();
          };
          if ('_support' in driverObject) {
            if (driverObject._support && typeof driverObject._support === 'function') {
              driverObject._support().then(setDriverSupport, reject);
            } else {
              setDriverSupport(!!driverObject._support);
            }
          } else {
            setDriverSupport(true);
          }
        } catch (e) {
          reject(e);
        }
      });
      utils_executeTwoCallbacks(promise, callback, errorCallback);
      return promise;
    }
  }, {
    key: "driver",
    value: function driver() {
      return this._driver || null;
    }
  }, {
    key: "getDriver",
    value: function getDriver(driverName, callback, errorCallback) {
      var getDriverPromise = DefinedDrivers[driverName] ? utils_promise.resolve(DefinedDrivers[driverName]) : utils_promise.reject(new Error('Driver not found.'));
      utils_executeTwoCallbacks(getDriverPromise, callback, errorCallback);
      return getDriverPromise;
    }
  }, {
    key: "getSerializer",
    value: function getSerializer(callback) {
      var serializerPromise = utils_promise.resolve(serializer);
      utils_executeTwoCallbacks(serializerPromise, callback);
      return serializerPromise;
    }
  }, {
    key: "ready",
    value: function ready(callback) {
      var self = this;
      var promise = self._driverSet.then(function () {
        if (self._ready === null) {
          self._ready = self._initDriver();
        }
        return self._ready;
      });
      utils_executeTwoCallbacks(promise, callback, callback);
      return promise;
    }
  }, {
    key: "setDriver",
    value: function setDriver(drivers, callback, errorCallback) {
      var self = this;
      if (!utils_isArray(drivers)) {
        drivers = [drivers];
      }
      var supportedDrivers = this._getSupportedDrivers(drivers);
      function setDriverToConfig() {
        self._config.driver = self.driver();
      }
      function extendSelfWithDriver(driver) {
        self._extend(driver);
        setDriverToConfig();
        self._ready = self._initStorage(self._config);
        return self._ready;
      }
      function initDriver(supportedDrivers) {
        return function () {
          var currentDriverIndex = 0;
          function driverPromiseLoop() {
            while (currentDriverIndex < supportedDrivers.length) {
              var driverName = supportedDrivers[currentDriverIndex];
              currentDriverIndex++;
              self._dbInfo = null;
              self._ready = null;
              return self.getDriver(driverName).then(extendSelfWithDriver).catch(driverPromiseLoop);
            }
            setDriverToConfig();
            var error = new Error('No available storage method found.');
            self._driverSet = utils_promise.reject(error);
            return self._driverSet;
          }
          return driverPromiseLoop();
        };
      }

      // There might be a driver initialization in progress
      // so wait for it to finish in order to avoid a possible
      // race condition to set _dbInfo
      var oldDriverSetDone = this._driverSet !== null ? this._driverSet.catch(function () {
        return utils_promise.resolve();
      }) : utils_promise.resolve();
      this._driverSet = oldDriverSetDone.then(function () {
        var driverName = supportedDrivers[0];
        self._dbInfo = null;
        self._ready = null;
        return self.getDriver(driverName).then(function (driver) {
          self._driver = driver._driver;
          setDriverToConfig();
          self._wrapLibraryMethodsWithReady();
          self._initDriver = initDriver(supportedDrivers);
        });
      }).catch(function () {
        setDriverToConfig();
        var error = new Error('No available storage method found.');
        self._driverSet = utils_promise.reject(error);
        return self._driverSet;
      });
      utils_executeTwoCallbacks(this._driverSet, callback, errorCallback);
      return this._driverSet;
    }
  }, {
    key: "supports",
    value: function supports(driverName) {
      return !!DriverSupport[driverName];
    }
  }, {
    key: "_extend",
    value: function _extend(libraryMethodsAndProperties) {
      extend(this, libraryMethodsAndProperties);
    }
  }, {
    key: "_getSupportedDrivers",
    value: function _getSupportedDrivers(drivers) {
      var supportedDrivers = [];
      for (var i = 0, len = drivers.length; i < len; i++) {
        var driverName = drivers[i];
        if (this.supports(driverName)) {
          supportedDrivers.push(driverName);
        }
      }
      return supportedDrivers;
    }
  }, {
    key: "_wrapLibraryMethodsWithReady",
    value: function _wrapLibraryMethodsWithReady() {
      // Add a stub for each driver API method that delays the call to the
      // corresponding driver method until localForage is ready. These stubs
      // will be replaced by the driver methods as soon as the driver is
      // loaded, so there is no performance impact.
      for (var i = 0, len = LibraryMethods.length; i < len; i++) {
        callWhenReady(this, LibraryMethods[i]);
      }
    }
  }, {
    key: "createInstance",
    value: function createInstance(options) {
      return new LocalForage(options);
    }
  }]);
  return LocalForage;
}(); // The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
/* harmony default export */ const localforage = (new LocalForage());
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assignMergeValue.js



/**
 * This function is like `assignValue` except that it doesn't assign
 * `undefined` values.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignMergeValue(object, key, value) {
  if (value !== undefined && !lodash_es_eq(object[key], value) || value === undefined && !(key in object)) {
    _baseAssignValue(object, key, value);
  }
}
/* harmony default export */ const _assignMergeValue = (assignMergeValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLikeObject.js



/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return lodash_es_isObjectLike(value) && lodash_es_isArrayLike(value);
}
/* harmony default export */ const lodash_es_isArrayLikeObject = (isArrayLikeObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_safeGet.js
/**
 * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function safeGet(object, key) {
  if (key === 'constructor' && typeof object[key] === 'function') {
    return;
  }
  if (key == '__proto__') {
    return;
  }
  return object[key];
}
/* harmony default export */ const _safeGet = (safeGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toPlainObject.js



/**
 * Converts `value` to a plain object flattening inherited enumerable string
 * keyed properties of `value` to own properties of the plain object.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {Object} Returns the converted plain object.
 * @example
 *
 * function Foo() {
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.assign({ 'a': 1 }, new Foo);
 * // => { 'a': 1, 'b': 2 }
 *
 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
 * // => { 'a': 1, 'b': 2, 'c': 3 }
 */
function toPlainObject(value) {
  return _copyObject(value, lodash_es_keysIn(value));
}
/* harmony default export */ const lodash_es_toPlainObject = (toPlainObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMergeDeep.js
















/**
 * A specialized version of `baseMerge` for arrays and objects which performs
 * deep merges and tracks traversed objects enabling objects with circular
 * references to be merged.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {string} key The key of the value to merge.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} mergeFunc The function to merge values.
 * @param {Function} [customizer] The function to customize assigned values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  var objValue = _safeGet(object, key),
    srcValue = _safeGet(source, key),
    stacked = stack.get(srcValue);
  if (stacked) {
    _assignMergeValue(object, key, stacked);
    return;
  }
  var newValue = customizer ? customizer(objValue, srcValue, key + '', object, source, stack) : undefined;
  var isCommon = newValue === undefined;
  if (isCommon) {
    var isArr = lodash_es_isArray(srcValue),
      isBuff = !isArr && lodash_es_isBuffer(srcValue),
      isTyped = !isArr && !isBuff && lodash_es_isTypedArray(srcValue);
    newValue = srcValue;
    if (isArr || isBuff || isTyped) {
      if (lodash_es_isArray(objValue)) {
        newValue = objValue;
      } else if (lodash_es_isArrayLikeObject(objValue)) {
        newValue = _copyArray(objValue);
      } else if (isBuff) {
        isCommon = false;
        newValue = _cloneBuffer(srcValue, true);
      } else if (isTyped) {
        isCommon = false;
        newValue = _cloneTypedArray(srcValue, true);
      } else {
        newValue = [];
      }
    } else if (lodash_es_isPlainObject(srcValue) || lodash_es_isArguments(srcValue)) {
      newValue = objValue;
      if (lodash_es_isArguments(objValue)) {
        newValue = lodash_es_toPlainObject(objValue);
      } else if (!lodash_es_isObject(objValue) || lodash_es_isFunction(objValue)) {
        newValue = _initCloneObject(srcValue);
      }
    } else {
      isCommon = false;
    }
  }
  if (isCommon) {
    // Recursively merge objects and arrays (susceptible to call stack limits).
    stack.set(srcValue, newValue);
    mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
    stack['delete'](srcValue);
  }
  _assignMergeValue(object, key, newValue);
}
/* harmony default export */ const _baseMergeDeep = (baseMergeDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMerge.js








/**
 * The base implementation of `_.merge` without support for multiple sources.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} [customizer] The function to customize merged values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMerge(object, source, srcIndex, customizer, stack) {
  if (object === source) {
    return;
  }
  _baseFor(source, function (srcValue, key) {
    stack || (stack = new _Stack());
    if (lodash_es_isObject(srcValue)) {
      _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
    } else {
      var newValue = customizer ? customizer(_safeGet(object, key), srcValue, key + '', object, source, stack) : undefined;
      if (newValue === undefined) {
        newValue = srcValue;
      }
      _assignMergeValue(object, key, newValue);
    }
  }, lodash_es_keysIn);
}
/* harmony default export */ const _baseMerge = (baseMerge);
;// CONCATENATED MODULE: ./node_modules/lodash-es/merge.js



/**
 * This method is like `_.assign` except that it recursively merges own and
 * inherited enumerable string keyed properties of source objects into the
 * destination object. Source properties that resolve to `undefined` are
 * skipped if a destination value exists. Array and plain object properties
 * are merged recursively. Other objects and value types are overridden by
 * assignment. Source objects are applied from left to right. Subsequent
 * sources overwrite property assignments of previous sources.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @example
 *
 * var object = {
 *   'a': [{ 'b': 2 }, { 'd': 4 }]
 * };
 *
 * var other = {
 *   'a': [{ 'c': 3 }, { 'e': 5 }]
 * };
 *
 * _.merge(object, other);
 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
 */
var merge = _createAssigner(function (object, source, srcIndex) {
  _baseMerge(object, source, srcIndex);
});
/* harmony default export */ const lodash_es_merge = (merge);
;// CONCATENATED MODULE: ./node_modules/lodash-es/mergeWith.js



/**
 * This method is like `_.merge` except that it accepts `customizer` which
 * is invoked to produce the merged values of the destination and source
 * properties. If `customizer` returns `undefined`, merging is handled by the
 * method instead. The `customizer` is invoked with six arguments:
 * (objValue, srcValue, key, object, source, stack).
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} sources The source objects.
 * @param {Function} customizer The function to customize assigned values.
 * @returns {Object} Returns `object`.
 * @example
 *
 * function customizer(objValue, srcValue) {
 *   if (_.isArray(objValue)) {
 *     return objValue.concat(srcValue);
 *   }
 * }
 *
 * var object = { 'a': [1], 'b': [2] };
 * var other = { 'a': [3], 'b': [4] };
 *
 * _.mergeWith(object, other, customizer);
 * // => { 'a': [1, 3], 'b': [2, 4] }
 */
var mergeWith = _createAssigner(function (object, source, srcIndex, customizer) {
  _baseMerge(object, source, srcIndex, customizer);
});
/* harmony default export */ const lodash_es_mergeWith = (mergeWith);
;// CONCATENATED MODULE: ./node_modules/lodash-es/now.js


/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */
var now = function now() {
  return _root.Date.now();
};
/* harmony default export */ const lodash_es_now = (now);
;// CONCATENATED MODULE: ./node_modules/mergebounce/mergebounce.js







/** Error message constants. */
var mergebounce_FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var mergebounce_nativeMax = Math.max;
var nativeMin = Math.min;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 *
 * This function differs from lodash's debounce by merging all passed objects
 * before passing them to the final invoked function.
 *
 * Because of this, invoking can only happen on the trailing edge, since
 * passed-in data would be discarded if invoking happened on the leading edge.
 *
 * If `wait` is `0`, `func` invocation is deferred until to the next tick,
 * similar to `setTimeout` with a timeout of `0`.
 *
 * @static
 * @category Function
 * @param {Function} func The function to mergebounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.concatArrays=false]
 *  By default arrays will be treated as objects when being merged. When
 *  merging two arrays, the values in the 2nd arrray will replace the
 *  corresponding values (i.e. those with the same indexes) in the first array.
 *  When `concatArrays` is set to `true`, arrays will be concatenated instead.
 * @param {boolean} [options.dedupeArrays=false]
 *  This option is similar to `concatArrays`, except that the concatenated
 *  array will also be deduplicated. Thus any entries that are concatenated to the
 *  existing array, which are already contained in the existing array, will
 *  first be removed.
 * @param {boolean} [options.promise=false]
 *  By default, when calling a merge-debounced function that doesn't execute
 *  immediately, you'll receive the result from its previous execution, or
 *  `undefined` if it has never executed before. By setting the `promise`
 *  option to `true`, a promise will be returned instead of the previous
 *  execution result when the function is debounced. The promise will resolve
 *  with the result of the next execution, as soon as it happens.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * window.addEventListener('resize', mergebounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * element.addEventListner('click', mergebounce(sendMail, 300));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * const mergebounced = mergebounce(batchLog, 250, { 'maxWait': 1000 });
 * const source = new EventSource('/stream');
 * jQuery(source).on('message', mergebounced);
 *
 * // Cancel the trailing debounced invocation.
 * window.addEventListener('popstate', mergebounced.cancel);
 */
function mergebounce(func, wait) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var lastArgs,
    lastThis,
    maxWait,
    result,
    timerId,
    lastCallTime,
    lastInvokeTime = 0,
    maxing = false;
  var promise = options.promise ? getOpenPromise() : null;
  if (typeof func != 'function') {
    throw new TypeError(mergebounce_FUNC_ERROR_TEXT);
  }
  wait = lodash_es_toNumber(wait) || 0;
  if (lodash_es_isObject(options)) {
    maxing = 'maxWait' in options;
    maxWait = maxing ? mergebounce_nativeMax(lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
  }
  function invokeFunc(time) {
    var args = lastArgs;
    var thisArg = lastThis;
    var existingPromise = promise;
    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    if (options.promise) {
      existingPromise.resolve(result);
      promise = getOpenPromise();
    }
    return options.promise ? existingPromise : result;
  }
  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time;
    // Start the timer for the trailing edge.
    timerId = setTimeout(timerExpired, wait);
    return options.promise ? promise : result;
  }
  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime;
    var timeSinceLastInvoke = time - lastInvokeTime;
    var timeWaiting = wait - timeSinceLastCall;
    return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
  }
  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime;
    var timeSinceLastInvoke = time - lastInvokeTime;

    // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.
    return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  }
  function timerExpired() {
    var time = lodash_es_now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // Restart the timer.
    timerId = setTimeout(timerExpired, remainingWait(time));
  }
  function trailingEdge(time) {
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;
    return options.promise ? promise : result;
  }
  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }
  function flush() {
    return timerId === undefined ? result : trailingEdge(lodash_es_now());
  }
  function concatArrays(objValue, srcValue) {
    if (Array.isArray(objValue) && Array.isArray(srcValue)) {
      if (options !== null && options !== void 0 && options.dedupeArrays) {
        return objValue.concat(srcValue.filter(function (i) {
          return objValue.indexOf(i) === -1;
        }));
      } else {
        return objValue.concat(srcValue);
      }
    }
  }
  function mergeArguments(args) {
    var _lastArgs;
    if ((_lastArgs = lastArgs) !== null && _lastArgs !== void 0 && _lastArgs.length) {
      if (!args.length) {
        return lastArgs;
      }
      if (options !== null && options !== void 0 && options.concatArrays || options !== null && options !== void 0 && options.dedupeArrays) {
        return lodash_es_mergeWith(lastArgs, args, concatArrays);
      } else {
        return lodash_es_merge(lastArgs, args);
      }
    } else {
      return args || [];
    }
  }
  function debounced() {
    var time = lodash_es_now();
    var isInvoking = shouldInvoke(time);
    lastArgs = mergeArguments(Array.from(arguments));
    lastThis = this;
    lastCallTime = time;
    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return options.promise ? promise : result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}
/* harmony default export */ const mergebounce_mergebounce = (mergebounce);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/drivers/sessionStorage.js
function sessionStorage_typeof(obj) {
  "@babel/helpers - typeof";

  return sessionStorage_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;
  }, sessionStorage_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" == sessionStorage_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);
    });
  };
}
// Copyright 2014 Mozilla
// Copyright 2015 Thodoris Greasidis
// Copyright 2018 JC Brand
//
// 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 sessionStorage_serialize = serializer["serialize"];
var sessionStorage_deserialize = serializer["deserialize"];
function isSessionStorageValid() {
  // If the app is running inside a Google Chrome packaged webapp, or some
  // other context where sessionStorage isn't available, we don't use
  // sessionStorage. This feature detection is preferred over the old
  // `if (window.chrome && window.chrome.runtime)` code.
  // See: https://github.com/mozilla/localForage/issues/68
  try {
    // If sessionStorage isn't available, we get outta here!
    // This should be inside a try catch
    if (sessionStorage && 'setItem' in sessionStorage) {
      return true;
    }
  } catch (e) {
    console.log(e);
  }
  return false;
}
function sessionStorage_getKeyPrefix(options, defaultConfig) {
  var keyPrefix = options.name + '/';
  if (options.storeName !== defaultConfig.storeName) {
    keyPrefix += options.storeName + '/';
  }
  return keyPrefix;
}
var dbInfo = {
  'serializer': {
    'serialize': sessionStorage_serialize,
    'deserialize': sessionStorage_deserialize
  }
};
function sessionStorage_initStorage(options) {
  dbInfo.keyPrefix = sessionStorage_getKeyPrefix(options, this._defaultConfig);
  if (options) {
    for (var i in options) {
      // eslint-disable-line guard-for-in
      dbInfo[i] = options[i];
    }
  }
}

// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function sessionStorage_clear(callback) {
  var promise = this.ready().then(function () {
    var keyPrefix = dbInfo.keyPrefix;
    for (var i = sessionStorage.length - 1; i >= 0; i--) {
      var _key = sessionStorage.key(i);
      if (_key.indexOf(keyPrefix) === 0) {
        sessionStorage.removeItem(_key);
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function sessionStorage_getItem(key, callback) {
  key = normalizeKey(key);
  var promise = this.ready().then(function () {
    var result = sessionStorage.getItem(dbInfo.keyPrefix + key);
    // If a result was found, parse it from the serialized
    // string into a JS object. If result isn't truthy, the key
    // is likely undefined and we'll pass it straight to the
    // callback.
    if (result) {
      result = dbInfo.serializer.deserialize(result);
    }
    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Iterate over all items in the store.
function sessionStorage_iterate(iterator, callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var keyPrefix = dbInfo.keyPrefix;
    var keyPrefixLength = keyPrefix.length;
    var length = sessionStorage.length;

    // We use a dedicated iterator instead of the `i` variable below
    // so other keys we fetch in sessionStorage aren't counted in
    // the `iterationNumber` argument passed to the `iterate()`
    // callback.
    //
    // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
    var iterationNumber = 1;
    for (var i = 0; i < length; i++) {
      var _key2 = sessionStorage.key(i);
      if (_key2.indexOf(keyPrefix) !== 0) {
        continue;
      }
      var value = sessionStorage.getItem(_key2);

      // If a result was found, parse it from the serialized
      // string into a JS object. If result isn't truthy, the
      // key is likely undefined and we'll pass it straight
      // to the iterator.
      if (value) {
        value = dbInfo.serializer.deserialize(value);
      }
      value = iterator(value, _key2.substring(keyPrefixLength), iterationNumber++);
      if (value !== void 0) {
        // eslint-disable-line no-void
        return value;
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Same as sessionStorage's key() method, except takes a callback.
function sessionStorage_key(n, callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var result;
    try {
      result = sessionStorage.key(n);
    } catch (error) {
      result = null;
    }

    // Remove the prefix from the key, if a key is found.
    if (result) {
      result = result.substring(dbInfo.keyPrefix.length);
    }
    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
}
function sessionStorage_keys(callback) {
  var self = this;
  var promise = self.ready().then(function () {
    var length = sessionStorage.length;
    var keys = [];
    for (var i = 0; i < length; i++) {
      var itemKey = sessionStorage.key(i);
      if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
        keys.push(itemKey.substring(dbInfo.keyPrefix.length));
      }
    }
    return keys;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Supply the number of keys in the datastore to the callback function.
function sessionStorage_length(callback) {
  var self = this;
  var promise = self.keys().then(function (keys) {
    return keys.length;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Remove an item from the store, nice and simple.
function sessionStorage_removeItem(key, callback) {
  key = normalizeKey(key);
  var promise = this.ready().then(function () {
    sessionStorage.removeItem(dbInfo.keyPrefix + key);
  });
  utils_executeCallback(promise, callback);
  return promise;
}

// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function sessionStorage_setItem(_x, _x2, _x3) {
  return drivers_sessionStorage_setItem.apply(this, arguments);
}
function drivers_sessionStorage_setItem() {
  drivers_sessionStorage_setItem = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(key, value, callback) {
    var _value;
    var originalValue;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          key = normalizeKey(key);
          _context.next = 3;
          return this.ready();
        case 3:
          // Convert undefined values to null.
          // https://github.com/mozilla/localForage/pull/42
          value = (_value = value) !== null && _value !== void 0 ? _value : null;

          // Save the original value to pass to the callback.
          originalValue = value;
          dbInfo.serializer.serialize(value, function (value, error) {
            if (error) {
              throw error;
            } else {
              try {
                sessionStorage.setItem(dbInfo.keyPrefix + key, value);
                utils_executeCallback(Promise.resolve(originalValue), callback);
              } catch (e) {
                if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                  console.error("Your sesionStorage capacity is used up.");
                  throw e;
                }
                throw e;
              }
            }
          });
        case 6:
        case "end":
          return _context.stop();
      }
    }, _callee, this);
  }));
  return drivers_sessionStorage_setItem.apply(this, arguments);
}
function sessionStorage_dropInstance(options, callback) {
  callback = getCallback.apply(this, arguments);
  options = typeof options !== 'function' && options || {};
  if (!options.name) {
    var currentConfig = this.config();
    options.name = options.name || currentConfig.name;
    options.storeName = options.storeName || currentConfig.storeName;
  }
  var self = this;
  var promise;
  if (!options.name) {
    promise = Promise.reject(new Error('Invalid arguments'));
  } else {
    promise = new Promise(function (resolve) {
      if (!options.storeName) {
        resolve("".concat(options.name, "/"));
      } else {
        resolve(sessionStorage_getKeyPrefix(options, self._defaultConfig));
      }
    }).then(function (keyPrefix) {
      for (var i = sessionStorage.length - 1; i >= 0; i--) {
        var _key3 = sessionStorage.key(i);
        if (_key3.indexOf(keyPrefix) === 0) {
          sessionStorage.removeItem(_key3);
        }
      }
    });
  }
  utils_executeCallback(promise, callback);
  return promise;
}
var sessionStorageWrapper = {
  _driver: 'sessionStorageWrapper',
  _initStorage: sessionStorage_initStorage,
  _support: isSessionStorageValid(),
  iterate: sessionStorage_iterate,
  getItem: sessionStorage_getItem,
  setItem: sessionStorage_setItem,
  removeItem: sessionStorage_removeItem,
  clear: sessionStorage_clear,
  length: sessionStorage_length,
  key: sessionStorage_key,
  keys: sessionStorage_keys,
  dropInstance: sessionStorage_dropInstance
};
/* harmony default export */ const drivers_sessionStorage = (sessionStorageWrapper);
// EXTERNAL MODULE: ./node_modules/localforage-setitems/dist/localforage-setitems.js
var localforage_setitems = __webpack_require__(829);
// EXTERNAL MODULE: ./node_modules/@converse/localforage-getitems/dist/localforage-getitems.js
var localforage_getitems = __webpack_require__(5246);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/storage.js
function storage_typeof(obj) {
  "@babel/helpers - typeof";

  return storage_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;
  }, storage_typeof(obj);
}
function storage_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  storage_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" == storage_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 storage_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 storage_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        storage_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        storage_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function storage_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function storage_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, storage_toPropertyKey(descriptor.key), descriptor);
  }
}
function storage_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) storage_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) storage_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function storage_toPropertyKey(arg) {
  var key = storage_toPrimitive(arg, "string");
  return storage_typeof(key) === "symbol" ? key : String(key);
}
function storage_toPrimitive(input, hint) {
  if (storage_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (storage_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/**
 * IndexedDB, localStorage and sessionStorage adapter
 */









var IN_MEMORY = umd._driver;
localforage.defineDriver(umd);
(0,localforage_setitems.extendPrototype)(localforage);
(0,localforage_getitems.extendPrototype)(localforage);
var Storage = /*#__PURE__*/function () {
  function Storage(id, type) {
    var _this = this;
    var batchedWrites = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    storage_classCallCheck(this, Storage);
    if (type === 'local' && !window.localStorage) {
      throw new Error("Skeletor.storage: Environment does not support localStorage.");
    } else if (type === 'session' && !window.sessionStorage) {
      throw new Error("Skeletor.storage: Environment does not support sessionStorage.");
    }
    if (lodash_es_isString(type)) {
      this.storeInitialized = this.initStore(type, batchedWrites);
    } else {
      this.store = type;
      if (batchedWrites) {
        this.store.debouncedSetItems = mergebounce_mergebounce(function (items) {
          return _this.store.setItems(items);
        }, 50, {
          'promise': true
        });
      }
      this.storeInitialized = Promise.resolve();
    }
    this.name = id;
  }
  storage_createClass(Storage, [{
    key: "initStore",
    value: function () {
      var _initStore = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee(type, batchedWrites) {
        var _this2 = this;
        return storage_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!(type === 'session')) {
                _context.next = 4;
                break;
              }
              localforage.setDriver(drivers_sessionStorage._driver);
              _context.next = 15;
              break;
            case 4:
              if (!(type === 'local')) {
                _context.next = 9;
                break;
              }
              _context.next = 7;
              return localforage.config({
                'driver': localforage.LOCALSTORAGE
              });
            case 7:
              _context.next = 15;
              break;
            case 9:
              if (!(type === 'in_memory')) {
                _context.next = 13;
                break;
              }
              localforage.config({
                'driver': IN_MEMORY
              });
              _context.next = 15;
              break;
            case 13:
              if (!(type !== 'indexed')) {
                _context.next = 15;
                break;
              }
              throw new Error("Skeletor.storage: No storage type was specified");
            case 15:
              this.store = localforage;
              if (batchedWrites) {
                this.store.debouncedSetItems = mergebounce_mergebounce(function (items) {
                  return _this2.store.setItems(items);
                }, 50, {
                  'promise': true
                });
              }
            case 17:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initStore(_x, _x2) {
        return _initStore.apply(this, arguments);
      }
      return initStore;
    }()
  }, {
    key: "flush",
    value: function flush() {
      var _this$store$debounced;
      return (_this$store$debounced = this.store.debouncedSetItems) === null || _this$store$debounced === void 0 ? void 0 : _this$store$debounced.flush();
    }
  }, {
    key: "clear",
    value: function () {
      var _clear = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee2() {
        var _this3 = this;
        var re, keys, removed_keys;
        return storage_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return this.store.removeItem(this.name).catch(function (e) {
                return console.error(e);
              });
            case 2:
              re = new RegExp("^".concat(this.name, "-"));
              _context2.next = 5;
              return this.store.keys();
            case 5:
              keys = _context2.sent;
              removed_keys = keys.filter(function (k) {
                return re.test(k);
              });
              _context2.next = 9;
              return Promise.all(removed_keys.map(function (k) {
                return _this3.store.removeItem(k).catch(function (e) {
                  return console.error(e);
                });
              }));
            case 9:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function clear() {
        return _clear.apply(this, arguments);
      }
      return clear;
    }()
  }, {
    key: "sync",
    value: function sync() {
      var that = this;
      function localSync(_x3, _x4, _x5) {
        return _localSync.apply(this, arguments);
      }
      function _localSync() {
        _localSync = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee3(method, model, options) {
          var resp, errorMessage, promise, new_attributes, collection, original_attributes, data;
          return storage_regeneratorRuntime().wrap(function _callee3$(_context3) {
            while (1) switch (_context3.prev = _context3.next) {
              case 0:
                // We get the collection (and if necessary the model attribute.
                // Waiting for storeInitialized will cause another iteration of
                // the event loop, after which the collection reference will
                // be removed from the model.
                collection = model.collection;
                if (['patch', 'update'].includes(method)) {
                  new_attributes = lodash_es_cloneDeep(model.attributes);
                }
                _context3.next = 4;
                return that.storeInitialized;
              case 4:
                _context3.prev = 4;
                original_attributes = model.attributes;
                _context3.t0 = method;
                _context3.next = _context3.t0 === "read" ? 9 : _context3.t0 === "create" ? 19 : _context3.t0 === 'patch' ? 23 : _context3.t0 === "update" ? 23 : _context3.t0 === "delete" ? 30 : 34;
                break;
              case 9:
                if (!(model.id !== undefined)) {
                  _context3.next = 15;
                  break;
                }
                _context3.next = 12;
                return that.find(model);
              case 12:
                resp = _context3.sent;
                _context3.next = 18;
                break;
              case 15:
                _context3.next = 17;
                return that.findAll();
              case 17:
                resp = _context3.sent;
              case 18:
                return _context3.abrupt("break", 34);
              case 19:
                _context3.next = 21;
                return that.create(model, options);
              case 21:
                resp = _context3.sent;
                return _context3.abrupt("break", 34);
              case 23:
                if (options.wait) {
                  // When `wait` is set to true, Skeletor waits until
                  // confirmation of storage before setting the values on
                  // the model.
                  // However, the new attributes needs to be sent, so it
                  // sets them manually on the model and then removes
                  // them after calling `sync`.
                  // Because our `sync` method is asynchronous and we
                  // wait for `storeInitialized`, the attributes are
                  // already restored once we get here, so we need to do
                  // the attributes dance again.
                  model.attributes = new_attributes;
                }
                promise = that.update(model, options);
                if (options.wait) {
                  model.attributes = original_attributes;
                }
                _context3.next = 28;
                return promise;
              case 28:
                resp = _context3.sent;
                return _context3.abrupt("break", 34);
              case 30:
                _context3.next = 32;
                return that.destroy(model, collection);
              case 32:
                resp = _context3.sent;
                return _context3.abrupt("break", 34);
              case 34:
                _context3.next = 39;
                break;
              case 36:
                _context3.prev = 36;
                _context3.t1 = _context3["catch"](4);
                if (_context3.t1.code === 22 && that.getStorageSize() === 0) {
                  errorMessage = "Private browsing is unsupported";
                } else {
                  errorMessage = _context3.t1.message;
                }
              case 39:
                if (resp) {
                  if (options && options.success) {
                    // When storing, we don't pass back the response (which is
                    // the set attributes returned from localforage because
                    // Skeletor sets them again on the model and due to the async
                    // nature of localforage it can cause stale attributes to be
                    // set on a model after it's been updated in the meantime.
                    data = method === "read" ? resp : null;
                    options.success(data, options);
                  }
                } else {
                  errorMessage = errorMessage ? errorMessage : "Record Not Found";
                  if (options && options.error) {
                    options.error(errorMessage);
                  }
                }
              case 40:
              case "end":
                return _context3.stop();
            }
          }, _callee3, null, [[4, 36]]);
        }));
        return _localSync.apply(this, arguments);
      }
      localSync.__name__ = 'localSync';
      return localSync;
    }
  }, {
    key: "removeCollectionReference",
    value: function removeCollectionReference(model, collection) {
      var _this4 = this;
      if (!collection) {
        return;
      }
      var ids = collection.filter(function (m) {
        return m.id !== model.id;
      }).map(function (m) {
        return _this4.getItemName(m.id);
      });
      return this.store.setItem(this.name, ids);
    }
  }, {
    key: "addCollectionReference",
    value: function addCollectionReference(model, collection) {
      var _this5 = this;
      if (!collection) {
        return;
      }
      var ids = collection.map(function (m) {
        return _this5.getItemName(m.id);
      });
      var new_id = this.getItemName(model.id);
      if (!ids.includes(new_id)) {
        ids.push(new_id);
      }
      return this.store.setItem(this.name, ids);
    }
  }, {
    key: "getCollectionReferenceData",
    value: function getCollectionReferenceData(model) {
      var _this6 = this;
      if (!model.collection) {
        return {};
      }
      var ids = model.collection.map(function (m) {
        return _this6.getItemName(m.id);
      });
      var new_id = this.getItemName(model.id);
      if (!ids.includes(new_id)) {
        ids.push(new_id);
      }
      var result = {};
      result[this.name] = ids;
      return result;
    }
  }, {
    key: "save",
    value: function () {
      var _save = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee4(model) {
        var items, key, data;
        return storage_regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              if (!this.store.setItems) {
                _context4.next = 7;
                break;
              }
              items = {};
              items[this.getItemName(model.id)] = model.toJSON();
              Object.assign(items, this.getCollectionReferenceData(model));
              return _context4.abrupt("return", this.store.debouncedSetItems ? this.store.debouncedSetItems(items) : this.store.setItems(items));
            case 7:
              key = this.getItemName(model.id);
              _context4.next = 10;
              return this.store.setItem(key, model.toJSON());
            case 10:
              data = _context4.sent;
              _context4.next = 13;
              return this.addCollectionReference(model, model.collection);
            case 13:
              return _context4.abrupt("return", data);
            case 14:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function save(_x6) {
        return _save.apply(this, arguments);
      }
      return save;
    }()
  }, {
    key: "create",
    value: function create(model, options) {
      /* Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
       * have an id of it's own.
       */
      if (!model.id) {
        model.id = guid();
        model.set(model.idAttribute, model.id, options);
      }
      return this.save(model);
    }
  }, {
    key: "update",
    value: function update(model) {
      return this.save(model);
    }
  }, {
    key: "find",
    value: function find(model) {
      return this.store.getItem(this.getItemName(model.id));
    }
  }, {
    key: "findAll",
    value: function () {
      var _findAll = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee5() {
        var keys, items;
        return storage_regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              _context5.next = 2;
              return this.store.getItem(this.name);
            case 2:
              keys = _context5.sent;
              if (!(keys !== null && keys !== void 0 && keys.length)) {
                _context5.next = 8;
                break;
              }
              _context5.next = 6;
              return this.store.getItems(keys);
            case 6:
              items = _context5.sent;
              return _context5.abrupt("return", Object.values(items));
            case 8:
              return _context5.abrupt("return", []);
            case 9:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function findAll() {
        return _findAll.apply(this, arguments);
      }
      return findAll;
    }()
  }, {
    key: "destroy",
    value: function () {
      var _destroy = storage_asyncToGenerator( /*#__PURE__*/storage_regeneratorRuntime().mark(function _callee6(model, collection) {
        return storage_regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              _context6.next = 2;
              return this.flush();
            case 2:
              _context6.next = 4;
              return this.store.removeItem(this.getItemName(model.id));
            case 4:
              _context6.next = 6;
              return this.removeCollectionReference(model, collection);
            case 6:
              return _context6.abrupt("return", model);
            case 7:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
      function destroy(_x7, _x8) {
        return _destroy.apply(this, arguments);
      }
      return destroy;
    }()
  }, {
    key: "getStorageSize",
    value: function getStorageSize() {
      return this.store.length;
    }
  }, {
    key: "getItemName",
    value: function getItemName(id) {
      return this.name + "-" + id;
    }
  }]);
  return Storage;
}();
Storage.sessionStorageInitialized = localforage.defineDriver(drivers_sessionStorage);
Storage.localForage = localforage;
/* harmony default export */ const storage = (Storage);
;// CONCATENATED MODULE: ./src/headless/utils/storage.js


function getDefaultStore() {
  if (shared_converse.config.get('trusted')) {
    var is_non_persistent = shared_api.settings.get('persistent_store') === 'sessionStorage';
    return is_non_persistent ? 'session' : 'persistent';
  } else {
    return 'session';
  }
}
function storeUsesIndexedDB(store) {
  return store === 'persistent' && shared_api.settings.get('persistent_store') === 'IndexedDB';
}
function createStore(id, store) {
  var name = store || getDefaultStore();
  var s = shared_converse.storage[name];
  if (typeof s === 'undefined') {
    throw new TypeError("createStore: Could not find store for ".concat(id));
  }
  return new storage(id, s, storeUsesIndexedDB(store));
}
function initStorage(model, id, type) {
  var store = type || getDefaultStore();
  model.browserStorage = createStore(id, store);
  if (storeUsesIndexedDB(store)) {
    var flush = function flush() {
      return model.browserStorage.flush();
    };
    window.addEventListener(shared_converse.unloadevent, flush);
    model.on('destroy', function () {
      return window.removeEventListener(shared_converse.unloadevent, flush);
    });
    model.listenTo(shared_converse, 'beforeLogout', flush);
  }
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/utils.js
function utils_typeof(obj) {
  "@babel/helpers - typeof";

  return utils_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;
  }, utils_typeof(obj);
}
function utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  utils_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" == utils_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 utils_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 utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}











var app_settings;
var init_settings = {}; // Container for settings passed in via converse.initialize
var user_settings; // User settings, populated via api.users.settings

function getAppSettings() {
  return app_settings;
}
function initAppSettings(settings) {
  init_settings = settings;
  app_settings = {};
  Object.assign(app_settings, Events);

  // Allow only whitelisted settings to be overwritten via converse.initialize
  var allowed_settings = lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS));
  lodash_es_assignIn(app_settings, DEFAULT_SETTINGS, allowed_settings);
}
function getInitSettings() {
  return init_settings;
}
function getAppSetting(key) {
  if (Object.keys(DEFAULT_SETTINGS).includes(key)) {
    return app_settings[key];
  }
}
function extendAppSettings(settings) {
  core.merge(DEFAULT_SETTINGS, settings);
  // When updating the settings, we need to avoid overwriting the
  // initialization_settings (i.e. the settings passed in via converse.initialize).
  var allowed_keys = Object.keys(lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS)));
  var allowed_site_settings = lodash_es_pick(init_settings, allowed_keys);
  var updated_settings = lodash_es_assignIn(lodash_es_pick(settings, allowed_keys), allowed_site_settings);
  core.merge(app_settings, updated_settings);
}
function registerListener(name, func, context) {
  app_settings.on(name, func, context);
}
function unregisterListener(name, func) {
  app_settings.off(name, func);
}
function updateAppSettings(key, val) {
  if (key == null) return this; // eslint-disable-line no-eq-null

  var attrs;
  if (lodash_es_isObject(key)) {
    attrs = key;
  } else if (typeof key === 'string') {
    attrs = {};
    attrs[key] = val;
  }
  var allowed_keys = Object.keys(lodash_es_pick(attrs, Object.keys(DEFAULT_SETTINGS)));
  var changed = {};
  allowed_keys.forEach(function (k) {
    var val = attrs[k];
    if (!lodash_es_isEqual(app_settings[k], val)) {
      changed[k] = val;
      app_settings[k] = val;
    }
  });
  Object.keys(changed).forEach(function (k) {
    return app_settings.trigger('change:' + k, changed[k]);
  });
  app_settings.trigger('change', changed);
}

/**
 * @async
 */
function initUserSettings() {
  var _user_settings;
  if (!shared_converse.bare_jid) {
    var msg = "No JID to fetch user settings for";
    log.error(msg);
    throw Error(msg);
  }
  if (!((_user_settings = user_settings) !== null && _user_settings !== void 0 && _user_settings.fetched)) {
    var id = "converse.user-settings.".concat(shared_converse.bare_jid);
    user_settings = new Model({
      id: id
    });
    initStorage(user_settings, id);
    user_settings.fetched = user_settings.fetch({
      'promise': true
    });
  }
  return user_settings.fetched;
}
function getUserSettings() {
  return _getUserSettings.apply(this, arguments);
}
function _getUserSettings() {
  _getUserSettings = utils_asyncToGenerator( /*#__PURE__*/utils_regeneratorRuntime().mark(function _callee() {
    return utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return initUserSettings();
        case 2:
          return _context.abrupt("return", user_settings);
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _getUserSettings.apply(this, arguments);
}
function updateUserSettings(_x, _x2) {
  return _updateUserSettings.apply(this, arguments);
}
function _updateUserSettings() {
  _updateUserSettings = utils_asyncToGenerator( /*#__PURE__*/utils_regeneratorRuntime().mark(function _callee2(data, options) {
    return utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return initUserSettings();
        case 2:
          return _context2.abrupt("return", user_settings.save(data, options));
        case 3:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _updateUserSettings.apply(this, arguments);
}
function clearUserSettings() {
  return _clearUserSettings.apply(this, arguments);
}
function _clearUserSettings() {
  _clearUserSettings = utils_asyncToGenerator( /*#__PURE__*/utils_regeneratorRuntime().mark(function _callee3() {
    return utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return initUserSettings();
        case 2:
          return _context3.abrupt("return", user_settings.clear());
        case 3:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _clearUserSettings.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/api.js
function api_typeof(obj) {
  "@babel/helpers - typeof";

  return api_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;
  }, api_typeof(obj);
}
function api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  api_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" == api_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 api_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 api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}




/**
 * This grouping allows access to the
 * [configuration settings](/docs/html/configuration.html#configuration-settings)
 * of Converse.
 *
 * @namespace _converse.api.settings
 * @memberOf _converse.api
 */
var settings_api = {
  /**
   * Allows new configuration settings to be specified, or new default values for
   * existing configuration settings to be specified.
   *
   * Note, calling this method *after* converse.initialize has been
   * called will *not* change the initialization settings provided via
   * `converse.initialize`.
   *
   * @method _converse.api.settings.extend
   * @param { object } settings The configuration settings
   * @example
   * _converse.api.settings.extend({
   *    'enable_foo': true
   * });
   *
   * // The user can then override the default value of the configuration setting when
   * // calling `converse.initialize`.
   * converse.initialize({
   *     'enable_foo': false
   * });
   */
  extend: function extend(settings) {
    return extendAppSettings(settings);
  },
  update: function update(settings) {
    log.warn('The api.settings.update method has been deprecated and will be removed. ' + 'Please use api.settings.extend instead.');
    return this.extend(settings);
  },
  /**
   * @method _converse.api.settings.get
   * @returns {*} Value of the particular configuration setting.
   * @example _converse.api.settings.get("play_sounds");
   */
  get: function get(key) {
    return getAppSetting(key);
  },
  /**
   * Set one or many configuration settings.
   *
   * Note, this is not an alternative to calling {@link converse.initialize}, which still needs
   * to be called. Generally, you'd use this method after Converse is already
   * running and you want to change the configuration on-the-fly.
   *
   * @method _converse.api.settings.set
   * @param { Object | string } [settings_or_key]
   *  An object containing configuration settings.
   *  Alternatively to passing in an object, you can pass in a key and a value.
   * @param { string } [value]
   * @example _converse.api.settings.set("play_sounds", true);
   * @example
   * _converse.api.settings.set({
   *     "play_sounds": true,
   *     "hide_offline_users": true
   * });
   */
  set: function set(settings_or_key, value) {
    updateAppSettings(settings_or_key, value);
  },
  /**
   * The `listen` namespace exposes methods for creating event listeners
   * (aka handlers) for events related to settings.
   *
   * @namespace _converse.api.settings.listen
   * @memberOf _converse.api.settings
   */
  listen: {
    /**
     * Register an event listener for the passed in event.
     * @method _converse.api.settings.listen.on
     * @param { ('change') } name - The name of the event to listen for.
     *  Currently there is only the 'change' event.
     * @param { Function } handler - The event handler function
     * @param { Object } [context] - The context of the `this` attribute of the
     *  handler function.
     * @example _converse.api.settings.listen.on('change', callback);
     */
    on: function on(name, handler, context) {
      registerListener(name, handler, context);
    },
    /**
     * To stop listening to an event, you can use the `not` method.
     * @method _converse.api.settings.listen.not
     * @param { String } name The event's name
     * @param { Function } handler The callback method that is to no longer be called when the event fires
     * @example _converse.api.settings.listen.not('change', callback);
     */
    not: function not(name, handler) {
      unregisterListener(name, handler);
    }
  }
};

/**
 * API for accessing and setting user settings. User settings are
 * different from the application settings from {@link _converse.api.settings}
 * because they are per-user and set via user action.
 * @namespace _converse.api.user.settings
 * @memberOf _converse.api.user
 */
var user_settings_api = {
  /**
   * Returns the user settings model. Useful when you want to listen for change events.
   * @async
   * @method _converse.api.user.settings.getModel
   * @returns {Promise<Model>}
   * @example const settings = await _converse.api.user.settings.getModel();
   */
  getModel: function getModel() {
    return getUserSettings();
  },
  /**
   * Get the value of a particular user setting.
   * @method _converse.api.user.settings.get
   * @param { String } key - The setting name
   * @param {*} [fallback] - An optional fallback value if the user setting is undefined
   * @returns {Promise} Promise which resolves with the value of the particular configuration setting.
   * @example _converse.api.user.settings.get("foo");
   */
  get: function get(key, fallback) {
    return api_asyncToGenerator( /*#__PURE__*/api_regeneratorRuntime().mark(function _callee() {
      var user_settings;
      return api_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getUserSettings();
          case 2:
            user_settings = _context.sent;
            return _context.abrupt("return", user_settings.get(key) === undefined ? fallback : user_settings.get(key));
          case 4:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * Set one or many user settings.
   * @async
   * @method _converse.api.user.settings.set
   * @param { Object } [settings] An object containing configuration settings.
   * @param { string } [key] Alternatively to passing in an object, you can pass in a key and a value.
   * @param { string } [value]
   * @example _converse.api.user.settings.set("foo", "bar");
   * @example
   * _converse.api.user.settings.set({
   *     "foo": "bar",
   *     "baz": "buz"
   * });
   */
  set: function set(key, val) {
    if (lodash_es_isObject(key)) {
      return updateUserSettings(key, {
        'promise': true
      });
    } else {
      var o = {};
      o[key] = val;
      return updateUserSettings(o, {
        'promise': true
      });
    }
  },
  /**
   * Clears all the user settings
   * @async
   * @method _converse.api.user.settings.clear
   */
  clear: function clear() {
    return clearUserSettings();
  }
};
;// CONCATENATED MODULE: ./src/headless/utils/stanza.js
function stanza_typeof(obj) {
  "@babel/helpers - typeof";

  return stanza_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;
  }, stanza_typeof(obj);
}
function stanza_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function stanza_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, stanza_toPropertyKey(descriptor.key), descriptor);
  }
}
function stanza_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) stanza_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) stanza_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function stanza_toPropertyKey(arg) {
  var key = stanza_toPrimitive(arg, "string");
  return stanza_typeof(key) === "symbol" ? key : String(key);
}
function stanza_toPrimitive(input, hint) {
  if (stanza_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (stanza_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}


var PARSE_ERROR_NS = 'http://www.w3.org/1999/xhtml';
function toStanza(string, throwErrorIfInvalidNS) {
  var doc = external_strophe_namespaceObject.Strophe.xmlHtmlNode(string);
  if (doc.getElementsByTagNameNS(PARSE_ERROR_NS, 'parsererror').length) {
    throw new Error("Parser Error: ".concat(string));
  }
  var node = doc.firstElementChild;
  if (['message', 'iq', 'presence'].includes(node.nodeName.toLowerCase()) && node.namespaceURI !== 'jabber:client' && node.namespaceURI !== 'jabber:server') {
    var err_msg = "Invalid namespaceURI ".concat(node.namespaceURI);
    log.error(err_msg);
    if (throwErrorIfInvalidNS) throw new Error(err_msg);
  }
  return node;
}

/**
 * A Stanza represents a XML element used in XMPP (commonly referred to as
 * stanzas).
 */
var Stanza = /*#__PURE__*/function () {
  function Stanza(strings, values) {
    stanza_classCallCheck(this, Stanza);
    this.strings = strings;
    this.values = values;
  }
  stanza_createClass(Stanza, [{
    key: "toString",
    value: function toString() {
      var _this = this;
      this.string = this.string || this.strings.reduce(function (acc, str) {
        var idx = _this.strings.indexOf(str);
        var value = _this.values.length > idx ? _this.values[idx].toString() : '';
        return acc + str + value;
      }, '');
      return this.string;
    }
  }, {
    key: "tree",
    value: function tree() {
      var _this$node;
      this.node = (_this$node = this.node) !== null && _this$node !== void 0 ? _this$node : toStanza(this.toString(), true);
      return this.node;
    }
  }]);
  return Stanza;
}();
/**
 * Tagged template literal function which generates {@link Stanza } objects
 *
 * Similar to the `html` function, from Lit.
 *
 * @example stx`<presence type="${type}"><show>${show}</show></presence>`
 */
function stx(strings) {
  for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    values[_key - 1] = arguments[_key];
  }
  return new Stanza(strings, values);
}
;// CONCATENATED MODULE: ./src/headless/utils/core.js
function core_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  core_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" == core_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 _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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 _iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function core_typeof(obj) {
  "@babel/helpers - typeof";

  return core_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;
  }, core_typeof(obj);
}
function core_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 core_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        core_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        core_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the core utilities module.
 */













/**
 * The utils object
 * @namespace u
 */
var u = {};
function isElement(el) {
  return el instanceof Element || el instanceof HTMLDocument;
}
function isError(obj) {
  return Object.prototype.toString.call(obj) === "[object Error]";
}
function core_isFunction(val) {
  return typeof val === 'function';
}
function isEmptyMessage(attrs) {
  if (attrs instanceof Model) {
    attrs = attrs.attributes;
  }
  return !attrs['oob_url'] && !attrs['file'] && !(attrs['is_encrypted'] && attrs['plaintext']) && !attrs['message'] && !attrs['body'];
}

/**
 * We distinguish between UniView and MultiView instances.
 *
 * UniView means that only one chat is visible, even though there might be multiple ongoing chats.
 * MultiView means that multiple chats may be visible simultaneously.
 */
function isUniView() {
  return ['mobile', 'fullscreen', 'embedded'].includes(settings_api.get("view_mode"));
}
function shouldClearCache() {
  var api = shared_converse.api;
  return !shared_converse.config.get('trusted') || api.settings.get('clear_cache_on_logout') || shared_converse.isTestEnv();
}
function tearDown() {
  return _tearDown.apply(this, arguments);
}
function _tearDown() {
  _tearDown = core_asyncToGenerator( /*#__PURE__*/core_regeneratorRuntime().mark(function _callee() {
    var api;
    return core_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          api = shared_converse.api;
          _context.next = 3;
          return api.trigger('beforeTearDown', {
            'synchronous': true
          });
        case 3:
          window.removeEventListener('click', shared_converse.onUserActivity);
          window.removeEventListener('focus', shared_converse.onUserActivity);
          window.removeEventListener('keypress', shared_converse.onUserActivity);
          window.removeEventListener('mousemove', shared_converse.onUserActivity);
          window.removeEventListener(shared_converse.unloadevent, shared_converse.onUserActivity);
          window.clearInterval(shared_converse.everySecondTrigger);
          api.trigger('afterTearDown');
          return _context.abrupt("return", shared_converse);
        case 11:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _tearDown.apply(this, arguments);
}
function clearSession() {
  var _converse$session;
  (_converse$session = shared_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.destroy();
  delete shared_converse.session;
  shouldClearCache() && shared_converse.api.user.settings.clear();
  /**
   * Synchronouse event triggered once the user session has been cleared,
   * for example when the user has logged out or when Converse has
   * disconnected for some other reason.
   * @event _converse#clearSession
   */
  return shared_converse.api.trigger('clearSession', {
    'synchronous': true
  });
}

/**
 * Given a message object, return its text with @ chars
 * inserted before the mentioned nicknames.
 */
function prefixMentions(message) {
  var text = message.getMessageText();
  (message.get('references') || []).sort(function (a, b) {
    return b.begin - a.begin;
  }).forEach(function (ref) {
    text = "".concat(text.slice(0, ref.begin), "@").concat(text.slice(ref.begin));
  });
  return text;
}
u.isTagEqual = function (stanza, name) {
  var _stanza$tree;
  if ((_stanza$tree = stanza.tree) !== null && _stanza$tree !== void 0 && _stanza$tree.call(stanza)) {
    return u.isTagEqual(stanza.tree(), name);
  } else if (!(stanza instanceof Element)) {
    throw Error("isTagEqual called with value which isn't " + "an element or Strophe.Builder instance");
  } else {
    return external_strophe_namespaceObject.Strophe.isTagEqual(stanza, name);
  }
};
u.getJIDFromURI = function (jid) {
  return jid.startsWith('xmpp:') && jid.endsWith('?join') ? jid.replace(/^xmpp:/, '').replace(/\?join$/, '') : jid;
};
u.getLongestSubstring = function (string, candidates) {
  function reducer(accumulator, current_value) {
    if (string.startsWith(current_value)) {
      if (current_value.length > accumulator.length) {
        return current_value;
      } else {
        return accumulator;
      }
    } else {
      return accumulator;
    }
  }
  return candidates.reduce(reducer, '');
};
function isValidJID(jid) {
  if (typeof jid === 'string') {
    return lodash_es_compact(jid.split('@')).length === 2 && !jid.startsWith('@') && !jid.endsWith('@');
  }
  return false;
}
u.isValidMUCJID = function (jid) {
  return !jid.startsWith('@') && !jid.endsWith('@');
};
u.isSameBareJID = function (jid1, jid2) {
  if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
    return false;
  }
  return external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid1).toLowerCase() === external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid2).toLowerCase();
};
u.isSameDomain = function (jid1, jid2) {
  if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
    return false;
  }
  return external_strophe_namespaceObject.Strophe.getDomainFromJid(jid1).toLowerCase() === external_strophe_namespaceObject.Strophe.getDomainFromJid(jid2).toLowerCase();
};
u.isNewMessage = function (message) {
  /* Given a stanza, determine whether it's a new
   * message, i.e. not a MAM archived one.
   */
  if (message instanceof Element) {
    return !(external_sizzle_default()("result[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MAM, "\"]"), message).length && external_sizzle_default()("delay[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.DELAY, "\"]"), message).length);
  } else if (message instanceof Model) {
    message = message.attributes;
  }
  return !(message['is_delayed'] && message['is_archived']);
};
u.shouldCreateMessage = function (attrs) {
  return attrs['retracted'] ||
  // Retraction received *before* the message
  !isEmptyMessage(attrs);
};
u.shouldCreateGroupchatMessage = function (attrs) {
  return attrs.nick && (u.shouldCreateMessage(attrs) || attrs.is_tombstone);
};
u.isChatRoom = function (model) {
  return model && model.get('type') === 'chatroom';
};
function isErrorObject(o) {
  return o instanceof Error;
}
u.isErrorStanza = function (stanza) {
  if (!isElement(stanza)) {
    return false;
  }
  return stanza.getAttribute('type') === 'error';
};
u.isForbiddenError = function (stanza) {
  if (!isElement(stanza)) {
    return false;
  }
  return external_sizzle_default()("error[type=\"auth\"] forbidden[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), stanza).length > 0;
};
u.isServiceUnavailableError = function (stanza) {
  if (!isElement(stanza)) {
    return false;
  }
  return external_sizzle_default()("error[type=\"cancel\"] service-unavailable[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), stanza).length > 0;
};

/**
 * Merge the second object into the first one.
 * @method u#merge
 * @param { Object } dst
 * @param { Object } src
 */
function core_merge(dst, src) {
  for (var k in src) {
    if (!Object.prototype.hasOwnProperty.call(src, k)) continue;
    if (k === "__proto__" || k === "constructor") continue;
    if (lodash_es_isObject(dst[k])) {
      core_merge(dst[k], src[k]);
    } else {
      dst[k] = src[k];
    }
  }
}
u.getOuterWidth = function (el) {
  var include_margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var width = el.offsetWidth;
  if (!include_margin) {
    return width;
  }
  var style = window.getComputedStyle(el);
  width += parseInt(style.marginLeft ? style.marginLeft : 0, 10) + parseInt(style.marginRight ? style.marginRight : 0, 10);
  return width;
};

/**
 * Converts an HTML string into a DOM element.
 * Expects that the HTML string has only one top-level element,
 * i.e. not multiple ones.
 * @private
 * @method u#stringToElement
 * @param { String } s - The HTML string
 */
u.stringToElement = function (s) {
  var div = document.createElement('div');
  div.innerHTML = s;
  return div.firstElementChild;
};

/**
 * Checks whether the DOM element matches the given selector.
 * @private
 * @method u#matchesSelector
 * @param { Element } el - The DOM element
 * @param { String } selector - The selector
 */
u.matchesSelector = function (el, selector) {
  var match = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
  return match ? match.call(el, selector) : false;
};

/**
 * Returns a list of children of the DOM element that match the selector.
 * @private
 * @method u#queryChildren
 * @param { Element } el - the DOM element
 * @param { String } selector - the selector they should be matched against
 */
u.queryChildren = function (el, selector) {
  return Array.from(el.childNodes).filter(function (el) {
    return u.matchesSelector(el, selector);
  });
};
u.contains = function (attr, query) {
  var checker = function checker(item, key) {
    return item.get(key).toLowerCase().includes(query.toLowerCase());
  };
  return function (item) {
    if (core_typeof(attr) === 'object') {
      return Object.keys(attr).reduce(function (acc, k) {
        return acc || checker(item, k);
      }, false);
    } else if (typeof attr === 'string') {
      return checker(item, attr);
    } else {
      throw new TypeError('contains: wrong attribute type. Must be string or array.');
    }
  };
};
u.isOfType = function (type, item) {
  return item.get('type') == type;
};
u.isInstance = function (type, item) {
  return item instanceof type;
};
u.getAttribute = function (key, item) {
  return item.get(key);
};
u.contains.not = function (attr, query) {
  return function (item) {
    return !u.contains(attr, query)(item);
  };
};
u.rootContains = function (root, el) {
  // The document element does not have the contains method in IE.
  if (root === document && !root.contains) {
    return document.head.contains(el) || document.body.contains(el);
  }
  return root.contains ? root.contains(el) : window.HTMLElement.prototype.contains.call(root, el);
};
u.createFragmentFromText = function (markup) {
  /* Returns a DocumentFragment containing DOM nodes based on the
   * passed-in markup text.
   */
  // http://stackoverflow.com/questions/9334645/create-node-from-markup-string
  var frag = document.createDocumentFragment(),
    tmp = document.createElement('body'),
    child;
  tmp.innerHTML = markup;
  // Append elements in a loop to a DocumentFragment, so that the
  // browser does not re-render the document for each node.
  while (child = tmp.firstChild) {
    // eslint-disable-line no-cond-assign
    frag.appendChild(child);
  }
  return frag;
};
u.isPersistableModel = function (model) {
  return model.collection && model.collection.browserStorage;
};
u.getResolveablePromise = getOpenPromise;
u.getOpenPromise = getOpenPromise;
u.interpolate = function (string, o) {
  return string.replace(/{{{([^{}]*)}}}/g, function (a, b) {
    var r = o[b];
    return typeof r === 'string' || typeof r === 'number' ? r : a;
  });
};

/**
 * Call the callback once all the events have been triggered
 * @private
 * @method u#onMultipleEvents
 * @param { Array } events: An array of objects, with keys `object` and
 *   `event`, representing the event name and the object it's triggered upon.
 * @param { Function } callback: The function to call once all events have
 *    been triggered.
 */
u.onMultipleEvents = function () {
  var events = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var callback = arguments.length > 1 ? arguments[1] : undefined;
  var triggered = [];
  function handler(result) {
    triggered.push(result);
    if (events.length === triggered.length) {
      callback(triggered);
      triggered = [];
    }
  }
  events.forEach(function (e) {
    return e.object.on(e.event, handler);
  });
};
function safeSave(model, attributes, options) {
  if (u.isPersistableModel(model)) {
    model.save(attributes, options);
  } else {
    model.set(attributes, options);
  }
}
u.safeSave = safeSave;
u.siblingIndex = function (el) {
  /* eslint-disable no-cond-assign */
  for (var i = 0; el = el.previousElementSibling; i++);
  return i;
};

/**
 * Returns the current word being written in the input element
 * @method u#getCurrentWord
 * @param { HTMLElement } input - The HTMLElement in which text is being entered
 * @param { number } [index] - An optional rightmost boundary index. If given, the text
 *  value of the input element will only be considered up until this index.
 * @param { string } [delineator] - An optional string delineator to
 *  differentiate between words.
 * @private
 */
u.getCurrentWord = function (input, index, delineator) {
  if (!index) {
    index = input.selectionEnd || undefined;
  }
  var _input$value$slice$sp = input.value.slice(0, index).split(/\s/).slice(-1),
    _input$value$slice$sp2 = _slicedToArray(_input$value$slice$sp, 1),
    word = _input$value$slice$sp2[0];
  if (delineator) {
    var _word$split$slice = word.split(delineator).slice(-1);
    var _word$split$slice2 = _slicedToArray(_word$split$slice, 1);
    word = _word$split$slice2[0];
  }
  return word;
};
u.isMentionBoundary = function (s) {
  return s !== '@' && RegExp("(\\p{Z}|\\p{P})", 'u').test(s);
};
u.replaceCurrentWord = function (input, new_value) {
  var caret = input.selectionEnd || undefined;
  var current_word = lodash_es_last(input.value.slice(0, caret).split(/\s/));
  var value = input.value;
  var mention_boundary = u.isMentionBoundary(current_word[0]) ? current_word[0] : '';
  input.value = value.slice(0, caret - current_word.length) + mention_boundary + "".concat(new_value, " ") + value.slice(caret);
  var selection_end = caret - current_word.length + new_value.length + 1;
  input.selectionEnd = mention_boundary ? selection_end + 1 : selection_end;
};
u.triggerEvent = function (el, name) {
  var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "Event";
  var bubbles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var cancelable = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var evt = document.createEvent(type);
  evt.initEvent(name, bubbles, cancelable);
  el.dispatchEvent(evt);
};
u.getSelectValues = function (select) {
  var result = [];
  var options = select && select.options;
  for (var i = 0, iLen = options.length; i < iLen; i++) {
    var opt = options[i];
    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
};
function getRandomInt(max) {
  return Math.random() * max | 0;
}
u.placeCaretAtEnd = function (textarea) {
  if (textarea !== document.activeElement) {
    textarea.focus();
  }
  // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
  var len = textarea.value.length * 2;
  // Timeout seems to be required for Blink
  setTimeout(function () {
    return textarea.setSelectionRange(len, len);
  }, 1);
  // Scroll to the bottom, in case we're in a tall textarea
  // (Necessary for Firefox and Chrome)
  this.scrollTop = 999999;
};
function getUniqueId(suffix) {
  var _crypto$randomUUID, _crypto$randomUUID2, _crypto;
  var uuid = (_crypto$randomUUID = (_crypto$randomUUID2 = (_crypto = crypto).randomUUID) === null || _crypto$randomUUID2 === void 0 ? void 0 : _crypto$randomUUID2.call(_crypto)) !== null && _crypto$randomUUID !== void 0 ? _crypto$randomUUID : 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = getRandomInt(16);
    var v = c === 'x' ? r : r & 0x3 | 0x8;
    return v.toString(16);
  });
  if (typeof suffix === "string" || typeof suffix === "number") {
    return uuid + ":" + suffix;
  } else {
    return uuid;
  }
}

/**
 * Clears the specified timeout and interval.
 * @method u#clearTimers
 * @param { number } timeout - Id if the timeout to clear.
 * @param { number } interval - Id of the interval to clear.
 * @private
 * @copyright Simen Bekkhus 2016
 * @license MIT
 */
function clearTimers(timeout, interval) {
  clearTimeout(timeout);
  clearInterval(interval);
}

/**
 * Creates a {@link Promise} that resolves if the passed in function returns a truthy value.
 * Rejects if it throws or does not return truthy within the given max_wait.
 * @method u#waitUntil
 * @param { Function } func - The function called every check_delay,
 *  and the result of which is the resolved value of the promise.
 * @param { number } [max_wait=300] - The time to wait before rejecting the promise.
 * @param { number } [check_delay=3] - The time to wait before each invocation of {func}.
 * @returns {Promise} A promise resolved with the value of func,
 *  or rejected with the exception thrown by it or it times out.
 * @copyright Simen Bekkhus 2016
 * @license MIT
 */
function core_waitUntil(func) {
  var max_wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300;
  var check_delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
  // Run the function once without setting up any listeners in case it's already true
  try {
    var result = func();
    if (result) {
      return Promise.resolve(result);
    }
  } catch (e) {
    return Promise.reject(e);
  }
  var promise = getOpenPromise();
  var timeout_err = new Error();
  function checker() {
    try {
      var _result = func();
      if (_result) {
        clearTimers(max_wait_timeout, interval);
        promise.resolve(_result);
      }
    } catch (e) {
      clearTimers(max_wait_timeout, interval);
      promise.reject(e);
    }
  }
  var interval = setInterval(checker, check_delay);
  function handler() {
    clearTimers(max_wait_timeout, interval);
    var err_msg = "Wait until promise timed out: \n\n".concat(timeout_err.stack);
    console.trace();
    log.error(err_msg);
    promise.reject(new Error(err_msg));
  }
  var max_wait_timeout = setTimeout(handler, max_wait);
  return promise;
}
;
function setUnloadEvent() {
  if ('onpagehide' in window) {
    // Pagehide gets thrown in more cases than unload. Specifically it
    // gets thrown when the page is cached and not just
    // closed/destroyed. It's the only viable event on mobile Safari.
    // https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
    shared_converse.unloadevent = 'pagehide';
  } else if ('onbeforeunload' in window) {
    shared_converse.unloadevent = 'beforeunload';
  } else if ('onunload' in window) {
    shared_converse.unloadevent = 'unload';
  }
}
function replacePromise(name) {
  var existing_promise = shared_converse.promises[name];
  if (!existing_promise) {
    throw new Error("Tried to replace non-existing promise: ".concat(name));
  }
  if (existing_promise.replace) {
    var promise = getOpenPromise();
    promise.replace = existing_promise.replace;
    shared_converse.promises[name] = promise;
  } else {
    log.debug("Not replacing promise \"".concat(name, "\""));
  }
}
var core_element = document.createElement('div');
function decodeHTMLEntities(str) {
  if (str && typeof str === 'string') {
    core_element.innerHTML = purify_default().sanitize(str);
    str = core_element.textContent;
    core_element.textContent = '';
  }
  return str;
}
function saveWindowState(ev) {
  // XXX: eventually we should be able to just use
  // document.visibilityState (when we drop support for older
  // browsers).
  var state;
  var event_map = {
    'focus': "visible",
    'focusin': "visible",
    'pageshow': "visible",
    'blur': "hidden",
    'focusout': "hidden",
    'pagehide': "hidden"
  };
  ev = ev || document.createEvent('Events');
  if (ev.type in event_map) {
    state = event_map[ev.type];
  } else {
    state = document.hidden ? "hidden" : "visible";
  }
  shared_converse.windowState = state;
  /**
   * Triggered when window state has changed.
   * Used to determine when a user left the page and when came back.
   * @event _converse#windowStateChanged
   * @type { object }
   * @property{ string } state - Either "hidden" or "visible"
   * @example _converse.api.listen.on('windowStateChanged', obj => { ... });
   */
  shared_converse.api.trigger('windowStateChanged', {
    state: state
  });
}
/* harmony default export */ const core = (Object.assign({
  shouldClearCache: shouldClearCache,
  waitUntil: core_waitUntil,
  // TODO: remove. Only the API should be used
  isErrorObject: isErrorObject,
  getRandomInt: getRandomInt,
  getUniqueId: getUniqueId,
  isElement: isElement,
  isEmptyMessage: isEmptyMessage,
  isValidJID: isValidJID,
  merge: core_merge,
  prefixMentions: prefixMentions,
  saveWindowState: saveWindowState,
  stx: stx,
  toStanza: toStanza
}, u));
;// CONCATENATED MODULE: ./src/headless/log.js
var _console, _console2, _console3, _console4;

var LEVELS = {
  'debug': 0,
  'info': 1,
  'warn': 2,
  'error': 3,
  'fatal': 4
};

/* eslint-disable @typescript-eslint/no-empty-function */
var logger = Object.assign({
  'debug': (_console = console) !== null && _console !== void 0 && _console.log ? console.log.bind(console) : function noop() {},
  'error': (_console2 = console) !== null && _console2 !== void 0 && _console2.log ? console.log.bind(console) : function noop() {},
  'info': (_console3 = console) !== null && _console3 !== void 0 && _console3.log ? console.log.bind(console) : function noop() {},
  'warn': (_console4 = console) !== null && _console4 !== void 0 && _console4.log ? console.log.bind(console) : function noop() {}
}, console);
/* eslint-enable @typescript-eslint/no-empty-function */

/**
 * The log namespace
 * @namespace log
 */
/* harmony default export */ const log = ({
  /**
   * The the log-level, which determines how verbose the logging is.
   * @method log#setLogLevel
   * @param { number } level - The loglevel which allows for filtering of log messages
   */
  setLogLevel: function setLogLevel(level) {
    if (!['debug', 'info', 'warn', 'error', 'fatal'].includes(level)) {
      throw new Error("Invalid loglevel: ".concat(level));
    }
    this.loglevel = level;
  },
  /**
   * Logs messages to the browser's developer console.
   * Available loglevels are 0 for 'debug', 1 for 'info', 2 for 'warn',
   * 3 for 'error' and 4 for 'fatal'.
   * When using the 'error' or 'warn' loglevels, a full stacktrace will be
   * logged as well.
   * @method log#log
   * @param { string | Error } message - The message to be logged
   * @param { number } level - The loglevel which allows for filtering of log messages
   */
  log: function log(message, level) {
    var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    if (LEVELS[level] < LEVELS[this.loglevel]) {
      return;
    }
    if (level === 'error' || level === 'fatal') {
      style = style || 'color: maroon';
    } else if (level === 'debug') {
      style = style || 'color: green';
    }
    if (message instanceof Error) {
      message = message.stack;
    } else if (isElement(message)) {
      message = message.outerHTML;
    }
    var prefix = style ? '%c' : '';
    if (level === 'error') {
      logger.error("".concat(prefix, " ERROR: ").concat(message), style);
    } else if (level === 'warn') {
      logger.warn("".concat(prefix, " ").concat(new Date().toISOString(), " WARNING: ").concat(message), style);
    } else if (level === 'fatal') {
      logger.error("".concat(prefix, " FATAL: ").concat(message), style);
    } else if (level === 'debug') {
      logger.debug("".concat(prefix, " ").concat(new Date().toISOString(), " DEBUG: ").concat(message), style);
    } else {
      logger.info("".concat(prefix, " ").concat(new Date().toISOString(), " INFO: ").concat(message), style);
    }
  },
  debug: function debug(message, style) {
    this.log(message, 'debug', style);
  },
  error: function error(message, style) {
    this.log(message, 'error', style);
  },
  info: function info(message, style) {
    this.log(message, 'info', style);
  },
  warn: function warn(message, style) {
    this.log(message, 'warn', style);
  },
  fatal: function fatal(message, style) {
    this.log(message, 'fatal', style);
  }
});
;// CONCATENATED MODULE: ./node_modules/pluggable.js/src/pluggable.js
function pluggable_typeof(obj) {
  "@babel/helpers - typeof";

  return pluggable_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;
  }, pluggable_typeof(obj);
}
function pluggable_slicedToArray(arr, i) {
  return pluggable_arrayWithHoles(arr) || pluggable_iterableToArrayLimit(arr, i) || pluggable_unsupportedIterableToArray(arr, i) || pluggable_nonIterableRest();
}
function pluggable_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function pluggable_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return pluggable_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 pluggable_arrayLikeToArray(o, minLen);
}
function pluggable_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 pluggable_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function pluggable_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function pluggable_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function pluggable_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, pluggable_toPropertyKey(descriptor.key), descriptor);
  }
}
function pluggable_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) pluggable_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) pluggable_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function pluggable_toPropertyKey(arg) {
  var key = pluggable_toPrimitive(arg, "string");
  return pluggable_typeof(key) === "symbol" ? key : String(key);
}
function pluggable_toPrimitive(input, hint) {
  if (pluggable_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (pluggable_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/*
       ____  __                        __    __         _
      / __ \/ /_  __ ___   ___  ____ _/ /_  / /__      (_)____
     / /_/ / / / / / __ \/ __ \/ __/ / __ \/ / _ \    / / ___/
    / ____/ / /_/ / /_/ / /_/ / /_/ / /_/ / /  __/   / (__  )
   /_/   /_/\__,_/\__, /\__, /\__/_/_.___/_/\___(_)_/ /____/
                 /____//____/                    /___/
 */

// Pluggable.js lets you to make your Javascript code pluggable while still
// keeping sensitive objects and data private through closures.

// `wrappedOverride` creates a partially applied wrapper function
// that makes sure to set the proper super method when the
// overriding method is called. This is done to enable
// chaining of plugin methods, all the way up to the
// original method.
function wrappedOverride(key, value, super_method, default_super) {
  if (typeof super_method === "function") {
    if (typeof this.__super__ === "undefined") {
      /* We're not on the context of the plugged object.
       * This can happen when the overridden method is called via
       * an event handler or when it's a constructor.
       *
       * In this case, we simply tack on the  __super__ obj.
       */
      this.__super__ = default_super;
    }
    this.__super__[key] = super_method.bind(this);
  }
  for (var _len = arguments.length, args = new Array(_len > 4 ? _len - 4 : 0), _key = 4; _key < _len; _key++) {
    args[_key - 4] = arguments[_key];
  }
  return value.apply(this, args);
}

// The `PluginSocket` class contains the plugin architecture, and gets
// created whenever `pluggable.enable(obj);` is called on the object
// that you want to make pluggable.
// You can also see it as the thing into which the plugins are plugged.
// It takes two parameters, first, the object being made pluggable, and
// then the name by which the pluggable object may be referenced on the
// __super__ object (inside overrides).
var PluginSocket = /*#__PURE__*/function () {
  function PluginSocket(plugged, name) {
    pluggable_classCallCheck(this, PluginSocket);
    this.name = name;
    this.plugged = plugged;
    if (typeof this.plugged.__super__ === 'undefined') {
      this.plugged.__super__ = {};
    } else if (typeof this.plugged.__super__ === 'string') {
      this.plugged.__super__ = {
        '__string__': this.plugged.__super__
      };
    }
    this.plugged.__super__[name] = this.plugged;
    this.plugins = {};
    this.initialized_plugins = [];
  }

  // `_overrideAttribute` overrides an attribute on the original object
  // (the thing being plugged into).
  //
  // If the attribute being overridden is a function, then the original
  // function will still be available via the `__super__` attribute.
  //
  // If the same function is being overridden multiple times, then
  // the original function will be available at the end of a chain of
  // functions, starting from the most recent override, all the way
  // back to the original function, each being referenced by the
  // previous' __super__ attribute.
  //
  // For example:
  //
  // `plugin2.MyFunc.__super__.myFunc => plugin1.MyFunc.__super__.myFunc => original.myFunc`
  pluggable_createClass(PluginSocket, [{
    key: "_overrideAttribute",
    value: function _overrideAttribute(key, plugin) {
      var value = plugin.overrides[key];
      if (typeof value === "function") {
        var default_super = {};
        default_super[this.name] = this.plugged;
        var super_method = this.plugged[key];
        this.plugged[key] = function () {
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          return wrappedOverride.apply(this, [key, value, super_method, default_super].concat(args));
        };
      } else {
        this.plugged[key] = value;
      }
    }
  }, {
    key: "_extendObject",
    value: function _extendObject(obj, attributes) {
      var _this = this;
      if (!obj.prototype.__super__) {
        obj.prototype.__super__ = {};
        obj.prototype.__super__[this.name] = this.plugged;
      }
      var _loop = function _loop() {
        var _Object$entries$_i = pluggable_slicedToArray(_Object$entries[_i], 2),
          key = _Object$entries$_i[0],
          value = _Object$entries$_i[1];
        if (key === 'events') {
          obj.prototype[key] = Object.assign(value, obj.prototype[key]);
        } else if (typeof value === 'function') {
          // We create a partially applied wrapper function, that
          // makes sure to set the proper super method when the
          // overriding method is called. This is done to enable
          // chaining of plugin methods, all the way up to the
          // original method.
          var default_super = {};
          default_super[_this.name] = _this.plugged;
          var super_method = obj.prototype[key];
          obj.prototype[key] = function () {
            for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
              args[_key3] = arguments[_key3];
            }
            return wrappedOverride.apply(this, [key, value, super_method, default_super].concat(args));
          };
        } else {
          obj.prototype[key] = value;
        }
      };
      for (var _i = 0, _Object$entries = Object.entries(attributes); _i < _Object$entries.length; _i++) {
        _loop();
      }
    }

    // Plugins can specify dependencies (by means of the
    // `dependencies` list attribute) which refers to dependencies
    // which will be initialized first, before the plugin itself gets initialized.
    //
    // If `strict_plugin_dependencies` is set to `false` (on the object being
    // made pluggable), then no error will be thrown if any of these plugins aren't
    // available.
  }, {
    key: "loadPluginDependencies",
    value: function loadPluginDependencies(plugin) {
      var _plugin$dependencies,
        _this2 = this;
      (_plugin$dependencies = plugin.dependencies) === null || _plugin$dependencies === void 0 ? void 0 : _plugin$dependencies.forEach(function (name) {
        var dep = _this2.plugins[name];
        if (dep) {
          var _dep$dependencies;
          if ((_dep$dependencies = dep.dependencies) !== null && _dep$dependencies !== void 0 && _dep$dependencies.includes(plugin.__name__)) {
            /* FIXME: circular dependency checking is only one level deep. */
            throw "Found a circular dependency between the plugins \"" + plugin.__name__ + "\" and \"" + name + "\"";
          }
          _this2.initializePlugin(dep);
        } else {
          _this2.throwUndefinedDependencyError("Could not find dependency \"" + name + "\" " + "for the plugin \"" + plugin.__name__ + "\". " + "If it's needed, make sure it's loaded by require.js");
        }
      });
    }
  }, {
    key: "throwUndefinedDependencyError",
    value: function throwUndefinedDependencyError(msg) {
      if (this.plugged.strict_plugin_dependencies) {
        throw msg;
      } else {
        if (console.warn) {
          console.warn(msg);
        } else {
          console.log(msg);
        }
      }
    }

    // `applyOverrides` is called by initializePlugin. It applies any
    // and all overrides of methods or Backbone views and models that
    // are defined on any of the plugins.
  }, {
    key: "applyOverrides",
    value: function applyOverrides(plugin) {
      var _this3 = this;
      Object.keys(plugin.overrides || {}).forEach(function (key) {
        var override = plugin.overrides[key];
        if (pluggable_typeof(override) === "object") {
          if (typeof _this3.plugged[key] === 'undefined') {
            _this3.throwUndefinedDependencyError("Plugin \"".concat(plugin.__name__, "\" tried to override \"").concat(key, "\" but it's not found."));
          } else {
            _this3._extendObject(_this3.plugged[key], override);
          }
        } else {
          _this3._overrideAttribute(key, plugin);
        }
      });
    }

    // `initializePlugin` applies the overrides (if any) defined on all
    // the registered plugins and then calls the initialize method of the plugin
  }, {
    key: "initializePlugin",
    value: function initializePlugin(plugin) {
      var _plugin$enabled;
      if (!Object.keys(this.allowed_plugins).includes(plugin.__name__)) {
        /* Don't initialize disallowed plugins. */
        return;
      }
      if (this.initialized_plugins.includes(plugin.__name__)) {
        /* Don't initialize plugins twice, otherwise we get
        * infinite recursion in overridden methods.
        */
        return;
      }
      if (typeof plugin.enabled === 'boolean' && plugin.enabled || (_plugin$enabled = plugin.enabled) !== null && _plugin$enabled !== void 0 && _plugin$enabled.call(plugin, this.plugged) || plugin.enabled == null) {
        // isNil

        Object.assign(plugin, this.properties);
        if (plugin.dependencies) {
          this.loadPluginDependencies(plugin);
        }
        this.applyOverrides(plugin);
        if (typeof plugin.initialize === "function") {
          plugin.initialize.bind(plugin)(this);
        }
        this.initialized_plugins.push(plugin.__name__);
      }
    }

    // `registerPlugin` registers (or inserts, if you'd like) a plugin,
    // by adding it to the `plugins` map on the PluginSocket instance.
  }, {
    key: "registerPlugin",
    value: function registerPlugin(name, plugin) {
      if (name in this.plugins) {
        throw new Error('Error: Plugin name ' + name + ' is already taken');
      }
      plugin.__name__ = name;
      this.plugins[name] = plugin;
    }

    // `initializePlugins` should get called once all plugins have been
    // registered. It will then iterate through all the plugins, calling
    // `initializePlugin` for each.
    // The passed in  properties variable is an object with attributes and methods
    // which will be attached to the plugins.
  }, {
    key: "initializePlugins",
    value: function initializePlugins() {
      var _this4 = this;
      var properties = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var whitelist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var blacklist = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
      if (!Object.keys(this.plugins).length) {
        return;
      }
      this.properties = properties;
      this.allowed_plugins = {};
      for (var _i2 = 0, _Object$entries2 = Object.entries(this.plugins); _i2 < _Object$entries2.length; _i2++) {
        var _Object$entries2$_i = pluggable_slicedToArray(_Object$entries2[_i2], 2),
          key = _Object$entries2$_i[0],
          plugin = _Object$entries2$_i[1];
        if ((!whitelist.length || whitelist.includes(key)) && !blacklist.includes(key)) {
          this.allowed_plugins[key] = plugin;
        }
      }
      Object.values(this.allowed_plugins).forEach(function (o) {
        return _this4.initializePlugin(o);
      });
    }
  }]);
  return PluginSocket;
}();
function enable(object, name, attrname) {
  // Call the `enable` method to make an object pluggable
  //
  // It takes three parameters:
  // - `object`: The object that gets made pluggable.
  // - `name`: The string name by which the now pluggable object
  //     may be referenced on the __super__ obj (in overrides).
  //     The default value is "plugged".
  // - `attrname`: The string name of the attribute on the now
  //     pluggable object, which refers to the PluginSocket instance
  //     that gets created.
  if (typeof attrname === "undefined") {
    attrname = "pluginSocket";
  }
  if (typeof name === 'undefined') {
    name = 'plugged';
  }
  object[attrname] = new PluginSocket(object, name);
  return object;
}

/* harmony default export */ const pluggable = ({
  enable: enable
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseEach.js


/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseEach(eachFunc, fromRight) {
  return function (collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!lodash_es_isArrayLike(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length,
      index = fromRight ? length : -1,
      iterable = Object(collection);
    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}
/* harmony default export */ const _createBaseEach = (createBaseEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEach.js



/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */
var baseEach = _createBaseEach(_baseForOwn);
/* harmony default export */ const _baseEach = (baseEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSome.js


/**
 * The base implementation of `_.some` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function baseSome(collection, predicate) {
  var result;
  _baseEach(collection, function (value, index, collection) {
    result = predicate(value, index, collection);
    return !result;
  });
  return !!result;
}
/* harmony default export */ const _baseSome = (baseSome);
;// CONCATENATED MODULE: ./node_modules/lodash-es/some.js






/**
 * Checks if `predicate` returns truthy for **any** element of `collection`.
 * Iteration is stopped once `predicate` returns truthy. The predicate is
 * invoked with three arguments: (value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 * @example
 *
 * _.some([null, 0, 'yes', false], Boolean);
 * // => true
 *
 * var users = [
 *   { 'user': 'barney', 'active': true },
 *   { 'user': 'fred',   'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.some(users, { 'user': 'barney', 'active': false });
 * // => false
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.some(users, ['active', false]);
 * // => true
 *
 * // The `_.property` iteratee shorthand.
 * _.some(users, 'active');
 * // => true
 */
function some(collection, predicate, guard) {
  var func = lodash_es_isArray(collection) ? _arraySome : _baseSome;
  if (guard && _isIterateeCall(collection, predicate, guard)) {
    predicate = undefined;
  }
  return func(collection, _baseIteratee(predicate, 3));
}
/* harmony default export */ const lodash_es_some = (some);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/history.js
//  Backbone.js 1.4.0
//  (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//  Backbone may be freely distributed under the MIT license.






// History
// -------

// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var history_History = function History() {
  this.handlers = [];
  this.checkUrl = this.checkUrl.bind(this);

  // Ensure that `History` can be used outside of the browser.
  if (typeof window !== 'undefined') {
    this.location = window.location;
    this.history = window.history;
  }
};
history_History.extend = inherits;

// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for stripping urls of hash.
var pathStripper = /#.*$/;

// Has the history handling already been started?
history_History.started = false;

// Set up all inheritable **History** properties and methods.
Object.assign(history_History.prototype, Events, {
  // The default interval to poll for hash changes, if necessary, is
  // twenty times a second.
  interval: 50,
  // Are we at the app root?
  atRoot: function atRoot() {
    var path = this.location.pathname.replace(/[^\/]$/, '$&/');
    return path === this.root && !this.getSearch();
  },
  // Does the pathname match the root?
  matchRoot: function matchRoot() {
    var path = this.decodeFragment(this.location.pathname);
    var rootPath = path.slice(0, this.root.length - 1) + '/';
    return rootPath === this.root;
  },
  // Unicode characters in `location.pathname` are percent encoded so they're
  // decoded for comparison. `%25` should not be decoded since it may be part
  // of an encoded parameter.
  decodeFragment: function decodeFragment(fragment) {
    return decodeURI(fragment.replace(/%25/g, '%2525'));
  },
  // In IE6, the hash fragment and search params are incorrect if the
  // fragment contains `?`.
  getSearch: function getSearch() {
    var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
    return match ? match[0] : '';
  },
  // Gets the true hash value. Cannot use location.hash directly due to bug
  // in Firefox where location.hash will always be decoded.
  getHash: function getHash(window) {
    var match = (window || this).location.href.match(/#(.*)$/);
    return match ? match[1] : '';
  },
  // Get the pathname and search params, without the root.
  getPath: function getPath() {
    var path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1);
    return path.charAt(0) === '/' ? path.slice(1) : path;
  },
  // Get the cross-browser normalized URL fragment from the path or hash.
  getFragment: function getFragment(fragment) {
    if (fragment == null) {
      if (this._usePushState || !this._wantsHashChange) {
        fragment = this.getPath();
      } else {
        fragment = this.getHash();
      }
    }
    return fragment.replace(routeStripper, '');
  },
  // Start the hash change handling, returning `true` if the current URL matches
  // an existing route, and `false` otherwise.
  start: function start(options) {
    if (history_History.started) throw new Error('history has already been started');
    history_History.started = true;

    // Figure out the initial configuration. Do we need an iframe?
    // Is pushState desired ... is it available?
    this.options = lodash_es_assignIn({
      root: '/'
    }, this.options, options);
    this.root = this.options.root;
    this._wantsHashChange = this.options.hashChange !== false;
    this._hasHashChange = 'onhashchange' in window && (document.documentMode === undefined || document.documentMode > 7);
    this._useHashChange = this._wantsHashChange && this._hasHashChange;
    this._wantsPushState = !!this.options.pushState;
    this._hasPushState = !!(this.history && this.history.pushState);
    this._usePushState = this._wantsPushState && this._hasPushState;
    this.fragment = this.getFragment();

    // Normalize root to always include a leading and trailing slash.
    this.root = ('/' + this.root + '/').replace(rootStripper, '/');

    // Transition from hashChange to pushState or vice versa if both are
    // requested.
    if (this._wantsHashChange && this._wantsPushState) {
      // If we've started off with a route from a `pushState`-enabled
      // browser, but we're currently in a browser that doesn't support it...
      if (!this._hasPushState && !this.atRoot()) {
        var rootPath = this.root.slice(0, -1) || '/';
        this.location.replace(rootPath + '#' + this.getPath());
        // Return immediately as browser will do redirect to new url
        return true;

        // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
      } else if (this._hasPushState && this.atRoot()) {
        this.navigate(this.getHash(), {
          replace: true
        });
      }
    }

    // Proxy an iframe to handle location events if the browser doesn't
    // support the `hashchange` event, HTML5 history, or the user wants
    // `hashChange` but not `pushState`.
    if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
      this.iframe = document.createElement('iframe');
      this.iframe.src = 'javascript:0';
      this.iframe.style.display = 'none';
      this.iframe.tabIndex = -1;
      var body = document.body;
      // Using `appendChild` will throw on IE < 9 if the document is not ready.
      var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
      iWindow.document.open();
      iWindow.document.close();
      iWindow.location.hash = '#' + this.fragment;
    }

    // Depending on whether we're using pushState or hashes, and whether
    // 'onhashchange' is supported, determine how we check the URL state.
    if (this._usePushState) {
      addEventListener('popstate', this.checkUrl, false);
    } else if (this._useHashChange && !this.iframe) {
      addEventListener('hashchange', this.checkUrl, false);
    } else if (this._wantsHashChange) {
      this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
    }
    if (!this.options.silent) return this.loadUrl();
  },
  // Disable history, perhaps temporarily. Not useful in a real app,
  // but possibly useful for unit testing Routers.
  stop: function stop() {
    // Remove window listeners.
    if (this._usePushState) {
      removeEventListener('popstate', this.checkUrl, false);
    } else if (this._useHashChange && !this.iframe) {
      removeEventListener('hashchange', this.checkUrl, false);
    }

    // Clean up the iframe if necessary.
    if (this.iframe) {
      document.body.removeChild(this.iframe);
      this.iframe = null;
    }

    // Some environments will throw when clearing an undefined interval.
    if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
    history_History.started = false;
  },
  // Add a route to be tested when the fragment changes. Routes added later
  // may override previous routes.
  route: function route(_route, callback) {
    this.handlers.unshift({
      route: _route,
      callback: callback
    });
  },
  // Checks the current URL to see if it has changed, and if it has,
  // calls `loadUrl`, normalizing across the hidden iframe.
  checkUrl: function checkUrl(e) {
    var current = this.getFragment();

    // If the user pressed the back button, the iframe's hash will have
    // changed and we should use that for comparison.
    if (current === this.fragment && this.iframe) {
      current = this.getHash(this.iframe.contentWindow);
    }
    if (current === this.fragment) return false;
    if (this.iframe) this.navigate(current);
    this.loadUrl();
  },
  // Attempt to load the current URL fragment. If a route succeeds with a
  // match, returns `true`. If no defined routes matches the fragment,
  // returns `false`.
  loadUrl: function loadUrl(fragment) {
    // If the root doesn't match, no routes can match either.
    if (!this.matchRoot()) return false;
    fragment = this.fragment = this.getFragment(fragment);
    return lodash_es_some(this.handlers, function (handler) {
      if (handler.route.test(fragment)) {
        handler.callback(fragment);
        return true;
      }
    });
  },
  // Save a fragment into the hash history, or replace the URL state if the
  // 'replace' option is passed. You are responsible for properly URL-encoding
  // the fragment in advance.
  //
  // The options object can contain `trigger: true` if you wish to have the
  // route callback be fired (not usually desirable), or `replace: true`, if
  // you wish to modify the current URL without adding an entry to the history.
  navigate: function navigate(fragment, options) {
    if (!history_History.started) return false;
    if (!options || options === true) options = {
      trigger: !!options
    };

    // Normalize the fragment.
    fragment = this.getFragment(fragment || '');

    // Don't include a trailing slash on the root.
    var rootPath = this.root;
    if (fragment === '' || fragment.charAt(0) === '?') {
      rootPath = rootPath.slice(0, -1) || '/';
    }
    var url = rootPath + fragment;

    // Strip the fragment of the query and hash for matching.
    fragment = fragment.replace(pathStripper, '');

    // Decode for matching.
    var decodedFragment = this.decodeFragment(fragment);
    if (this.fragment === decodedFragment) return;
    this.fragment = decodedFragment;

    // If pushState is available, we use it to set the fragment as a real URL.
    if (this._usePushState) {
      this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
    } else if (this._wantsHashChange) {
      this._updateHash(this.location, fragment, options.replace);
      if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
        var iWindow = this.iframe.contentWindow;

        // Opening and closing the iframe tricks IE7 and earlier to push a
        // history entry on hash-tag change.  When replace is true, we don't
        // want this.
        if (!options.replace) {
          iWindow.document.open();
          iWindow.document.close();
        }
        this._updateHash(iWindow.location, fragment, options.replace);
      }
      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
    } else {
      return this.location.assign(url);
    }
    if (options.trigger) return this.loadUrl(fragment);
  },
  // Update the hash location, either replacing the current entry, or adding
  // a new one to the browser history.
  _updateHash: function _updateHash(location, fragment, replace) {
    if (replace) {
      var href = location.href.replace(/(javascript:|#).*$/, '');
      location.replace(href + '#' + fragment);
    } else {
      // Some browsers require that `hash` contains a leading #.
      location.hash = '#' + fragment;
    }
  }
});
/* harmony default export */ const src_history = (history_History);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsRegExp.js



/** `Object#toString` result references. */
var _baseIsRegExp_regexpTag = '[object RegExp]';

/**
 * The base implementation of `_.isRegExp` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
 */
function baseIsRegExp(value) {
  return lodash_es_isObjectLike(value) && _baseGetTag(value) == _baseIsRegExp_regexpTag;
}
/* harmony default export */ const _baseIsRegExp = (baseIsRegExp);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isRegExp.js




/* Node.js helper references. */
var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp;

/**
 * Checks if `value` is classified as a `RegExp` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
 * @example
 *
 * _.isRegExp(/abc/);
 * // => true
 *
 * _.isRegExp('/abc/');
 * // => false
 */
var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp;
/* harmony default export */ const lodash_es_isRegExp = (isRegExp);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/router.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.

// Router
// ------










// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = function Router() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  this.history = options.history || new src_history();
  this.preinitialize.apply(this, arguments);
  if (options.routes) this.routes = options.routes;
  this._bindRoutes();
  this.initialize.apply(this, arguments);
};
Router.extend = inherits;

// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;

// Set up all inheritable **Router** properties and methods.
Object.assign(Router.prototype, Events, {
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Router.
  preinitialize: function preinitialize() {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function initialize() {},
  // Manually bind a single named route to a callback. For example:
  //
  //     this.route('search/:query/p:num', 'search', function(query, num) {
  //       ...
  //     });
  //
  route: function route(_route, name, callback) {
    var _this = this;
    if (!lodash_es_isRegExp(_route)) _route = this._routeToRegExp(_route);
    if (lodash_es_isFunction(name)) {
      callback = name;
      name = '';
    }
    if (!callback) callback = this[name];
    this.history.route(_route, function (fragment) {
      var args = _this._extractParameters(_route, fragment);
      if (_this.execute(callback, args, name) !== false) {
        _this.trigger.apply(_this, ['route:' + name].concat(args));
        _this.trigger('route', name, args);
        _this.history.trigger('route', _this, name, args);
      }
    });
    return this;
  },
  // Execute a route handler with the provided parameters.  This is an
  // excellent place to do pre-route setup or post-route cleanup.
  execute: function execute(callback, args, name) {
    if (callback) callback.apply(this, args);
  },
  // Simple proxy to `history` to save a fragment into the history.
  navigate: function navigate(fragment, options) {
    this.history.navigate(fragment, options);
    return this;
  },
  // Bind all defined routes to `history`. We have to reverse the
  // order of the routes here to support behavior where the most general
  // routes can be defined at the bottom of the route map.
  _bindRoutes: function _bindRoutes() {
    if (!this.routes) return;
    this.routes = lodash_es_result(this, 'routes');
    var route;
    var routes = lodash_es_keys(this.routes);
    while ((route = routes.pop()) != null) {
      this.route(route, this.routes[route]);
    }
  },
  // Convert a route string into a regular expression, suitable for matching
  // against the current location hash.
  _routeToRegExp: function _routeToRegExp(route) {
    route = route.replace(escapeRegExp, '\\$&').replace(optionalParam, '(?:$1)?').replace(namedParam, function (match, optional) {
      return optional ? match : '([^/?]+)';
    }).replace(splatParam, '([^?]*?)');
    return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
  },
  // Given a route, and a URL fragment that it matches, return the array of
  // extracted decoded parameters. Empty or unmatched parameters will be
  // treated as `null` to normalize cross-browser behavior.
  _extractParameters: function _extractParameters(route, fragment) {
    var params = route.exec(fragment).slice(1);
    return params.map(function (param, i) {
      // Don't decode the search params.
      if (i === params.length - 1) return param || null;
      return param ? decodeURIComponent(param) : null;
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/shared/_converse.js











/**
 * A private, closured object containing the private api (via {@link _converse.api})
 * as well as private methods and internal data-structures.
 * @global
 * @namespace _converse
 */
var _converse = {
  log: log,
  shouldClearCache: shouldClearCache,
  // TODO: Should be moved to utils with next major release
  VERSION_NAME: VERSION_NAME,
  templates: {},
  promises: {
    'initialized': getOpenPromise()
  },
  // TODO: remove constants in next major release
  ANONYMOUS: ANONYMOUS,
  CLOSED: CLOSED,
  EXTERNAL: EXTERNAL,
  LOGIN: LOGIN,
  LOGOUT: LOGOUT,
  OPENED: OPENED,
  PREBIND: PREBIND,
  SUCCESS: SUCCESS,
  FAILURE: FAILURE,
  DEFAULT_IMAGE_TYPE: DEFAULT_IMAGE_TYPE,
  DEFAULT_IMAGE: DEFAULT_IMAGE,
  INACTIVE: INACTIVE,
  ACTIVE: ACTIVE,
  COMPOSING: COMPOSING,
  PAUSED: PAUSED,
  GONE: GONE,
  PRIVATE_CHAT_TYPE: PRIVATE_CHAT_TYPE,
  CHATROOMS_TYPE: CHATROOMS_TYPE,
  HEADLINES_TYPE: HEADLINES_TYPE,
  CONTROLBOX_TYPE: CONTROLBOX_TYPE,
  // Set as module attr so that we can override in tests.
  // TODO: replace with config settings
  TIMEOUTS: {
    PAUSED: 10000,
    INACTIVE: 90000
  },
  default_connection_options: {
    'explicitResourceBinding': true
  },
  router: new Router(),
  isTestEnv: function isTestEnv() {
    return getInitSettings()['bosh_service_url'] === 'montague.lit/http-bind';
  },
  getDefaultStore: getDefaultStore,
  createStore: createStore,
  /**
   * Translate the given string based on the current locale.
   * @method __
   * @private
   * @memberOf _converse
   * @param { String } str
   */
  '__': function __() {
    return i18n.__.apply(i18n, arguments);
  },
  /**
   * A no-op method which is used to signal to gettext that the passed in string
   * should be included in the pot translation file.
   *
   * In contrast to the double-underscore method, the triple underscore method
   * doesn't actually translate the strings.
   *
   * One reason for this method might be because we're using strings we cannot
   * send to the translation function because they require variable interpolation
   * and we don't yet have the variables at scan time.
   *
   * @method ___
   * @private
   * @memberOf _converse
   * @param { String } str
   */
  '___': function ___(str) {
    return str;
  }
};

// Make _converse an event emitter
Object.assign(_converse, Events);

// Make _converse pluggable
pluggable.enable(_converse, '_converse', 'pluggable');
/* harmony default export */ const shared_converse = (_converse);
// EXTERNAL MODULE: ./node_modules/dayjs/plugin/advancedFormat.js
var advancedFormat = __webpack_require__(4289);
var advancedFormat_default = /*#__PURE__*/__webpack_require__.n(advancedFormat);
;// CONCATENATED MODULE: ./src/headless/shared/connection/api.js



/**
 * This grouping collects API functions related to the XMPP connection.
 *
 * @namespace _converse.api.connection
 * @memberOf _converse.api
 */
/* harmony default export */ const api = ({
  /**
   * @method _converse.api.connection.authenticated
   * @memberOf _converse.api.connection
   * @returns {boolean} Whether we're authenticated to the XMPP server or not
   */
  authenticated: function authenticated() {
    var _converse$connection;
    return (shared_converse === null || shared_converse === void 0 ? void 0 : (_converse$connection = shared_converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.authenticated) && true;
  },
  /**
   * @method _converse.api.connection.connected
   * @memberOf _converse.api.connection
   * @returns {boolean} Whether there is an established connection or not.
   */
  connected: function connected() {
    var _converse$connection2;
    return (shared_converse === null || shared_converse === void 0 ? void 0 : (_converse$connection2 = shared_converse.connection) === null || _converse$connection2 === void 0 ? void 0 : _converse$connection2.connected) && true;
  },
  /**
   * Terminates the connection.
   *
   * @method _converse.api.connection.disconnect
   * @memberOf _converse.api.connection
   */
  disconnect: function disconnect() {
    if (shared_converse.connection) {
      shared_converse.connection.disconnect();
    }
  },
  /**
   * Can be called once the XMPP connection has dropped and we want
   * to attempt reconnection.
   * Only needs to be called once, if reconnect fails Converse will
   * attempt to reconnect every two seconds, alternating between BOSH and
   * Websocket if URLs for both were provided.
   * @method reconnect
   * @memberOf _converse.api.connection
   */
  reconnect: function reconnect() {
    var __ = shared_converse.__,
      connection = shared_converse.connection;
    connection.setConnectionStatus(external_strophe_namespaceObject.Strophe.Status.RECONNECTING, __('The connection has dropped, attempting to reconnect.'));
    if (connection !== null && connection !== void 0 && connection.reconnecting) {
      return connection.debouncedReconnect();
    } else {
      return connection.reconnect();
    }
  },
  /**
   * Utility method to determine the type of connection we have
   * @method isType
   * @memberOf _converse.api.connection
   * @returns {boolean}
   */
  isType: function isType(type) {
    return shared_converse.connection.isType(type);
  }
});
;// CONCATENATED MODULE: ./src/headless/shared/api/events.js
function api_events_typeof(obj) {
  "@babel/helpers - typeof";

  return api_events_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;
  }, api_events_typeof(obj);
}
function events_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  events_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" == api_events_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 events_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 events_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        events_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        events_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


/* harmony default export */ const events = ({
  /**
   * Lets you trigger events, which can be listened to via
   * {@link _converse.api.listen.on} or {@link _converse.api.listen.once}
   * (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
   *
   * Some events also double as promises and can be waited on via {@link _converse.api.waitUntil}.
   *
   * @method _converse.api.trigger
   * @param { string } name - The event name
   * @param {...any} [argument] - Argument to be passed to the event handler
   * @param { object } [options]
   * @param { boolean } [options.synchronous] - Whether the event is synchronous or not.
   *  When a synchronous event is fired, a promise will be returned
   *  by {@link _converse.api.trigger} which resolves once all the
   *  event handlers' promises have been resolved.
   */
  trigger: function trigger(name) {
    var _arguments = arguments;
    return events_asyncToGenerator( /*#__PURE__*/events_regeneratorRuntime().mark(function _callee() {
      var args, options, events, event_args, promise;
      return events_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (shared_converse._events) {
              _context.next = 2;
              break;
            }
            return _context.abrupt("return");
          case 2:
            args = Array.from(_arguments);
            options = args.pop();
            if (!(options && options.synchronous)) {
              _context.next = 11;
              break;
            }
            events = shared_converse._events[name] || [];
            event_args = args.splice(1);
            _context.next = 9;
            return Promise.all(events.map(function (e) {
              return e.callback.apply(e.ctx, event_args);
            }));
          case 9:
            _context.next = 12;
            break;
          case 11:
            shared_converse.trigger.apply(shared_converse, _arguments);
          case 12:
            promise = shared_converse.promises[name];
            if (promise !== undefined) {
              promise.resolve();
            }
          case 14:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * Triggers a hook which can be intercepted by registered listeners via
   * {@link _converse.api.listen.on} or {@link _converse.api.listen.once}.
   * (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
   * A hook is a special kind of event which allows you to intercept a data
   * structure in order to modify it, before passing it back.
   * @async
   * @param { string } name - The hook name
   * @param {...any} context - The context to which the hook applies (could be for example, a {@link _converse.ChatBox})).
   * @param {...any} data - The data structure to be intercepted and modified by the hook listeners.
   * @returns {Promise<any>} - A promise that resolves with the modified data structure.
   */
  hook: function hook(name, context, data) {
    var events = shared_converse._events[name] || [];
    if (events.length) {
      // Create a chain of promises, with each one feeding its output to
      // the next. The first input is a promise with the original data
      // sent to this hook.
      return events.reduce(function (o, e) {
        return o.then(function (d) {
          return e.callback(context, d);
        });
      }, Promise.resolve(data));
    } else {
      return data;
    }
  },
  /**
   * Converse emits events to which you can subscribe to.
   *
   * The `listen` namespace exposes methods for creating event listeners
   * (aka handlers) for these events.
   *
   * @namespace _converse.api.listen
   * @memberOf _converse
   */
  listen: {
    /**
     * Lets you listen to an event exactly once.
     * @method _converse.api.listen.once
     * @param { string } name The event's name
     * @param { function } callback The callback method to be called when the event is emitted.
     * @param { object } [context] The value of the `this` parameter for the callback.
     * @example _converse.api.listen.once('message', function (messageXML) { ... });
     */
    once: shared_converse.once.bind(shared_converse),
    /**
     * Lets you subscribe to an event.
     * Every time the event fires, the callback method specified by `callback` will be called.
     * @method _converse.api.listen.on
     * @param { string } name The event's name
     * @param { function } callback The callback method to be called when the event is emitted.
     * @param { object } [context] The value of the `this` parameter for the callback.
     * @example _converse.api.listen.on('message', function (messageXML) { ... });
     */
    on: shared_converse.on.bind(shared_converse),
    /**
     * To stop listening to an event, you can use the `not` method.
     * @method _converse.api.listen.not
     * @param { string } name The event's name
     * @param { function } callback The callback method that is to no longer be called when the event fires
     * @example _converse.api.listen.not('message', function (messageXML);
     */
    not: shared_converse.off.bind(shared_converse),
    /**
     * Subscribe to an incoming stanza
     * Every a matched stanza is received, the callback method specified by
     * `callback` will be called.
     * @method _converse.api.listen.stanza
     * @param { string } name The stanza's name
     * @param { object } options Matching options (e.g. 'ns' for namespace, 'type' for stanza type, also 'id' and 'from');
     * @param { function } handler The callback method to be called when the stanza appears
     */
    stanza: function stanza(name, options, handler) {
      if (core(options)) {
        handler = options;
        options = {};
      } else {
        options = options || {};
      }
      shared_converse.connection.addHandler(handler, options.ns, name, options.type, options.id, options.from, options);
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/shared/api/promise.js



/* harmony default export */ const promise = ({
  /**
   * Converse and its plugins trigger various events which you can listen to via the
   * {@link _converse.api.listen} namespace.
   *
   * Some of these events are also available as [ES2015 Promises](http://es6-features.org/#PromiseUsage)
   * although not all of them could logically act as promises, since some events
   * might be fired multpile times whereas promises are to be resolved (or
   * rejected) only once.
   *
   * Events which are also promises include:
   *
   * * [cachedRoster](/docs/html/events.html#cachedroster)
   * * [chatBoxesFetched](/docs/html/events.html#chatBoxesFetched)
   * * [pluginsInitialized](/docs/html/events.html#pluginsInitialized)
   * * [roster](/docs/html/events.html#roster)
   * * [rosterContactsFetched](/docs/html/events.html#rosterContactsFetched)
   * * [rosterGroupsFetched](/docs/html/events.html#rosterGroupsFetched)
   * * [rosterInitialized](/docs/html/events.html#rosterInitialized)
   *
   * The various plugins might also provide promises, and they do this by using the
   * `promises.add` api method.
   *
   * @namespace _converse.api.promises
   * @memberOf _converse.api
   */
  promises: {
    /**
     * By calling `promises.add`, a new [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
     * is made available for other code or plugins to depend on via the
     * {@link _converse.api.waitUntil} method.
     *
     * Generally, it's the responsibility of the plugin which adds the promise to
     * also resolve it.
     *
     * This is done by calling {@link _converse.api.trigger}, which not only resolves the
     * promise, but also emits an event with the same name (which can be listened to
     * via {@link _converse.api.listen}).
     *
     * @method _converse.api.promises.add
     * @param {string|array} [name|names] The name or an array of names for the promise(s) to be added
     * @param { boolean } [replace=true] Whether this promise should be replaced with a new one when the user logs out.
     * @example _converse.api.promises.add('foo-completed');
     */
    add: function add(promises) {
      var replace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      promises = Array.isArray(promises) ? promises : [promises];
      promises.forEach(function (name) {
        var promise = getOpenPromise();
        promise.replace = replace;
        shared_converse.promises[name] = promise;
      });
    }
  },
  /**
   * Wait until a promise is resolved or until the passed in function returns
   * a truthy value.
   * @method _converse.api.waitUntil
   * @param {string|function} condition - The name of the promise to wait for,
   * or a function which should eventually return a truthy value.
   * @returns {Promise}
   */
  waitUntil: function waitUntil(condition) {
    if (core_isFunction(condition)) {
      return core_waitUntil(condition);
    } else {
      var promise = shared_converse.promises[condition];
      if (promise === undefined) {
        return null;
      }
      return promise;
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/shared/errors.js
function errors_typeof(obj) {
  "@babel/helpers - typeof";

  return errors_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;
  }, errors_typeof(obj);
}
function errors_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, errors_toPropertyKey(descriptor.key), descriptor);
  }
}
function errors_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) errors_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) errors_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function errors_toPropertyKey(arg) {
  var key = errors_toPrimitive(arg, "string");
  return errors_typeof(key) === "symbol" ? key : String(key);
}
function errors_toPrimitive(input, hint) {
  if (errors_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (errors_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function errors_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function errors_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) errors_setPrototypeOf(subClass, superClass);
}
function errors_createSuper(Derived) {
  var hasNativeReflectConstruct = errors_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = errors_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = errors_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return errors_possibleConstructorReturn(this, result);
  };
}
function errors_possibleConstructorReturn(self, call) {
  if (call && (errors_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 errors_assertThisInitialized(self);
}
function errors_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function errors_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  errors_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !errors_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return errors_construct(Class, arguments, errors_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return errors_setPrototypeOf(Wrapper, Class);
  };
  return errors_wrapNativeSuper(Class);
}
function errors_construct(Parent, args, Class) {
  if (errors_isNativeReflectConstruct()) {
    errors_construct = Reflect.construct.bind();
  } else {
    errors_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) errors_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return errors_construct.apply(null, arguments);
}
function errors_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 errors_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function errors_setPrototypeOf(o, p) {
  errors_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return errors_setPrototypeOf(o, p);
}
function errors_getPrototypeOf(o) {
  errors_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return errors_getPrototypeOf(o);
}
/**
 * Custom error for indicating timeouts
 * @namespace converse.env
 */
var TimeoutError = /*#__PURE__*/function (_Error) {
  errors_inherits(TimeoutError, _Error);
  var _super = errors_createSuper(TimeoutError);
  function TimeoutError() {
    errors_classCallCheck(this, TimeoutError);
    return _super.apply(this, arguments);
  }
  return errors_createClass(TimeoutError);
}( /*#__PURE__*/errors_wrapNativeSuper(Error));
;// CONCATENATED MODULE: ./src/headless/shared/api/send.js





/* harmony default export */ const send = ({
  /**
   * Allows you to send XML stanzas.
   * @method _converse.api.send
   * @param { Element | Stanza } stanza
   * @return { void }
   * @example
   * const msg = converse.env.$msg({
   *     'from': 'juliet@example.com/balcony',
   *     'to': 'romeo@example.net',
   *     'type':'chat'
   * });
   * _converse.api.send(msg);
   */
  send: function send(stanza) {
    var _stanza;
    var api = shared_converse.api;
    if (!api.connection.connected()) {
      log.warn("Not sending stanza because we're not connected!");
      log.warn(external_strophe_namespaceObject.Strophe.serialize(stanza));
      return;
    }
    if (typeof stanza === 'string') {
      stanza = toStanza(stanza);
    } else if ((_stanza = stanza) !== null && _stanza !== void 0 && _stanza.tree) {
      stanza = stanza.tree();
    }
    if (stanza.tagName === 'iq') {
      return api.sendIQ(stanza);
    } else {
      shared_converse.connection.send(stanza);
      api.trigger('send', stanza);
    }
  },
  /**
   * Send an IQ stanza
   * @method _converse.api.sendIQ
   * @param { Element } stanza
   * @param { number } [timeout] - The default timeout value is taken from
   *  the `stanza_timeout` configuration setting.
   * @param { Boolean } [reject=true] - Whether an error IQ should cause the promise
   *  to be rejected. If `false`, the promise will resolve instead of being rejected.
   * @returns { Promise } A promise which resolves (or potentially rejected) once we
   *  receive a `result` or `error` stanza or once a timeout is reached.
   *  If the IQ stanza being sent is of type `result` or `error`, there's
   *  nothing to wait for, so an already resolved promise is returned.
   */
  sendIQ: function sendIQ(stanza, timeout) {
    var _stanza$tree, _stanza$tree2, _stanza2;
    var reject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
    var api = shared_converse.api,
      connection = shared_converse.connection;
    var promise;
    stanza = (_stanza$tree = (_stanza$tree2 = (_stanza2 = stanza).tree) === null || _stanza$tree2 === void 0 ? void 0 : _stanza$tree2.call(_stanza2)) !== null && _stanza$tree !== void 0 ? _stanza$tree : stanza;
    if (['get', 'set'].includes(stanza.getAttribute('type'))) {
      timeout = timeout || api.settings.get('stanza_timeout');
      if (reject) {
        promise = new Promise(function (resolve, reject) {
          return connection.sendIQ(stanza, resolve, reject, timeout);
        });
        promise.catch(function (e) {
          if (e === null) {
            throw new TimeoutError("Timeout error after ".concat(timeout, "ms for the following IQ stanza: ").concat(external_strophe_namespaceObject.Strophe.serialize(stanza)));
          }
        });
      } else {
        promise = new Promise(function (resolve) {
          return connection.sendIQ(stanza, resolve, resolve, timeout);
        });
      }
    } else {
      shared_converse.connection.sendIQ(stanza);
      promise = Promise.resolve();
    }
    api.trigger('send', stanza);
    return promise;
  }
});
;// CONCATENATED MODULE: ./src/headless/shared/api/presence.js
function presence_typeof(obj) {
  "@babel/helpers - typeof";

  return presence_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;
  }, presence_typeof(obj);
}
function presence_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  presence_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" == presence_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 presence_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 presence_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        presence_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        presence_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

/* harmony default export */ const presence = ({
  /**
   * @namespace _converse.api.user.presence
   * @memberOf _converse.api.user
   */
  presence: {
    /**
     * Send out a presence stanza
     * @method _converse.api.user.presence.send
     * @param { String } [type]
     * @param { String } [to]
     * @param { String } [status] - An optional status message
     * @param { Array<Element>|Array<Strophe.Builder>|Element|Strophe.Builder } [child_nodes]
     *  Nodes(s) to be added as child nodes of the `presence` XML element.
     */
    send: function send(type, to, status, child_nodes) {
      return presence_asyncToGenerator( /*#__PURE__*/presence_regeneratorRuntime().mark(function _callee() {
        var _child_nodes;
        var model, presence, mucs;
        return presence_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('statusInitialized');
            case 2:
              if (child_nodes && !Array.isArray(child_nodes)) {
                child_nodes = [child_nodes];
              }
              model = shared_converse.xmppstatus;
              _context.next = 6;
              return model.constructPresence(type, to, status);
            case 6:
              presence = _context.sent;
              (_child_nodes = child_nodes) === null || _child_nodes === void 0 ? void 0 : _child_nodes.map(function (c) {
                var _c$tree;
                return (_c$tree = c === null || c === void 0 ? void 0 : c.tree()) !== null && _c$tree !== void 0 ? _c$tree : c;
              }).forEach(function (c) {
                return presence.cnode(c).up();
              });
              shared_api.send(presence);
              if (!['away', 'chat', 'dnd', 'online', 'xa', undefined].includes(type)) {
                _context.next = 14;
                break;
              }
              _context.next = 12;
              return shared_api.rooms.get();
            case 12:
              mucs = _context.sent;
              mucs.forEach(function (muc) {
                return muc.sendStatusPresence(type, status, child_nodes);
              });
            case 14:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/debounce.js




/** Error message constants. */
var debounce_FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var debounce_nativeMax = Math.max,
  debounce_nativeMin = Math.min;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide `options` to indicate whether `func` should be invoked on the
 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent
 * calls to the debounced function return the result of the last `func`
 * invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the debounced function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=false]
 *  Specify invoking on the leading edge of the timeout.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function debounce(func, wait, options) {
  var lastArgs,
    lastThis,
    maxWait,
    result,
    timerId,
    lastCallTime,
    lastInvokeTime = 0,
    leading = false,
    maxing = false,
    trailing = true;
  if (typeof func != 'function') {
    throw new TypeError(debounce_FUNC_ERROR_TEXT);
  }
  wait = lodash_es_toNumber(wait) || 0;
  if (lodash_es_isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? debounce_nativeMax(lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }
  function invokeFunc(time) {
    var args = lastArgs,
      thisArg = lastThis;
    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }
  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time;
    // Start the timer for the trailing edge.
    timerId = setTimeout(timerExpired, wait);
    // Invoke the leading edge.
    return leading ? invokeFunc(time) : result;
  }
  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime,
      timeSinceLastInvoke = time - lastInvokeTime,
      timeWaiting = wait - timeSinceLastCall;
    return maxing ? debounce_nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
  }
  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime,
      timeSinceLastInvoke = time - lastInvokeTime;

    // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.
    return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  }
  function timerExpired() {
    var time = lodash_es_now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // Restart the timer.
    timerId = setTimeout(timerExpired, remainingWait(time));
  }
  function trailingEdge(time) {
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;
    return result;
  }
  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }
  function flush() {
    return timerId === undefined ? result : trailingEdge(lodash_es_now());
  }
  function debounced() {
    var time = lodash_es_now(),
      isInvoking = shouldInvoke(time);
    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;
    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}
/* harmony default export */ const lodash_es_debounce = (debounce);
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/local.js
var local = __webpack_require__(3710);
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/sync.js
var localforage_webextensionstorage_driver_sync = __webpack_require__(7777);
;// CONCATENATED MODULE: ./src/headless/shared/connection/index.js
function connection_typeof(obj) {
  "@babel/helpers - typeof";

  return connection_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;
  }, connection_typeof(obj);
}
function connection_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  connection_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" == connection_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 connection_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 connection_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        connection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        connection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function connection_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function connection_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, connection_toPropertyKey(descriptor.key), descriptor);
  }
}
function connection_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) connection_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) connection_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function connection_toPropertyKey(arg) {
  var key = connection_toPrimitive(arg, "string");
  return connection_typeof(key) === "symbol" ? key : String(key);
}
function connection_toPrimitive(input, hint) {
  if (connection_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (connection_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    _get = Reflect.get.bind();
  } else {
    _get = function _get(target, property, receiver) {
      var base = _superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return _get.apply(this, arguments);
}
function _superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = connection_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function connection_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) connection_setPrototypeOf(subClass, superClass);
}
function connection_setPrototypeOf(o, p) {
  connection_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return connection_setPrototypeOf(o, p);
}
function connection_createSuper(Derived) {
  var hasNativeReflectConstruct = connection_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = connection_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = connection_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return connection_possibleConstructorReturn(this, result);
  };
}
function connection_possibleConstructorReturn(self, call) {
  if (call && (connection_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 connection_assertThisInitialized(self);
}
function connection_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function connection_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 connection_getPrototypeOf(o) {
  connection_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return connection_getPrototypeOf(o);
}










var i = Object.keys(external_strophe_namespaceObject.Strophe.Status).reduce(function (max, k) {
  return Math.max(max, external_strophe_namespaceObject.Strophe.Status[k]);
}, 0);
external_strophe_namespaceObject.Strophe.Status.RECONNECTING = i + 1;

/**
 * The Connection class manages the connection to the XMPP server. It's
 * agnostic concerning the underlying protocol (i.e. websocket, long-polling
 * via BOSH or websocket inside a shared worker).
 */
var Connection = /*#__PURE__*/function (_Strophe$Connection) {
  connection_inherits(Connection, _Strophe$Connection);
  var _super = connection_createSuper(Connection);
  function Connection(service, options) {
    var _this;
    connection_classCallCheck(this, Connection);
    _this = _super.call(this, service, options);
    _this.debouncedReconnect = lodash_es_debounce(_this.reconnect, 3000);
    return _this;
  }
  connection_createClass(Connection, [{
    key: "bind",
    value: function () {
      var _bind = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee() {
        return connection_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.trigger('beforeResourceBinding', {
                'synchronous': true
              });
            case 2:
              _get(connection_getPrototypeOf(Connection.prototype), "bind", this).call(this);
            case 3:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function bind() {
        return _bind.apply(this, arguments);
      }
      return bind;
    }()
  }, {
    key: "onDomainDiscovered",
    value: function () {
      var _onDomainDiscovered = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee2(response) {
        var text, xrd, bosh_links, ws_links, bosh_methods, ws_methods;
        return connection_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return response.text();
            case 2:
              text = _context2.sent;
              xrd = new window.DOMParser().parseFromString(text, "text/xml").firstElementChild;
              if (!(xrd.nodeName != "XRD" || xrd.namespaceURI != "http://docs.oasis-open.org/ns/xri/xrd-1.0")) {
                _context2.next = 6;
                break;
              }
              return _context2.abrupt("return", log.warn("Could not discover XEP-0156 connection methods"));
            case 6:
              bosh_links = external_sizzle_default()("Link[rel=\"urn:xmpp:alt-connections:xbosh\"]", xrd);
              ws_links = external_sizzle_default()("Link[rel=\"urn:xmpp:alt-connections:websocket\"]", xrd);
              bosh_methods = bosh_links.map(function (el) {
                return el.getAttribute('href');
              });
              ws_methods = ws_links.map(function (el) {
                return el.getAttribute('href');
              });
              if (bosh_methods.length === 0 && ws_methods.length === 0) {
                log.warn("Neither BOSH nor WebSocket connection methods have been specified with XEP-0156.");
              } else {
                // TODO: support multiple endpoints
                shared_api.settings.set("websocket_url", ws_methods.pop());
                shared_api.settings.set('bosh_service_url', bosh_methods.pop());
                this.service = shared_api.settings.get("websocket_url") || shared_api.settings.get('bosh_service_url');
                this.setProtocol();
              }
            case 11:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function onDomainDiscovered(_x) {
        return _onDomainDiscovered.apply(this, arguments);
      }
      return onDomainDiscovered;
    }()
    /**
     * Adds support for XEP-0156 by quering the XMPP server for alternate
     * connection methods. This allows users to use the websocket or BOSH
     * connection of their own XMPP server instead of a proxy provided by the
     * host of Converse.js.
     * @method Connnection.discoverConnectionMethods
     */
  }, {
    key: "discoverConnectionMethods",
    value: function () {
      var _discoverConnectionMethods = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee3(domain) {
        var options, url, response;
        return connection_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              // Use XEP-0156 to check whether this host advertises websocket or BOSH connection methods.
              options = {
                'mode': 'cors',
                'headers': {
                  'Accept': 'application/xrd+xml, text/xml'
                }
              };
              url = "https://".concat(domain, "/.well-known/host-meta");
              _context3.prev = 2;
              _context3.next = 5;
              return fetch(url, options);
            case 5:
              response = _context3.sent;
              _context3.next = 13;
              break;
            case 8:
              _context3.prev = 8;
              _context3.t0 = _context3["catch"](2);
              log.error("Failed to discover alternative connection methods at ".concat(url));
              log.error(_context3.t0);
              return _context3.abrupt("return");
            case 13:
              if (!(response.status >= 200 && response.status < 400)) {
                _context3.next = 18;
                break;
              }
              _context3.next = 16;
              return this.onDomainDiscovered(response);
            case 16:
              _context3.next = 19;
              break;
            case 18:
              log.warn("Could not discover XEP-0156 connection methods");
            case 19:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this, [[2, 8]]);
      }));
      function discoverConnectionMethods(_x2) {
        return _discoverConnectionMethods.apply(this, arguments);
      }
      return discoverConnectionMethods;
    }()
    /**
     * Establish a new XMPP session by logging in with the supplied JID and
     * password.
     * @method Connnection.connect
     * @param { String } jid
     * @param { String } password
     * @param { Funtion } callback
     */
  }, {
    key: "connect",
    value: function () {
      var _connect = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee4(jid, password, callback) {
        var domain;
        return connection_regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              if (!shared_api.settings.get("discover_connection_methods")) {
                _context4.next = 4;
                break;
              }
              domain = external_strophe_namespaceObject.Strophe.getDomainFromJid(jid);
              _context4.next = 4;
              return this.discoverConnectionMethods(domain);
            case 4:
              if (!(!shared_api.settings.get('bosh_service_url') && !shared_api.settings.get("websocket_url"))) {
                _context4.next = 6;
                break;
              }
              throw new Error("You must supply a value for either the bosh_service_url or websocket_url or both.");
            case 6:
              _get(connection_getPrototypeOf(Connection.prototype), "connect", this).call(this, jid, password, callback || this.onConnectStatusChanged, BOSH_WAIT);
            case 7:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function connect(_x3, _x4, _x5) {
        return _connect.apply(this, arguments);
      }
      return connect;
    }()
    /**
     * Switch to a different transport if a service URL is available for it.
     *
     * When reconnecting with a new transport, we call setUserJID
     * so that a new resource is generated, to avoid multiple
     * server-side sessions with the same resource.
     *
     * We also call `_proto._doDisconnect` so that connection event handlers
     * for the old transport are removed.
     */
  }, {
    key: "switchTransport",
    value: function () {
      var _switchTransport = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee5() {
        return connection_regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              if (!(shared_api.connection.isType('websocket') && shared_api.settings.get('bosh_service_url'))) {
                _context5.next = 8;
                break;
              }
              _context5.next = 3;
              return setUserJID(shared_converse.bare_jid);
            case 3:
              this._proto._doDisconnect();
              this._proto = new external_strophe_namespaceObject.Strophe.Bosh(this);
              this.service = shared_api.settings.get('bosh_service_url');
              _context5.next = 19;
              break;
            case 8:
              if (!(shared_api.connection.isType('bosh') && shared_api.settings.get("websocket_url"))) {
                _context5.next = 19;
                break;
              }
              if (!(shared_api.settings.get("authentication") === ANONYMOUS)) {
                _context5.next = 14;
                break;
              }
              _context5.next = 12;
              return setUserJID(shared_api.settings.get("jid"));
            case 12:
              _context5.next = 16;
              break;
            case 14:
              _context5.next = 16;
              return setUserJID(shared_converse.bare_jid);
            case 16:
              this._proto._doDisconnect();
              this._proto = new external_strophe_namespaceObject.Strophe.Websocket(this);
              this.service = shared_api.settings.get("websocket_url");
            case 19:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function switchTransport() {
        return _switchTransport.apply(this, arguments);
      }
      return switchTransport;
    }()
  }, {
    key: "reconnect",
    value: function () {
      var _reconnect = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee6() {
        var conn_status;
        return connection_regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              log.debug('RECONNECTING: the connection has dropped, attempting to reconnect.');
              this.reconnecting = true;
              _context6.next = 4;
              return tearDown();
            case 4:
              conn_status = shared_converse.connfeedback.get('connection_status');
              if (!(conn_status === external_strophe_namespaceObject.Strophe.Status.CONNFAIL)) {
                _context6.next = 9;
                break;
              }
              this.switchTransport();
              _context6.next = 12;
              break;
            case 9:
              if (!(conn_status === external_strophe_namespaceObject.Strophe.Status.AUTHFAIL && shared_api.settings.get("authentication") === ANONYMOUS)) {
                _context6.next = 12;
                break;
              }
              _context6.next = 12;
              return setUserJID(shared_api.settings.get("jid"));
            case 12:
              /**
               * Triggered when the connection has dropped, but Converse will attempt
               * to reconnect again.
               * @event _converse#will-reconnect
               */
              shared_api.trigger('will-reconnect');
              if (!(shared_api.settings.get("authentication") === ANONYMOUS)) {
                _context6.next = 16;
                break;
              }
              _context6.next = 16;
              return clearSession();
            case 16:
              return _context6.abrupt("return", shared_api.user.login());
            case 17:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
      function reconnect() {
        return _reconnect.apply(this, arguments);
      }
      return reconnect;
    }()
    /**
     * Called as soon as a new connection has been established, either
     * by logging in or by attaching to an existing BOSH session.
     * @method Connection.onConnected
     * @param { Boolean } reconnecting - Whether Converse.js reconnected from an earlier dropped session.
     */
  }, {
    key: "onConnected",
    value: function () {
      var _onConnected = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee7(reconnecting) {
        return connection_regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              delete this.reconnecting;
              this.flush(); // Solves problem of returned PubSub BOSH response not received by browser
              _context7.next = 4;
              return setUserJID(this.jid);
            case 4:
              // Save the current JID in persistent storage so that we can attempt to
              // recreate the session from SCRAM keys
              if (shared_converse.config.get('trusted')) {
                localStorage.setItem('conversejs-session-jid', shared_converse.bare_jid);
              }

              /**
               * Synchronous event triggered after we've sent an IQ to bind the
               * user's JID resource for this session.
               * @event _converse#afterResourceBinding
               */
              _context7.next = 7;
              return shared_api.trigger('afterResourceBinding', reconnecting, {
                'synchronous': true
              });
            case 7:
              if (reconnecting) {
                /**
                 * After the connection has dropped and converse.js has reconnected.
                 * Any Strophe stanza handlers (as registered via `converse.listen.stanza`) will
                 * have to be registered anew.
                 * @event _converse#reconnected
                 * @example _converse.api.listen.on('reconnected', () => { ... });
                 */
                shared_api.trigger('reconnected');
              } else {
                /**
                 * Triggered after the connection has been established and Converse
                 * has got all its ducks in a row.
                 * @event _converse#initialized
                 */
                shared_api.trigger('connected');
              }
            case 8:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this);
      }));
      function onConnected(_x6) {
        return _onConnected.apply(this, arguments);
      }
      return onConnected;
    }()
    /**
     * Used to keep track of why we got disconnected, so that we can
     * decide on what the next appropriate action is (in onDisconnected)
     * @method Connection.setDisconnectionCause
     * @param { Number } cause - The status number as received from Strophe.
     * @param { String } [reason] - An optional user-facing message as to why
     *  there was a disconnection.
     * @param { Boolean } [override] - An optional flag to replace any previous
     *  disconnection cause and reason.
     */
  }, {
    key: "setDisconnectionCause",
    value: function setDisconnectionCause(cause, reason, override) {
      if (cause === undefined) {
        delete this.disconnection_cause;
        delete this.disconnection_reason;
      } else if (this.disconnection_cause === undefined || override) {
        this.disconnection_cause = cause;
        this.disconnection_reason = reason;
      }
    }
  }, {
    key: "setConnectionStatus",
    value: function setConnectionStatus(status, message) {
      this.status = status;
      shared_converse.connfeedback.set({
        'connection_status': status,
        message: message
      });
    }
  }, {
    key: "finishDisconnection",
    value: function () {
      var _finishDisconnection = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee8() {
        return connection_regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              // Properly tear down the session so that it's possible to manually connect again.
              log.debug('DISCONNECTED');
              delete this.reconnecting;
              this.reset();
              tearDown();
              _context8.next = 6;
              return clearSession();
            case 6:
              delete shared_converse.connection;
              /**
              * Triggered after converse.js has disconnected from the XMPP server.
              * @event _converse#disconnected
              * @memberOf _converse
              * @example _converse.api.listen.on('disconnected', () => { ... });
              */
              shared_api.trigger('disconnected');
            case 8:
            case "end":
              return _context8.stop();
          }
        }, _callee8, this);
      }));
      function finishDisconnection() {
        return _finishDisconnection.apply(this, arguments);
      }
      return finishDisconnection;
    }()
    /**
     * Gets called once strophe's status reaches Strophe.Status.DISCONNECTED.
     * Will either start a teardown process for converse.js or attempt
     * to reconnect.
     * @method onDisconnected
     */
  }, {
    key: "onDisconnected",
    value: function onDisconnected() {
      if (shared_api.settings.get("auto_reconnect")) {
        var reason = this.disconnection_reason;
        if (this.disconnection_cause === external_strophe_namespaceObject.Strophe.Status.AUTHFAIL) {
          if (shared_api.settings.get("credentials_url") || shared_api.settings.get("authentication") === ANONYMOUS) {
            // If `credentials_url` is set, we reconnect, because we might
            // be receiving expirable tokens from the credentials_url.
            //
            // If `authentication` is anonymous, we reconnect because we
            // might have tried to attach with stale BOSH session tokens
            // or with a cached JID and password
            return shared_api.connection.reconnect();
          } else {
            return this.finishDisconnection();
          }
        } else if (this.status === external_strophe_namespaceObject.Strophe.Status.CONNECTING) {
          // Don't try to reconnect if we were never connected to begin
          // with, otherwise an infinite loop can occur (e.g. when the
          // BOSH service URL returns a 404).
          var __ = shared_converse.__;
          this.setConnectionStatus(external_strophe_namespaceObject.Strophe.Status.CONNFAIL, __('An error occurred while connecting to the chat server.'));
          return this.finishDisconnection();
        } else if (this.disconnection_cause === LOGOUT || reason === external_strophe_namespaceObject.Strophe.ErrorCondition.NO_AUTH_MECH || reason === "host-unknown" || reason === "remote-connection-failed") {
          return this.finishDisconnection();
        }
        shared_api.connection.reconnect();
      } else {
        return this.finishDisconnection();
      }
    }

    /**
     * Callback method called by Strophe as the Connection goes
     * through various states while establishing or tearing down a
     * connection.
     * @param { Number } status
     * @param { String } message
     */
  }, {
    key: "onConnectStatusChanged",
    value: function onConnectStatusChanged(status, message) {
      var __ = shared_converse.__;
      log.debug("Status changed to: ".concat(CONNECTION_STATUS[status]));
      if (status === external_strophe_namespaceObject.Strophe.Status.ATTACHFAIL) {
        var _this$worker_attach_p;
        this.setConnectionStatus(status);
        (_this$worker_attach_p = this.worker_attach_promise) === null || _this$worker_attach_p === void 0 ? void 0 : _this$worker_attach_p.resolve(false);
      } else if (status === external_strophe_namespaceObject.Strophe.Status.CONNECTED || status === external_strophe_namespaceObject.Strophe.Status.ATTACHED) {
        var _this$worker_attach_p2, _this$worker_attach_p3;
        if ((_this$worker_attach_p2 = this.worker_attach_promise) !== null && _this$worker_attach_p2 !== void 0 && _this$worker_attach_p2.isResolved && this.status === external_strophe_namespaceObject.Strophe.Status.ATTACHED) {
          // A different tab must have attached, so nothing to do for us here.
          return;
        }
        this.setConnectionStatus(status);
        (_this$worker_attach_p3 = this.worker_attach_promise) === null || _this$worker_attach_p3 === void 0 ? void 0 : _this$worker_attach_p3.resolve(true);

        // By default we always want to send out an initial presence stanza.
        shared_converse.send_initial_presence = true;
        this.setDisconnectionCause();
        if (this.reconnecting) {
          log.debug(status === external_strophe_namespaceObject.Strophe.Status.CONNECTED ? 'Reconnected' : 'Reattached');
          this.onConnected(true);
        } else {
          log.debug(status === external_strophe_namespaceObject.Strophe.Status.CONNECTED ? 'Connected' : 'Attached');
          if (this.restored) {
            // No need to send an initial presence stanza when
            // we're restoring an existing session.
            shared_converse.send_initial_presence = false;
          }
          this.onConnected();
        }
      } else if (status === external_strophe_namespaceObject.Strophe.Status.DISCONNECTED) {
        this.setDisconnectionCause(status, message);
        this.onDisconnected();
      } else if (status === external_strophe_namespaceObject.Strophe.Status.BINDREQUIRED) {
        this.bind();
      } else if (status === external_strophe_namespaceObject.Strophe.Status.ERROR) {
        this.setConnectionStatus(status, __('An error occurred while connecting to the chat server.'));
      } else if (status === external_strophe_namespaceObject.Strophe.Status.CONNECTING) {
        this.setConnectionStatus(status);
      } else if (status === external_strophe_namespaceObject.Strophe.Status.AUTHENTICATING) {
        this.setConnectionStatus(status);
      } else if (status === external_strophe_namespaceObject.Strophe.Status.AUTHFAIL) {
        if (!message) {
          message = __('Your XMPP address and/or password is incorrect. Please try again.');
        }
        this.setConnectionStatus(status, message);
        this.setDisconnectionCause(status, message, true);
        this.onDisconnected();
      } else if (status === external_strophe_namespaceObject.Strophe.Status.CONNFAIL) {
        var _Strophe$ErrorConditi;
        var feedback = message;
        if (message === "host-unknown" || message == "remote-connection-failed") {
          feedback = __("Sorry, we could not connect to the XMPP host with domain: %1$s", "\"".concat(external_strophe_namespaceObject.Strophe.getDomainFromJid(this.jid), "\""));
        } else if (message !== undefined && message === (external_strophe_namespaceObject.Strophe === null || external_strophe_namespaceObject.Strophe === void 0 ? void 0 : (_Strophe$ErrorConditi = external_strophe_namespaceObject.Strophe.ErrorCondition) === null || _Strophe$ErrorConditi === void 0 ? void 0 : _Strophe$ErrorConditi.NO_AUTH_MECH)) {
          feedback = __("The XMPP server did not offer a supported authentication mechanism");
        }
        this.setConnectionStatus(status, feedback);
        this.setDisconnectionCause(status, message);
      } else if (status === external_strophe_namespaceObject.Strophe.Status.DISCONNECTING) {
        this.setDisconnectionCause(status, message);
      }
    }
  }, {
    key: "isType",
    value: function isType(type) {
      if (type.toLowerCase() === 'websocket') {
        return this._proto instanceof external_strophe_namespaceObject.Strophe.Websocket;
      } else if (type.toLowerCase() === 'bosh') {
        return external_strophe_namespaceObject.Strophe.Bosh && this._proto instanceof external_strophe_namespaceObject.Strophe.Bosh;
      }
    }
  }, {
    key: "hasResumed",
    value: function hasResumed() {
      var _api$settings$get;
      if ((_api$settings$get = shared_api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.worker || this.isType('bosh')) {
        return shared_converse.connfeedback.get('connection_status') === external_strophe_namespaceObject.Strophe.Status.ATTACHED;
      } else {
        // Not binding means that the session was resumed.
        return !this.do_bind;
      }
    }
  }, {
    key: "restoreWorkerSession",
    value: function restoreWorkerSession() {
      this.attach(this.onConnectStatusChanged);
      this.worker_attach_promise = getOpenPromise();
      return this.worker_attach_promise;
    }
  }], [{
    key: "generateResource",
    value: function generateResource() {
      return "/converse.js-".concat(Math.floor(Math.random() * 139749528).toString());
    }
  }]);
  return Connection;
}(external_strophe_namespaceObject.Strophe.Connection);

/**
 * The MockConnection class is used during testing, to mock an XMPP connection.
 * @class
 */
var MockConnection = /*#__PURE__*/function (_Connection) {
  connection_inherits(MockConnection, _Connection);
  var _super2 = connection_createSuper(MockConnection);
  function MockConnection(service, options) {
    var _this2;
    connection_classCallCheck(this, MockConnection);
    _this2 = _super2.call(this, service, options);
    _this2.sent_stanzas = [];
    _this2.IQ_stanzas = [];
    _this2.IQ_ids = [];
    _this2.features = external_strophe_namespaceObject.Strophe.xmlHtmlNode('<stream:features xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">' + '<ver xmlns="urn:xmpp:features:rosterver"/>' + '<csi xmlns="urn:xmpp:csi:0"/>' + '<this xmlns="http://jabber.org/protocol/caps" ver="UwBpfJpEt3IoLYfWma/o/p3FFRo=" hash="sha-1" node="http://prosody.im"/>' + '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">' + '<required/>' + '</bind>' + "<sm xmlns='urn:xmpp:sm:3'/>" + '<session xmlns="urn:ietf:params:xml:ns:xmpp-session">' + '<optional/>' + '</session>' + '</stream:features>').firstChild;
    _this2._proto._processRequest = function () {};
    _this2._proto._disconnect = function () {
      return _this2._onDisconnectTimeout();
    };
    _this2._proto._onDisconnectTimeout = function () {};
    _this2._proto._connect = function () {
      _this2.connected = true;
      _this2.mock = true;
      _this2.jid = 'romeo@montague.lit/orchard';
      _this2._changeConnectStatus(external_strophe_namespaceObject.Strophe.Status.BINDREQUIRED);
    };
    return _this2;
  }
  connection_createClass(MockConnection, [{
    key: "_processRequest",
    value: function _processRequest() {// eslint-disable-line class-methods-use-this
      // Don't attempt to send out stanzas
    }
  }, {
    key: "sendIQ",
    value: function sendIQ(iq, callback, errback) {
      var _iq$tree, _iq$tree2, _iq;
      iq = (_iq$tree = (_iq$tree2 = (_iq = iq).tree) === null || _iq$tree2 === void 0 ? void 0 : _iq$tree2.call(_iq)) !== null && _iq$tree !== void 0 ? _iq$tree : iq;
      this.IQ_stanzas.push(iq);
      var id = _get(connection_getPrototypeOf(MockConnection.prototype), "sendIQ", this).call(this, iq, callback, errback);
      this.IQ_ids.push(id);
      return id;
    }
  }, {
    key: "send",
    value: function send(stanza) {
      var _stanza$tree, _stanza$tree2, _stanza;
      stanza = (_stanza$tree = (_stanza$tree2 = (_stanza = stanza).tree) === null || _stanza$tree2 === void 0 ? void 0 : _stanza$tree2.call(_stanza)) !== null && _stanza$tree !== void 0 ? _stanza$tree : stanza;
      this.sent_stanzas.push(stanza);
      return _get(connection_getPrototypeOf(MockConnection.prototype), "send", this).call(this, stanza);
    }
  }, {
    key: "bind",
    value: function () {
      var _bind2 = connection_asyncToGenerator( /*#__PURE__*/connection_regeneratorRuntime().mark(function _callee9() {
        return connection_regeneratorRuntime().wrap(function _callee9$(_context9) {
          while (1) switch (_context9.prev = _context9.next) {
            case 0:
              _context9.next = 2;
              return shared_api.trigger('beforeResourceBinding', {
                'synchronous': true
              });
            case 2:
              this.authenticated = true;
              if (!shared_converse.no_connection_on_bind) {
                this._changeConnectStatus(external_strophe_namespaceObject.Strophe.Status.CONNECTED);
              }
            case 4:
            case "end":
              return _context9.stop();
          }
        }, _callee9, this);
      }));
      function bind() {
        return _bind2.apply(this, arguments);
      }
      return bind;
    }()
  }]);
  return MockConnection;
}(Connection);
;// CONCATENATED MODULE: ./src/headless/utils/init.js
function init_typeof(obj) {
  "@babel/helpers - typeof";

  return init_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;
  }, init_typeof(obj);
}
function init_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  init_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" == init_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 init_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 init_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        init_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        init_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}












function setUpXMLLogging() {
  var lmap = {};
  lmap[external_strophe_namespaceObject.Strophe.LogLevel.DEBUG] = 'debug';
  lmap[external_strophe_namespaceObject.Strophe.LogLevel.INFO] = 'info';
  lmap[external_strophe_namespaceObject.Strophe.LogLevel.WARN] = 'warn';
  lmap[external_strophe_namespaceObject.Strophe.LogLevel.ERROR] = 'error';
  lmap[external_strophe_namespaceObject.Strophe.LogLevel.FATAL] = 'fatal';
  external_strophe_namespaceObject.Strophe.log = function (level, msg) {
    return log.log(msg, lmap[level]);
  };
  external_strophe_namespaceObject.Strophe.error = function (msg) {
    return log.error(msg);
  };
  shared_converse.connection.xmlInput = function (body) {
    return log.debug(body.outerHTML, 'color: darkgoldenrod');
  };
  shared_converse.connection.xmlOutput = function (body) {
    return log.debug(body.outerHTML, 'color: darkcyan');
  };
}
function getConnectionServiceURL() {
  var api = shared_converse.api;
  if (('WebSocket' in window || 'MozWebSocket' in window) && api.settings.get("websocket_url")) {
    return api.settings.get('websocket_url');
  } else if (api.settings.get('bosh_service_url')) {
    return api.settings.get('bosh_service_url');
  }
  return '';
}
function initConnection() {
  var api = shared_converse.api;
  if (!api.settings.get('bosh_service_url')) {
    if (api.settings.get("authentication") === PREBIND) {
      throw new Error("authentication is set to 'prebind' but we don't have a BOSH connection");
    }
  }
  var XMPPConnection = shared_converse.isTestEnv() ? MockConnection : Connection;
  shared_converse.connection = new XMPPConnection(getConnectionServiceURL(), Object.assign(shared_converse.default_connection_options, api.settings.get("connection_options"), {
    'keepalive': api.settings.get("keepalive")
  }));
  setUpXMLLogging();
  /**
   * Triggered once the `Connection` constructor has been initialized, which
   * will be responsible for managing the connection to the XMPP server.
   *
   * @event _converse#connectionInitialized
   */
  api.trigger('connectionInitialized');
}
function initPlugins(_converse) {
  // If initialize gets called a second time (e.g. during tests), then we
  // need to re-apply all plugins (for a new converse instance), and we
  // therefore need to clear this array that prevents plugins from being
  // initialized twice.
  // If initialize is called for the first time, then this array is empty
  // in any case.
  _converse.pluggable.initialized_plugins = [];
  var whitelist = CORE_PLUGINS.concat(_converse.api.settings.get("whitelisted_plugins"));
  if (_converse.api.settings.get("singleton")) {
    ['converse-bookmarks', 'converse-controlbox', 'converse-headline', 'converse-register'].forEach(function (name) {
      return _converse.api.settings.get("blacklisted_plugins").push(name);
    });
  }
  _converse.pluggable.initializePlugins({
    _converse: _converse
  }, whitelist, _converse.api.settings.get("blacklisted_plugins"));

  /**
   * Triggered once all plugins have been initialized. This is a useful event if you want to
   * register event handlers but would like your own handlers to be overridable by
   * plugins. In that case, you need to first wait until all plugins have been
   * initialized, so that their overrides are active. One example where this is used
   * is in [converse-notifications.js](https://github.com/jcbrand/converse.js/blob/master/src/converse-notification.js)`.
   *
   * Also available as an [ES2015 Promise](http://es6-features.org/#PromiseUsage)
   * which can be listened to with `_converse.api.waitUntil`.
   *
   * @event _converse#pluginsInitialized
   * @memberOf _converse
   * @example _converse.api.listen.on('pluginsInitialized', () => { ... });
   */
  _converse.api.trigger('pluginsInitialized');
}
function initClientConfig(_x) {
  return _initClientConfig.apply(this, arguments);
}
function _initClientConfig() {
  _initClientConfig = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee2(_converse) {
    var id;
    return init_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          /* The client config refers to configuration of the client which is
           * independent of any particular user.
           * What this means is that config values need to persist across
           * user sessions.
           */
          id = 'converse.client-config';
          _converse.config = new Model({
            id: id,
            'trusted': true
          });
          _converse.config.browserStorage = createStore(id, "session");
          _context2.next = 5;
          return new Promise(function (r) {
            return _converse.config.fetch({
              'success': r,
              'error': r
            });
          });
        case 5:
          /**
           * Triggered once the XMPP-client configuration has been initialized.
           * The client configuration is independent of any particular and its values
           * persist across user sessions.
           *
           * @event _converse#clientConfigInitialized
           * @example
           * _converse.api.listen.on('clientConfigInitialized', () => { ... });
           */
          _converse.api.trigger('clientConfigInitialized');
        case 6:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _initClientConfig.apply(this, arguments);
}
function initSessionStorage(_x2) {
  return _initSessionStorage.apply(this, arguments);
}
function _initSessionStorage() {
  _initSessionStorage = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee3(_converse) {
    return init_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return storage.sessionStorageInitialized;
        case 2:
          _converse.storage = {
            'session': storage.localForage.createInstance({
              'name': _converse.isTestEnv() ? 'converse-test-session' : 'converse-session',
              'description': 'sessionStorage instance',
              'driver': ['sessionStorageWrapper']
            })
          };
        case 3:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _initSessionStorage.apply(this, arguments);
}
function initPersistentStorage(_converse, store_name) {
  if (_converse.api.settings.get('persistent_store') === 'sessionStorage') {
    return;
  } else if (_converse.api.settings.get("persistent_store") === 'BrowserExtLocal') {
    storage.localForage.defineDriver(local/* default */.Z).then(function () {
      return storage.localForage.setDriver('webExtensionLocalStorage');
    });
    _converse.storage['persistent'] = storage.localForage;
    return;
  } else if (_converse.api.settings.get("persistent_store") === 'BrowserExtSync') {
    storage.localForage.defineDriver(localforage_webextensionstorage_driver_sync/* default */.Z).then(function () {
      return storage.localForage.setDriver('webExtensionSyncStorage');
    });
    _converse.storage['persistent'] = storage.localForage;
    return;
  }
  var config = {
    'name': _converse.isTestEnv() ? 'converse-test-persistent' : 'converse-persistent',
    'storeName': store_name
  };
  if (_converse.api.settings.get("persistent_store") === 'localStorage') {
    config['description'] = 'localStorage instance';
    config['driver'] = [storage.localForage.LOCALSTORAGE];
  } else if (_converse.api.settings.get("persistent_store") === 'IndexedDB') {
    config['description'] = 'indexedDB instance';
    config['driver'] = [storage.localForage.INDEXEDDB];
  }
  _converse.storage['persistent'] = storage.localForage.createInstance(config);
}
function saveJIDtoSession(_converse, jid) {
  jid = _converse.session.get('jid') || jid;
  if (_converse.api.settings.get("authentication") !== ANONYMOUS && !external_strophe_namespaceObject.Strophe.getResourceFromJid(jid)) {
    jid = jid.toLowerCase() + Connection.generateResource();
  }
  _converse.jid = jid;
  _converse.bare_jid = external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid);
  _converse.resource = external_strophe_namespaceObject.Strophe.getResourceFromJid(jid);
  _converse.domain = external_strophe_namespaceObject.Strophe.getDomainFromJid(jid);
  _converse.session.save({
    'jid': jid,
    'bare_jid': _converse.bare_jid,
    'resource': _converse.resource,
    'domain': _converse.domain,
    // We use the `active` flag to determine whether we should use the values from sessionStorage.
    // When "cloning" a tab (e.g. via middle-click), the `active` flag will be set and we'll create
    // a new empty user session, otherwise it'll be false and we can re-use the user session.
    // When the tab is reloaded, the `active` flag is set to `false`.
    'active': true
  });
  // Set JID on the connection object so that when we call `connection.bind`
  // the new resource is found by Strophe.js and sent to the XMPP server.
  _converse.connection.jid = jid;
}

/**
 * Stores the passed in JID for the current user, potentially creating a
 * resource if the JID is bare.
 *
 * Given that we can only create an XMPP connection if we know the domain of
 * the server connect to and we only know this once we know the JID, we also
 * call {@link initConnection } (if necessary) to make sure that the
 * connection is set up.
 *
 * @emits _converse#setUserJID
 * @params { String } jid
 */
function setUserJID(_x3) {
  return _setUserJID.apply(this, arguments);
}
function _setUserJID() {
  _setUserJID = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee4(jid) {
    return init_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 2;
          return initSession(shared_converse, jid);
        case 2:
          /**
           * Triggered whenever the user's JID has been updated
           * @event _converse#setUserJID
           */
          shared_converse.api.trigger('setUserJID');
          return _context4.abrupt("return", jid);
        case 4:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _setUserJID.apply(this, arguments);
}
function initSession(_x4, _x5) {
  return _initSession.apply(this, arguments);
}
function _initSession() {
  _initSession = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee5(_converse, jid) {
    var _converse$session;
    var is_shared_session, bare_jid, id;
    return init_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          is_shared_session = _converse.api.settings.get('connection_options').worker;
          bare_jid = external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid).toLowerCase();
          id = "converse.session-".concat(bare_jid);
          if (!(((_converse$session = _converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.get('id')) !== id)) {
            _context5.next = 15;
            break;
          }
          initPersistentStorage(_converse, bare_jid);
          _converse.session = new Model({
            id: id
          });
          initStorage(_converse.session, id, is_shared_session ? "persistent" : "session");
          _context5.next = 9;
          return new Promise(function (r) {
            return _converse.session.fetch({
              'success': r,
              'error': r
            });
          });
        case 9:
          if (!is_shared_session && _converse.session.get('active')) {
            // If the `active` flag is set, it means this tab was cloned from
            // another (e.g. via middle-click), and its session data was copied over.
            _converse.session.clear();
            _converse.session.save({
              id: id
            });
          }
          saveJIDtoSession(_converse, jid);

          // Set `active` flag to false when the tab gets reloaded
          window.addEventListener(_converse.unloadevent, function () {
            var _converse$session2;
            return (_converse$session2 = _converse.session) === null || _converse$session2 === void 0 ? void 0 : _converse$session2.save('active', false);
          });

          /**
           * Triggered once the user's session has been initialized. The session is a
           * cache which stores information about the user's current session.
           * @event _converse#userSessionInitialized
           * @memberOf _converse
           */
          _converse.api.trigger('userSessionInitialized');
          _context5.next = 16;
          break;
        case 15:
          saveJIDtoSession(_converse, jid);
        case 16:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
  return _initSession.apply(this, arguments);
}
function registerGlobalEventHandlers(_converse) {
  document.addEventListener("visibilitychange", saveWindowState);
  saveWindowState({
    'type': document.hidden ? "blur" : "focus"
  }); // Set initial state
  /**
   * Called once Converse has registered its global event handlers
   * (for events such as window resize or unload).
   * Plugins can listen to this event as cue to register their own
   * global event handlers.
   * @event _converse#registeredGlobalEventHandlers
   * @example _converse.api.listen.on('registeredGlobalEventHandlers', () => { ... });
   */
  _converse.api.trigger('registeredGlobalEventHandlers');
}
function unregisterGlobalEventHandlers(_converse) {
  var api = _converse.api;
  document.removeEventListener("visibilitychange", saveWindowState);
  api.trigger('unregisteredGlobalEventHandlers');
}

// Make sure everything is reset in case this is a subsequent call to
// converse.initialize (happens during tests).
function cleanup(_x6) {
  return _cleanup.apply(this, arguments);
}
function _cleanup() {
  _cleanup = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee6(_converse) {
    var _converse$connection;
    var api;
    return init_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          api = _converse.api;
          _context6.next = 3;
          return api.trigger('cleanup', {
            'synchronous': true
          });
        case 3:
          _converse.router.history.stop();
          unregisterGlobalEventHandlers(_converse);
          (_converse$connection = _converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.reset();
          _converse.stopListening();
          _converse.off();
          if (_converse.promises['initialized'].isResolved) {
            api.promises.add('initialized');
          }
        case 9:
        case "end":
          return _context6.stop();
      }
    }, _callee6);
  }));
  return _cleanup.apply(this, arguments);
}
function fetchLoginCredentials() {
  var _this = this;
  var wait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  return new Promise(lodash_es_debounce( /*#__PURE__*/function () {
    var _ref = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee(resolve, reject) {
      var xhr;
      return init_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            xhr = new XMLHttpRequest();
            xhr.open('GET', shared_converse.api.settings.get("credentials_url"), true);
            xhr.setRequestHeader('Accept', 'application/json, text/javascript');
            xhr.onload = function () {
              if (xhr.status >= 200 && xhr.status < 400) {
                var data = JSON.parse(xhr.responseText);
                setUserJID(data.jid).then(function () {
                  resolve({
                    jid: data.jid,
                    password: data.password
                  });
                });
              } else {
                reject(new Error("".concat(xhr.status, ": ").concat(xhr.responseText)));
              }
            };
            xhr.onerror = reject;
            /**
             * *Hook* which allows modifying the server request
             * @event _converse#beforeFetchLoginCredentials
             */
            _context.next = 7;
            return shared_converse.api.hook('beforeFetchLoginCredentials', _this, xhr);
          case 7:
            xhr = _context.sent;
            xhr.send();
          case 9:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x7, _x8) {
      return _ref.apply(this, arguments);
    };
  }(), wait));
}
function getLoginCredentialsFromURL() {
  return _getLoginCredentialsFromURL.apply(this, arguments);
}
function _getLoginCredentialsFromURL() {
  _getLoginCredentialsFromURL = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee7() {
    var credentials, wait;
    return init_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) switch (_context7.prev = _context7.next) {
        case 0:
          wait = 0;
        case 1:
          if (credentials) {
            _context7.next = 15;
            break;
          }
          _context7.prev = 2;
          _context7.next = 5;
          return fetchLoginCredentials(wait);
        case 5:
          credentials = _context7.sent;
          _context7.next = 12;
          break;
        case 8:
          _context7.prev = 8;
          _context7.t0 = _context7["catch"](2);
          log.error('Could not fetch login credentials');
          log.error(_context7.t0);
        case 12:
          // If unsuccessful, we wait 2 seconds between subsequent attempts to
          // fetch the credentials.
          wait = 2000;
          _context7.next = 1;
          break;
        case 15:
          return _context7.abrupt("return", credentials);
        case 16:
        case "end":
          return _context7.stop();
      }
    }, _callee7, null, [[2, 8]]);
  }));
  return _getLoginCredentialsFromURL.apply(this, arguments);
}
function getLoginCredentialsFromBrowser() {
  return _getLoginCredentialsFromBrowser.apply(this, arguments);
}
function _getLoginCredentialsFromBrowser() {
  _getLoginCredentialsFromBrowser = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee8() {
    var jid, creds;
    return init_regeneratorRuntime().wrap(function _callee8$(_context8) {
      while (1) switch (_context8.prev = _context8.next) {
        case 0:
          jid = localStorage.getItem('conversejs-session-jid');
          if (jid) {
            _context8.next = 3;
            break;
          }
          return _context8.abrupt("return", null);
        case 3:
          _context8.prev = 3;
          _context8.next = 6;
          return navigator.credentials.get({
            password: true
          });
        case 6:
          creds = _context8.sent;
          if (!(creds && creds.type == 'password' && isValidJID(creds.id))) {
            _context8.next = 11;
            break;
          }
          _context8.next = 10;
          return setUserJID(creds.id);
        case 10:
          return _context8.abrupt("return", {
            'jid': creds.id,
            'password': creds.password
          });
        case 11:
          _context8.next = 17;
          break;
        case 13:
          _context8.prev = 13;
          _context8.t0 = _context8["catch"](3);
          log.error(_context8.t0);
          return _context8.abrupt("return", null);
        case 17:
        case "end":
          return _context8.stop();
      }
    }, _callee8, null, [[3, 13]]);
  }));
  return _getLoginCredentialsFromBrowser.apply(this, arguments);
}
function getLoginCredentialsFromSCRAMKeys() {
  return _getLoginCredentialsFromSCRAMKeys.apply(this, arguments);
}
function _getLoginCredentialsFromSCRAMKeys() {
  _getLoginCredentialsFromSCRAMKeys = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee9() {
    var jid, login_info, scram_keys;
    return init_regeneratorRuntime().wrap(function _callee9$(_context9) {
      while (1) switch (_context9.prev = _context9.next) {
        case 0:
          jid = localStorage.getItem('conversejs-session-jid');
          if (jid) {
            _context9.next = 3;
            break;
          }
          return _context9.abrupt("return", null);
        case 3:
          _context9.next = 5;
          return setUserJID(jid);
        case 5:
          _context9.next = 7;
          return savedLoginInfo(jid);
        case 7:
          login_info = _context9.sent;
          scram_keys = login_info.get('scram_keys');
          return _context9.abrupt("return", scram_keys ? {
            jid: jid,
            'password': scram_keys
          } : null);
        case 10:
        case "end":
          return _context9.stop();
      }
    }, _callee9);
  }));
  return _getLoginCredentialsFromSCRAMKeys.apply(this, arguments);
}
function attemptNonPreboundSession(_x9, _x10) {
  return _attemptNonPreboundSession.apply(this, arguments);
}

/**
 * Fetch the stored SCRAM keys for the given JID, if available.
 *
 * The user's plaintext password is not stored, nor any material from which
 * the user's plaintext password could be recovered.
 *
 * @param { String } jid - The XMPP address for which to fetch the SCRAM keys
 * @returns { Promise } A promise which resolves once we've fetched the previously
 *  used login keys.
 */
function _attemptNonPreboundSession() {
  _attemptNonPreboundSession = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee10(credentials, automatic) {
    var api, _credentials, _credentials2;
    return init_regeneratorRuntime().wrap(function _callee10$(_context10) {
      while (1) switch (_context10.prev = _context10.next) {
        case 0:
          api = shared_converse.api;
          if (!(api.settings.get("authentication") === LOGIN)) {
            _context10.next = 31;
            break;
          }
          if (!credentials) {
            _context10.next = 6;
            break;
          }
          return _context10.abrupt("return", connect(credentials));
        case 6:
          if (!api.settings.get("credentials_url")) {
            _context10.next = 14;
            break;
          }
          _context10.t0 = connect;
          _context10.next = 10;
          return getLoginCredentialsFromURL();
        case 10:
          _context10.t1 = _context10.sent;
          return _context10.abrupt("return", (0, _context10.t0)(_context10.t1));
        case 14:
          if (!(shared_converse.jid && (api.settings.get("password") || shared_converse.connection.pass))) {
            _context10.next = 16;
            break;
          }
          return _context10.abrupt("return", connect());
        case 16:
          if (!api.settings.get('reuse_scram_keys')) {
            _context10.next = 22;
            break;
          }
          _context10.next = 19;
          return getLoginCredentialsFromSCRAMKeys();
        case 19:
          _credentials = _context10.sent;
          if (!_credentials) {
            _context10.next = 22;
            break;
          }
          return _context10.abrupt("return", connect(_credentials));
        case 22:
          if (!(!shared_converse.isTestEnv() && 'credentials' in navigator)) {
            _context10.next = 28;
            break;
          }
          _context10.next = 25;
          return getLoginCredentialsFromBrowser();
        case 25:
          _credentials2 = _context10.sent;
          if (!_credentials2) {
            _context10.next = 28;
            break;
          }
          return _context10.abrupt("return", connect(_credentials2));
        case 28:
          if (!shared_converse.isTestEnv()) log.warn("attemptNonPreboundSession: Couldn't find credentials to log in with");
          _context10.next = 32;
          break;
        case 31:
          if ([ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication")) && (!automatic || api.settings.get("auto_login"))) {
            connect();
          }
        case 32:
        case "end":
          return _context10.stop();
      }
    }, _callee10);
  }));
  return _attemptNonPreboundSession.apply(this, arguments);
}
function savedLoginInfo(_x11) {
  return _savedLoginInfo.apply(this, arguments);
}

/**
 * @param { Object } [credentials]
 * @param { string } credentials.password
 * @param { Object } credentials.password
 * @param { string } credentials.password.ck
 * @returns { Promise<void> }
 */
function _savedLoginInfo() {
  _savedLoginInfo = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee11(jid) {
    var id, login_info;
    return init_regeneratorRuntime().wrap(function _callee11$(_context11) {
      while (1) switch (_context11.prev = _context11.next) {
        case 0:
          id = "converse.scram-keys-".concat(external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid));
          login_info = new Model({
            id: id
          });
          initStorage(login_info, id, 'persistent');
          _context11.next = 5;
          return new Promise(function (f) {
            return login_info.fetch({
              'success': f,
              'error': f
            });
          });
        case 5:
          return _context11.abrupt("return", login_info);
        case 6:
        case "end":
          return _context11.stop();
      }
    }, _callee11);
  }));
  return _savedLoginInfo.apply(this, arguments);
}
function connect(_x12) {
  return _connect.apply(this, arguments);
}
function _connect() {
  _connect = init_asyncToGenerator( /*#__PURE__*/init_regeneratorRuntime().mark(function _callee12(credentials) {
    var api, _credentials$password, _converse$connection2, password, callback, login_info;
    return init_regeneratorRuntime().wrap(function _callee12$(_context12) {
      while (1) switch (_context12.prev = _context12.next) {
        case 0:
          api = shared_converse.api;
          if (![ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication"))) {
            _context12.next = 8;
            break;
          }
          if (shared_converse.jid) {
            _context12.next = 4;
            break;
          }
          throw new Error("Config Error: when using anonymous login " + "you need to provide the server's domain via the 'jid' option. " + "Either when calling converse.initialize, or when calling " + "_converse.api.user.login.");
        case 4:
          if (!shared_converse.connection.reconnecting) {
            shared_converse.connection.reset();
          }
          shared_converse.connection.connect(shared_converse.jid.toLowerCase());
          _context12.next = 23;
          break;
        case 8:
          if (!(api.settings.get("authentication") === LOGIN)) {
            _context12.next = 23;
            break;
          }
          password = (_credentials$password = credentials === null || credentials === void 0 ? void 0 : credentials.password) !== null && _credentials$password !== void 0 ? _credentials$password : ((_converse$connection2 = shared_converse.connection) === null || _converse$connection2 === void 0 ? void 0 : _converse$connection2.pass) || api.settings.get("password");
          if (password) {
            _context12.next = 16;
            break;
          }
          if (!api.settings.get("auto_login")) {
            _context12.next = 13;
            break;
          }
          throw new Error("autoLogin: If you use auto_login and " + "authentication='login' then you also need to provide a password.");
        case 13:
          shared_converse.connection.setDisconnectionCause(external_strophe_namespaceObject.Strophe.Status.AUTHFAIL, undefined, true);
          api.connection.disconnect();
          return _context12.abrupt("return");
        case 16:
          if (!shared_converse.connection.reconnecting) {
            shared_converse.connection.reset();
            shared_converse.connection.service = getConnectionServiceURL();
          }
          if (!(shared_converse.config.get('trusted') && shared_converse.jid && api.settings.get("reuse_scram_keys") && !(password !== null && password !== void 0 && password.ck))) {
            _context12.next = 22;
            break;
          }
          _context12.next = 20;
          return savedLoginInfo(shared_converse.jid);
        case 20:
          login_info = _context12.sent;
          callback = function callback(status) {
            var scram_keys = shared_converse.connection.scram_keys;
            if (scram_keys) login_info.save({
              scram_keys: scram_keys
            });
            shared_converse.connection.onConnectStatusChanged(status);
          };
        case 22:
          shared_converse.connection.connect(shared_converse.jid, password, callback);
        case 23:
        case "end":
          return _context12.stop();
      }
    }, _callee12);
  }));
  return _connect.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/shared/api/user.js
function user_typeof(obj) {
  "@babel/helpers - typeof";

  return user_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;
  }, user_typeof(obj);
}
function user_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  user_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" == user_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 user_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 user_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        user_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        user_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
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) {
      user_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 user_defineProperty(obj, key, value) {
  key = user_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 user_toPropertyKey(arg) {
  var key = user_toPrimitive(arg, "string");
  return user_typeof(key) === "symbol" ? key : String(key);
}
function user_toPrimitive(input, hint) {
  if (user_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (user_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}







/* harmony default export */ const user = ({
  /**
   * This grouping collects API functions related to the current logged in user.
   *
   * @namespace _converse.api.user
   * @memberOf _converse.api
   */
  user: _objectSpread(_objectSpread({
    settings: user_settings_api
  }, presence), {}, {
    /**
     * @method _converse.api.user.jid
     * @returns {string} The current user's full JID (Jabber ID)
     * @example _converse.api.user.jid())
     */
    jid: function jid() {
      return shared_converse.connection.jid;
    },
    /**
     * Logs the user in.
     *
     * If called without any parameters, Converse will try
     * to log the user in by calling the `prebind_url` or `credentials_url` depending
     * on whether prebinding is used or not.
     *
     * @method _converse.api.user.login
     * @param { string } [jid]
     * @param { string } [password]
     * @param { boolean } [automatic=false] - An internally used flag that indicates whether
     *  this method was called automatically once the connection has been
     *  initialized. It's used together with the `auto_login` configuration flag
     *  to determine whether Converse should try to log the user in if it
     *  fails to restore a previous auth'd session.
     *  @returns  { Promise<void> }
     */
    login: function login(jid, password) {
      var _arguments = arguments;
      return user_asyncToGenerator( /*#__PURE__*/user_regeneratorRuntime().mark(function _callee() {
        var _converse$connection, _api$settings$get;
        var automatic, api, bosh_plugin, credentials;
        return user_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              automatic = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : false;
              api = shared_converse.api;
              jid = jid || api.settings.get('jid');
              if (!((_converse$connection = shared_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.jid) || jid && !core.isSameDomain(shared_converse.connection.jid, jid)) {
                initConnection();
              }
              _context.t0 = (_api$settings$get = api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.worker;
              if (!_context.t0) {
                _context.next = 9;
                break;
              }
              _context.next = 8;
              return shared_converse.connection.restoreWorkerSession();
            case 8:
              _context.t0 = _context.sent;
            case 9:
              if (!_context.t0) {
                _context.next = 11;
                break;
              }
              return _context.abrupt("return");
            case 11:
              if (!jid) {
                _context.next = 15;
                break;
              }
              _context.next = 14;
              return setUserJID(jid);
            case 14:
              jid = _context.sent;
            case 15:
              // See whether there is a BOSH session to re-attach to
              bosh_plugin = shared_converse.pluggable.plugins['converse-bosh'];
              if (!(bosh_plugin !== null && bosh_plugin !== void 0 && bosh_plugin.enabled())) {
                _context.next = 25;
                break;
              }
              _context.next = 19;
              return shared_converse.restoreBOSHSession();
            case 19:
              if (!_context.sent) {
                _context.next = 23;
                break;
              }
              return _context.abrupt("return");
            case 23:
              if (!(api.settings.get("authentication") === PREBIND && (!automatic || api.settings.get("auto_login")))) {
                _context.next = 25;
                break;
              }
              return _context.abrupt("return", shared_converse.startNewPreboundBOSHSession());
            case 25:
              password = password || api.settings.get("password");
              credentials = jid && password ? {
                jid: jid,
                password: password
              } : null;
              attemptNonPreboundSession(credentials, automatic);
            case 28:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * Logs the user out of the current XMPP session.
     * @method _converse.api.user.logout
     * @example _converse.api.user.logout();
     */
    logout: function logout() {
      return user_asyncToGenerator( /*#__PURE__*/user_regeneratorRuntime().mark(function _callee2() {
        var api, promise, complete;
        return user_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              api = shared_converse.api;
              /**
               * Triggered before the user is logged out
               * @event _converse#beforeLogout
               */
              _context2.next = 3;
              return api.trigger('beforeLogout', {
                'synchronous': true
              });
            case 3:
              promise = getOpenPromise();
              complete = function complete() {
                // Recreate all the promises
                Object.keys(shared_converse.promises).forEach(replacePromise);
                delete shared_converse.jid;

                // Remove the session JID, otherwise the user would just be logged
                // in again upon reload. See #2759
                localStorage.removeItem('conversejs-session-jid');

                /**
                 * Triggered once the user has logged out.
                 * @event _converse#logout
                 */
                api.trigger('logout');
                promise.resolve();
              };
              shared_converse.connection.setDisconnectionCause(LOGOUT, undefined, true);
              if (shared_converse.connection !== undefined) {
                api.listen.once('disconnected', function () {
                  return complete();
                });
                shared_converse.connection.disconnect();
              } else {
                complete();
              }
              return _context2.abrupt("return", promise);
            case 8:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    }
  })
});
;// CONCATENATED MODULE: ./src/headless/shared/api/index.js
function shared_api_typeof(obj) {
  "@babel/helpers - typeof";

  return shared_api_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;
  }, shared_api_typeof(obj);
}
function api_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 api_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? api_ownKeys(Object(source), !0).forEach(function (key) {
      api_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : api_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function api_defineProperty(obj, key, value) {
  key = api_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 api_toPropertyKey(arg) {
  var key = api_toPrimitive(arg, "string");
  return shared_api_typeof(key) === "symbol" ? key : String(key);
}
function api_toPrimitive(input, hint) {
  if (shared_api_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (shared_api_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}








/**
 * ### The private API
 *
 * The private API methods are only accessible via the closured {@link _converse}
 * object, which is only available to plugins.
 *
 * These methods are kept private (i.e. not global) because they may return
 * sensitive data which should be kept off-limits to other 3rd-party scripts
 * that might be running in the page.
 *
 * @namespace _converse.api
 * @memberOf _converse
 */
var api_api = shared_converse.api = api_objectSpread(api_objectSpread(api_objectSpread(api_objectSpread({
  connection: api,
  settings: settings_api
}, send), user), events), promise);
/* harmony default export */ const shared_api = (api_api);
// EXTERNAL MODULE: ./node_modules/dayjs/dayjs.min.js
var dayjs_min = __webpack_require__(4735);
var dayjs_min_default = /*#__PURE__*/__webpack_require__.n(dayjs_min);
;// CONCATENATED MODULE: ./src/headless/shared/connection/feedback.js



/* harmony default export */ const feedback = (Model.extend({
  defaults: {
    'connection_status': external_strophe_namespaceObject.Strophe.Status.DISCONNECTED,
    'message': ''
  },
  initialize: function initialize() {
    var api = shared_converse.api;
    this.on('change', function () {
      return api.trigger('connfeedback', shared_converse.connfeedback);
    });
  }
}));
;// CONCATENATED MODULE: external "urijs"
const external_urijs_namespaceObject = urijs;
var external_urijs_default = /*#__PURE__*/__webpack_require__.n(external_urijs_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayAggregator.js
/**
 * A specialized version of `baseAggregator` for arrays.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform keys.
 * @param {Object} accumulator The initial aggregated object.
 * @returns {Function} Returns `accumulator`.
 */
function arrayAggregator(array, setter, iteratee, accumulator) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    var value = array[index];
    setter(accumulator, value, iteratee(value), array);
  }
  return accumulator;
}
/* harmony default export */ const _arrayAggregator = (arrayAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAggregator.js


/**
 * Aggregates elements of `collection` on `accumulator` with keys transformed
 * by `iteratee` and values set by `setter`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform keys.
 * @param {Object} accumulator The initial aggregated object.
 * @returns {Function} Returns `accumulator`.
 */
function baseAggregator(collection, setter, iteratee, accumulator) {
  _baseEach(collection, function (value, key, collection) {
    setter(accumulator, value, iteratee(value), collection);
  });
  return accumulator;
}
/* harmony default export */ const _baseAggregator = (baseAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createAggregator.js





/**
 * Creates a function like `_.groupBy`.
 *
 * @private
 * @param {Function} setter The function to set accumulator values.
 * @param {Function} [initializer] The accumulator object initializer.
 * @returns {Function} Returns the new aggregator function.
 */
function createAggregator(setter, initializer) {
  return function (collection, iteratee) {
    var func = lodash_es_isArray(collection) ? _arrayAggregator : _baseAggregator,
      accumulator = initializer ? initializer() : {};
    return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
  };
}
/* harmony default export */ const _createAggregator = (createAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/countBy.js



/** Used for built-in method references. */
var countBy_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var countBy_hasOwnProperty = countBy_objectProto.hasOwnProperty;

/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The corresponding value of
 * each key is the number of times the key was returned by `iteratee`. The
 * iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.countBy([6.1, 4.2, 6.3], Math.floor);
 * // => { '4': 1, '6': 2 }
 *
 * // The `_.property` iteratee shorthand.
 * _.countBy(['one', 'two', 'three'], 'length');
 * // => { '3': 2, '5': 1 }
 */
var countBy = _createAggregator(function (result, value, key) {
  if (countBy_hasOwnProperty.call(result, key)) {
    ++result[key];
  } else {
    _baseAssignValue(result, key, 1);
  }
});
/* harmony default export */ const lodash_es_countBy = (countBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFindIndex.js
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
    index = fromIndex + (fromRight ? 1 : -1);
  while (fromRight ? index-- : ++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}
/* harmony default export */ const _baseFindIndex = (baseFindIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNaN.js
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}
/* harmony default export */ const _baseIsNaN = (baseIsNaN);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_strictIndexOf.js
/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
    length = array.length;
  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}
/* harmony default export */ const _strictIndexOf = (strictIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIndexOf.js




/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
}
/* harmony default export */ const _baseIndexOf = (baseIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludes.js


/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && _baseIndexOf(array, value, 0) > -1;
}
/* harmony default export */ const _arrayIncludes = (arrayIncludes);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludesWith.js
/**
 * This function is like `arrayIncludes` except that it accepts a comparator.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @param {Function} comparator The comparator invoked per element.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludesWith(array, value, comparator) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}
/* harmony default export */ const _arrayIncludesWith = (arrayIncludesWith);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDifference.js







/** Used as the size to enable large array optimizations. */
var _baseDifference_LARGE_ARRAY_SIZE = 200;

/**
 * The base implementation of methods like `_.difference` without support
 * for excluding multiple arrays or iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Array} values The values to exclude.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new array of filtered values.
 */
function baseDifference(array, values, iteratee, comparator) {
  var index = -1,
    includes = _arrayIncludes,
    isCommon = true,
    length = array.length,
    result = [],
    valuesLength = values.length;
  if (!length) {
    return result;
  }
  if (iteratee) {
    values = _arrayMap(values, _baseUnary(iteratee));
  }
  if (comparator) {
    includes = _arrayIncludesWith;
    isCommon = false;
  } else if (values.length >= _baseDifference_LARGE_ARRAY_SIZE) {
    includes = _cacheHas;
    isCommon = false;
    values = new _SetCache(values);
  }
  outer: while (++index < length) {
    var value = array[index],
      computed = iteratee == null ? value : iteratee(value);
    value = comparator || value !== 0 ? value : 0;
    if (isCommon && computed === computed) {
      var valuesIndex = valuesLength;
      while (valuesIndex--) {
        if (values[valuesIndex] === computed) {
          continue outer;
        }
      }
      result.push(value);
    } else if (!includes(values, computed, comparator)) {
      result.push(value);
    }
  }
  return result;
}
/* harmony default export */ const _baseDifference = (baseDifference);
;// CONCATENATED MODULE: ./node_modules/lodash-es/difference.js





/**
 * Creates an array of `array` values not included in the other given arrays
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons. The order and references of result values are
 * determined by the first array.
 *
 * **Note:** Unlike `_.pullAll`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {...Array} [values] The values to exclude.
 * @returns {Array} Returns the new array of filtered values.
 * @see _.without, _.xor
 * @example
 *
 * _.difference([2, 1], [2, 3]);
 * // => [1]
 */
var difference = _baseRest(function (array, values) {
  return lodash_es_isArrayLikeObject(array) ? _baseDifference(array, _baseFlatten(values, 1, lodash_es_isArrayLikeObject, true)) : [];
});
/* harmony default export */ const lodash_es_difference = (difference);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEvery.js
/**
 * A specialized version of `_.every` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`.
 */
function arrayEvery(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (!predicate(array[index], index, array)) {
      return false;
    }
  }
  return true;
}
/* harmony default export */ const _arrayEvery = (arrayEvery);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEvery.js


/**
 * The base implementation of `_.every` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`
 */
function baseEvery(collection, predicate) {
  var result = true;
  _baseEach(collection, function (value, index, collection) {
    result = !!predicate(value, index, collection);
    return result;
  });
  return result;
}
/* harmony default export */ const _baseEvery = (baseEvery);
;// CONCATENATED MODULE: ./node_modules/lodash-es/every.js






/**
 * Checks if `predicate` returns truthy for **all** elements of `collection`.
 * Iteration is stopped once `predicate` returns falsey. The predicate is
 * invoked with three arguments: (value, index|key, collection).
 *
 * **Note:** This method returns `true` for
 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
 * elements of empty collections.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`.
 * @example
 *
 * _.every([true, 1, null, 'yes'], Boolean);
 * // => false
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': false },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.every(users, { 'user': 'barney', 'active': false });
 * // => false
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.every(users, ['active', false]);
 * // => true
 *
 * // The `_.property` iteratee shorthand.
 * _.every(users, 'active');
 * // => false
 */
function every(collection, predicate, guard) {
  var func = lodash_es_isArray(collection) ? _arrayEvery : _baseEvery;
  if (guard && _isIterateeCall(collection, predicate, guard)) {
    predicate = undefined;
  }
  return func(collection, _baseIteratee(predicate, 3));
}
/* harmony default export */ const lodash_es_every = (every);
;// CONCATENATED MODULE: ./node_modules/lodash-es/findIndex.js




/* Built-in method references for those with the same name as other `lodash` methods. */
var findIndex_nativeMax = Math.max;

/**
 * This method is like `_.find` except that it returns the index of the first
 * element `predicate` returns truthy for instead of the element itself.
 *
 * @static
 * @memberOf _
 * @since 1.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': false },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': true }
 * ];
 *
 * _.findIndex(users, function(o) { return o.user == 'barney'; });
 * // => 0
 *
 * // The `_.matches` iteratee shorthand.
 * _.findIndex(users, { 'user': 'fred', 'active': false });
 * // => 1
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.findIndex(users, ['active', false]);
 * // => 0
 *
 * // The `_.property` iteratee shorthand.
 * _.findIndex(users, 'active');
 * // => 2
 */
function findIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);
  if (index < 0) {
    index = findIndex_nativeMax(length + index, 0);
  }
  return _baseFindIndex(array, _baseIteratee(predicate, 3), index);
}
/* harmony default export */ const lodash_es_findIndex = (findIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/findLastIndex.js




/* Built-in method references for those with the same name as other `lodash` methods. */
var findLastIndex_nativeMax = Math.max,
  findLastIndex_nativeMin = Math.min;

/**
 * This method is like `_.findIndex` except that it iterates over elements
 * of `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @since 2.0.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': true },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': false }
 * ];
 *
 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
 * // => 2
 *
 * // The `_.matches` iteratee shorthand.
 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
 * // => 0
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.findLastIndex(users, ['active', false]);
 * // => 2
 *
 * // The `_.property` iteratee shorthand.
 * _.findLastIndex(users, 'active');
 * // => 0
 */
function findLastIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = length - 1;
  if (fromIndex !== undefined) {
    index = lodash_es_toInteger(fromIndex);
    index = fromIndex < 0 ? findLastIndex_nativeMax(length + index, 0) : findLastIndex_nativeMin(index, length - 1);
  }
  return _baseFindIndex(array, _baseIteratee(predicate, 3), index, true);
}
/* harmony default export */ const lodash_es_findLastIndex = (findLastIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/groupBy.js



/** Used for built-in method references. */
var groupBy_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var groupBy_hasOwnProperty = groupBy_objectProto.hasOwnProperty;

/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The order of grouped values
 * is determined by the order they occur in `collection`. The corresponding
 * value of each key is an array of elements responsible for generating the
 * key. The iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
 * // => { '4': [4.2], '6': [6.1, 6.3] }
 *
 * // The `_.property` iteratee shorthand.
 * _.groupBy(['one', 'two', 'three'], 'length');
 * // => { '3': ['one', 'two'], '5': ['three'] }
 */
var groupBy = _createAggregator(function (result, value, key) {
  if (groupBy_hasOwnProperty.call(result, key)) {
    result[key].push(value);
  } else {
    _baseAssignValue(result, key, [value]);
  }
});
/* harmony default export */ const lodash_es_groupBy = (groupBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/indexOf.js



/* Built-in method references for those with the same name as other `lodash` methods. */
var indexOf_nativeMax = Math.max;

/**
 * Gets the index at which the first occurrence of `value` is found in `array`
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons. If `fromIndex` is negative, it's used as the
 * offset from the end of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 * @example
 *
 * _.indexOf([1, 2, 1, 2], 2);
 * // => 1
 *
 * // Search from the `fromIndex`.
 * _.indexOf([1, 2, 1, 2], 2, 2);
 * // => 3
 */
function indexOf(array, value, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);
  if (index < 0) {
    index = indexOf_nativeMax(length + index, 0);
  }
  return _baseIndexOf(array, value, index);
}
/* harmony default export */ const lodash_es_indexOf = (indexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keyBy.js



/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The corresponding value of
 * each key is the last element responsible for generating the key. The
 * iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * var array = [
 *   { 'dir': 'left', 'code': 97 },
 *   { 'dir': 'right', 'code': 100 }
 * ];
 *
 * _.keyBy(array, function(o) {
 *   return String.fromCharCode(o.code);
 * });
 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
 *
 * _.keyBy(array, 'dir');
 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
 */
var keyBy = _createAggregator(function (result, value, key) {
  _baseAssignValue(result, key, value);
});
/* harmony default export */ const lodash_es_keyBy = (keyBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_strictLastIndexOf.js
/**
 * A specialized version of `_.lastIndexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictLastIndexOf(array, value, fromIndex) {
  var index = fromIndex + 1;
  while (index--) {
    if (array[index] === value) {
      return index;
    }
  }
  return index;
}
/* harmony default export */ const _strictLastIndexOf = (strictLastIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/lastIndexOf.js





/* Built-in method references for those with the same name as other `lodash` methods. */
var lastIndexOf_nativeMax = Math.max,
  lastIndexOf_nativeMin = Math.min;

/**
 * This method is like `_.indexOf` except that it iterates over elements of
 * `array` from right to left.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 * @example
 *
 * _.lastIndexOf([1, 2, 1, 2], 2);
 * // => 3
 *
 * // Search from the `fromIndex`.
 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
 * // => 1
 */
function lastIndexOf(array, value, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = length;
  if (fromIndex !== undefined) {
    index = lodash_es_toInteger(fromIndex);
    index = index < 0 ? lastIndexOf_nativeMax(length + index, 0) : lastIndexOf_nativeMin(index, length - 1);
  }
  return value === value ? _strictLastIndexOf(array, value, index) : _baseFindIndex(array, _baseIsNaN, index, true);
}
/* harmony default export */ const lodash_es_lastIndexOf = (lastIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMap.js



/**
 * The base implementation of `_.map` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function baseMap(collection, iteratee) {
  var index = -1,
    result = lodash_es_isArrayLike(collection) ? Array(collection.length) : [];
  _baseEach(collection, function (value, key, collection) {
    result[++index] = iteratee(value, key, collection);
  });
  return result;
}
/* harmony default export */ const _baseMap = (baseMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSortBy.js
/**
 * The base implementation of `_.sortBy` which uses `comparer` to define the
 * sort order of `array` and replaces criteria objects with their corresponding
 * values.
 *
 * @private
 * @param {Array} array The array to sort.
 * @param {Function} comparer The function to define sort order.
 * @returns {Array} Returns `array`.
 */
function baseSortBy(array, comparer) {
  var length = array.length;
  array.sort(comparer);
  while (length--) {
    array[length] = array[length].value;
  }
  return array;
}
/* harmony default export */ const _baseSortBy = (baseSortBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_compareAscending.js


/**
 * Compares values to sort them in ascending order.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {number} Returns the sort order indicator for `value`.
 */
function compareAscending(value, other) {
  if (value !== other) {
    var valIsDefined = value !== undefined,
      valIsNull = value === null,
      valIsReflexive = value === value,
      valIsSymbol = lodash_es_isSymbol(value);
    var othIsDefined = other !== undefined,
      othIsNull = other === null,
      othIsReflexive = other === other,
      othIsSymbol = lodash_es_isSymbol(other);
    if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
      return 1;
    }
    if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}
/* harmony default export */ const _compareAscending = (compareAscending);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_compareMultiple.js


/**
 * Used by `_.orderBy` to compare multiple properties of a value to another
 * and stable sort them.
 *
 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
 * specify an order of "desc" for descending or "asc" for ascending sort order
 * of corresponding values.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {boolean[]|string[]} orders The order to sort by for each property.
 * @returns {number} Returns the sort order indicator for `object`.
 */
function compareMultiple(object, other, orders) {
  var index = -1,
    objCriteria = object.criteria,
    othCriteria = other.criteria,
    length = objCriteria.length,
    ordersLength = orders.length;
  while (++index < length) {
    var result = _compareAscending(objCriteria[index], othCriteria[index]);
    if (result) {
      if (index >= ordersLength) {
        return result;
      }
      var order = orders[index];
      return result * (order == 'desc' ? -1 : 1);
    }
  }
  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to provide the same value for
  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  // for more details.
  //
  // This also ensures a stable sort in V8 and other engines.
  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  return object.index - other.index;
}
/* harmony default export */ const _compareMultiple = (compareMultiple);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseOrderBy.js










/**
 * The base implementation of `_.orderBy` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
 * @param {string[]} orders The sort orders of `iteratees`.
 * @returns {Array} Returns the new sorted array.
 */
function baseOrderBy(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = _arrayMap(iteratees, function (iteratee) {
      if (lodash_es_isArray(iteratee)) {
        return function (value) {
          return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        };
      }
      return iteratee;
    });
  } else {
    iteratees = [lodash_es_identity];
  }
  var index = -1;
  iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee));
  var result = _baseMap(collection, function (value, key, collection) {
    var criteria = _arrayMap(iteratees, function (iteratee) {
      return iteratee(value);
    });
    return {
      'criteria': criteria,
      'index': ++index,
      'value': value
    };
  });
  return _baseSortBy(result, function (object, other) {
    return _compareMultiple(object, other, orders);
  });
}
/* harmony default export */ const _baseOrderBy = (baseOrderBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/sortBy.js





/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection thru each iteratee. This method
 * performs a stable sort, that is, it preserves the original sort order of
 * equal elements. The iteratees are invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {...(Function|Function[])} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 36 },
 *   { 'user': 'fred',   'age': 30 },
 *   { 'user': 'barney', 'age': 34 }
 * ];
 *
 * _.sortBy(users, [function(o) { return o.user; }]);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
 *
 * _.sortBy(users, ['user', 'age']);
 * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
 */
var sortBy = _baseRest(function (collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []);
});
/* harmony default export */ const lodash_es_sortBy = (sortBy);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/collection.js
function collection_typeof(obj) {
  "@babel/helpers - typeof";

  return collection_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;
  }, collection_typeof(obj);
}
function collection_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  collection_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" == collection_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 collection_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 collection_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        collection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        collection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.

// Collection
// ----------

// If models tend to represent a single row of data, a Collection is
// more analogous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.




















var _slice = Array.prototype.slice;

// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = function Collection(models, options) {
  options || (options = {});
  this.preinitialize.apply(this, arguments);
  if (options.model) this.model = options.model;
  if (options.comparator !== undefined) this.comparator = options.comparator;
  this._reset();
  this.initialize.apply(this, arguments);
  if (models) this.reset(models, lodash_es_assignIn({
    silent: true
  }, options));
};
Collection.extend = inherits;

// Default options for `Collection#set`.
var setOptions = {
  add: true,
  remove: true,
  merge: true
};
var addOptions = {
  add: true,
  remove: false
};

// Splices `insert` into `array` at index `at`.
var collection_splice = function splice(array, insert, at) {
  at = Math.min(Math.max(at, 0), array.length);
  var tail = Array(array.length - at);
  var length = insert.length;
  var i;
  for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
  for (i = 0; i < length; i++) array[i + at] = insert[i];
  for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
};

// Define the Collection's inheritable methods.
Object.assign(Collection.prototype, Events, {
  // The default model for a collection is just a **Backbone.Model**.
  // This should be overridden in most cases.
  model: Model,
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Collection.
  preinitialize: function preinitialize() {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function initialize() {},
  // The JSON representation of a Collection is an array of the
  // models' attributes.
  toJSON: function toJSON(options) {
    return this.map(function (model) {
      return model.toJSON(options);
    });
  },
  // Proxy `Backbone.sync` by default.
  sync: function sync(method, model, options) {
    return getSyncMethod(this)(method, model, options);
  },
  // Add a model, or list of models to the set. `models` may be Backbone
  // Models or raw JavaScript objects to be converted to Models, or any
  // combination of the two.
  add: function add(models, options) {
    return this.set(models, lodash_es_assignIn({
      merge: false
    }, options, addOptions));
  },
  // Remove a model, or a list of models from the set.
  remove: function remove(models, options) {
    options = lodash_es_assignIn({}, options);
    var singular = !Array.isArray(models);
    models = singular ? [models] : models.slice();
    var removed = this._removeModels(models, options);
    if (!options.silent && removed.length) {
      options.changes = {
        added: [],
        merged: [],
        removed: removed
      };
      this.trigger('update', this, options);
    }
    return singular ? removed[0] : removed;
  },
  // Update a collection by `set`-ing a new list of models, adding new ones,
  // removing models that are no longer present, and merging models that
  // already exist in the collection, as necessary. Similar to **Model#set**,
  // the core operation for updating the data contained by the collection.
  set: function set(models, options) {
    if (models == null) return;
    options = lodash_es_assignIn({}, setOptions, options);
    if (options.parse && !this._isModel(models)) {
      models = this.parse(models, options) || [];
    }
    var singular = !Array.isArray(models);
    models = singular ? [models] : models.slice();
    var at = options.at;
    if (at != null) at = +at;
    if (at > this.length) at = this.length;
    if (at < 0) at += this.length + 1;
    var set = [];
    var toAdd = [];
    var toMerge = [];
    var toRemove = [];
    var modelMap = {};
    var add = options.add;
    var merge = options.merge;
    var remove = options.remove;
    var sort = false;
    var sortable = this.comparator && at == null && options.sort !== false;
    var sortAttr = lodash_es_isString(this.comparator) ? this.comparator : null;

    // Turn bare objects into model references, and prevent invalid models
    // from being added.
    var model, i;
    for (i = 0; i < models.length; i++) {
      model = models[i];

      // If a duplicate is found, prevent it from being added and
      // optionally merge it into the existing model.
      var existing = this.get(model);
      if (existing) {
        if (merge && model !== existing) {
          var attrs = this._isModel(model) ? model.attributes : model;
          if (options.parse) attrs = existing.parse(attrs, options);
          existing.set(attrs, options);
          toMerge.push(existing);
          if (sortable && !sort) sort = existing.hasChanged(sortAttr);
        }
        if (!modelMap[existing.cid]) {
          modelMap[existing.cid] = true;
          set.push(existing);
        }
        models[i] = existing;

        // If this is a new, valid model, push it to the `toAdd` list.
      } else if (add) {
        model = models[i] = this._prepareModel(model, options);
        if (model) {
          toAdd.push(model);
          this._addReference(model, options);
          modelMap[model.cid] = true;
          set.push(model);
        }
      }
    }

    // Remove stale models.
    if (remove) {
      for (i = 0; i < this.length; i++) {
        model = this.models[i];
        if (!modelMap[model.cid]) toRemove.push(model);
      }
      if (toRemove.length) this._removeModels(toRemove, options);
    }

    // See if sorting is needed, update `length` and splice in new models.
    var orderChanged = false;
    var replace = !sortable && add && remove;
    if (set.length && replace) {
      orderChanged = this.length !== set.length || lodash_es_some(this.models, function (m, index) {
        return m !== set[index];
      });
      this.models.length = 0;
      collection_splice(this.models, set, 0);
      this.length = this.models.length;
    } else if (toAdd.length) {
      if (sortable) sort = true;
      collection_splice(this.models, toAdd, at == null ? this.length : at);
      this.length = this.models.length;
    }

    // Silently sort the collection if appropriate.
    if (sort) this.sort({
      silent: true
    });

    // Unless silenced, it's time to fire all appropriate add/sort/update events.
    if (!options.silent) {
      for (i = 0; i < toAdd.length; i++) {
        if (at != null) options.index = at + i;
        model = toAdd[i];
        model.trigger('add', model, this, options);
      }
      if (sort || orderChanged) this.trigger('sort', this, options);
      if (toAdd.length || toRemove.length || toMerge.length) {
        options.changes = {
          added: toAdd,
          removed: toRemove,
          merged: toMerge
        };
        this.trigger('update', this, options);
      }
    }

    // Return the added (or merged) model (or models).
    return singular ? models[0] : models;
  },
  clearStore: function () {
    var _clearStore = collection_asyncToGenerator( /*#__PURE__*/collection_regeneratorRuntime().mark(function _callee() {
      var options,
        filter,
        _args = arguments;
      return collection_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            options = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            filter = _args.length > 1 && _args[1] !== undefined ? _args[1] : function (o) {
              return o;
            };
            _context.next = 4;
            return Promise.all(this.models.filter(filter).map(function (m) {
              return new Promise(function (resolve) {
                m.destroy(Object.assign(options, {
                  'success': resolve,
                  'error': function error(m, e) {
                    console.error(e);
                    resolve();
                  }
                }));
              });
            }));
          case 4:
            _context.next = 6;
            return this.browserStorage.clear();
          case 6:
            this.reset();
          case 7:
          case "end":
            return _context.stop();
        }
      }, _callee, this);
    }));
    function clearStore() {
      return _clearStore.apply(this, arguments);
    }
    return clearStore;
  }(),
  // When you have more items than you want to add or remove individually,
  // you can reset the entire set with a new list of models, without firing
  // any granular `add` or `remove` events. Fires `reset` when finished.
  // Useful for bulk operations and optimizations.
  reset: function reset(models, options) {
    options = options ? lodash_es_clone(options) : {};
    for (var i = 0; i < this.models.length; i++) {
      this._removeReference(this.models[i], options);
    }
    options.previousModels = this.models;
    this._reset();
    models = this.add(models, lodash_es_assignIn({
      silent: true
    }, options));
    if (!options.silent) this.trigger('reset', this, options);
    return models;
  },
  // Add a model to the end of the collection.
  push: function push(model, options) {
    return this.add(model, lodash_es_assignIn({
      at: this.length
    }, options));
  },
  // Remove a model from the end of the collection.
  pop: function pop(options) {
    var model = this.at(this.length - 1);
    return this.remove(model, options);
  },
  // Add a model to the beginning of the collection.
  unshift: function unshift(model, options) {
    return this.add(model, lodash_es_assignIn({
      at: 0
    }, options));
  },
  // Remove a model from the beginning of the collection.
  shift: function shift(options) {
    var model = this.at(0);
    return this.remove(model, options);
  },
  // Slice out a sub-array of models from the collection.
  slice: function slice() {
    return _slice.apply(this.models, arguments);
  },
  filter: function filter(callback, thisArg) {
    return this.models.filter(lodash_es_isFunction(callback) ? callback : function (m) {
      return m.matches(callback);
    }, thisArg);
  },
  every: function every(pred) {
    return lodash_es_every(this.models.map(function (m) {
      return m.attributes;
    }), pred);
  },
  difference: function difference(values) {
    return lodash_es_difference(this.models, values);
  },
  max: function max() {
    return Math.max.apply(Math, this.models);
  },
  min: function min() {
    return Math.min.apply(Math, this.models);
  },
  drop: function drop() {
    var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
    return this.models.slice(n);
  },
  some: function some(pred) {
    return lodash_es_some(this.models.map(function (m) {
      return m.attributes;
    }), pred);
  },
  sortBy: function sortBy(iteratee) {
    return lodash_es_sortBy(this.models, lodash_es_isFunction(iteratee) ? iteratee : function (m) {
      return lodash_es_isString(iteratee) ? m.get(iteratee) : m.matches(iteratee);
    });
  },
  isEmpty: function isEmpty() {
    return lodash_es_isEmpty(this.models);
  },
  keyBy: function keyBy(iteratee) {
    return lodash_es_keyBy(this.models, iteratee);
  },
  each: function each(callback, thisArg) {
    return this.forEach(callback, thisArg);
  },
  forEach: function forEach(callback, thisArg) {
    return this.models.forEach(callback, thisArg);
  },
  includes: function includes(item) {
    return this.models.includes(item);
  },
  size: function size() {
    return this.models.length;
  },
  countBy: function countBy(f) {
    return lodash_es_countBy(this.models, lodash_es_isFunction(f) ? f : function (m) {
      return lodash_es_isString(f) ? m.get(f) : m.matches(f);
    });
  },
  groupBy: function groupBy(pred) {
    return lodash_es_groupBy(this.models, lodash_es_isFunction(pred) ? pred : function (m) {
      return lodash_es_isString(pred) ? m.get(pred) : m.matches(pred);
    });
  },
  indexOf: function indexOf(fromIndex) {
    return lodash_es_indexOf(this.models, fromIndex);
  },
  findLastIndex: function findLastIndex(pred, fromIndex) {
    return lodash_es_findLastIndex(this.models, lodash_es_isFunction(pred) ? pred : function (m) {
      return lodash_es_isString(pred) ? m.get(pred) : m.matches(pred);
    }, fromIndex);
  },
  lastIndexOf: function lastIndexOf(fromIndex) {
    return lodash_es_lastIndexOf(this.models, fromIndex);
  },
  findIndex: function findIndex(pred) {
    return lodash_es_findIndex(this.models, lodash_es_isFunction(pred) ? pred : function (m) {
      return lodash_es_isString(pred) ? m.get(pred) : m.matches(pred);
    });
  },
  last: function last() {
    var length = this.models == null ? 0 : this.models.length;
    return length ? this.models[length - 1] : undefined;
  },
  head: function head() {
    return this.models[0];
  },
  first: function first() {
    return this.head();
  },
  map: function map(cb, thisArg) {
    return this.models.map(lodash_es_isFunction(cb) ? cb : function (m) {
      return lodash_es_isString(cb) ? m.get(cb) : m.matches(cb);
    }, thisArg);
  },
  reduce: function reduce(callback, initialValue) {
    return this.models.reduce(callback, initialValue || this.models[0]);
  },
  reduceRight: function reduceRight(callback, initialValue) {
    return this.models.reduceRight(callback, initialValue || this.models[0]);
  },
  toArray: function toArray() {
    return Array.from(this.models);
  },
  // Get a model from the set by id, cid, model object with id or cid
  // properties, or an attributes object that is transformed through modelId.
  get: function get(obj) {
    if (obj == null) return undefined;
    return this._byId[obj] || this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] || obj.cid && this._byId[obj.cid];
  },
  // Returns `true` if the model is in the collection.
  has: function has(obj) {
    return this.get(obj) != null;
  },
  // Get the model at the given index.
  at: function at(index) {
    if (index < 0) index += this.length;
    return this.models[index];
  },
  // Return models with matching attributes. Useful for simple cases of
  // `filter`.
  where: function where(attrs, first) {
    return this[first ? 'find' : 'filter'](attrs);
  },
  // Return the first model with matching attributes. Useful for simple cases
  // of `find`.
  findWhere: function findWhere(attrs) {
    return this.where(attrs, true);
  },
  find: function find(predicate, fromIndex) {
    var pred = lodash_es_isFunction(predicate) ? predicate : function (m) {
      return m.matches(predicate);
    };
    return this.models.find(pred, fromIndex);
  },
  // Force the collection to re-sort itself. You don't need to call this under
  // normal circumstances, as the set will maintain sort order as each item
  // is added.
  sort: function sort(options) {
    var comparator = this.comparator;
    if (!comparator) throw new Error('Cannot sort a set without a comparator');
    options || (options = {});
    var length = comparator.length;
    if (lodash_es_isFunction(comparator)) comparator = comparator.bind(this);

    // Run sort based on type of `comparator`.
    if (length === 1 || lodash_es_isString(comparator)) {
      this.models = this.sortBy(comparator);
    } else {
      this.models.sort(comparator);
    }
    if (!options.silent) this.trigger('sort', this, options);
    return this;
  },
  // Pluck an attribute from each model in the collection.
  pluck: function pluck(attr) {
    return this.map(attr + '');
  },
  // Fetch the default set of models for this collection, resetting the
  // collection when they arrive. If `reset: true` is passed, the response
  // data will be passed through the `reset` method instead of `set`.
  fetch: function fetch(options) {
    options = lodash_es_assignIn({
      parse: true
    }, options);
    var success = options.success;
    var collection = this;
    var promise = options.promise && getResolveablePromise();
    options.success = function (resp) {
      var method = options.reset ? 'reset' : 'set';
      collection[method](resp, options);
      if (success) success.call(options.context, collection, resp, options);
      promise && promise.resolve();
      collection.trigger('sync', collection, resp, options);
    };
    wrapError(this, options);
    return promise ? promise : this.sync('read', this, options);
  },
  // Create a new instance of a model in this collection. Add the model to the
  // collection immediately, unless `wait: true` is passed, in which case we
  // wait for the server to agree.
  create: function create(model, options) {
    options = options ? lodash_es_clone(options) : {};
    var wait = options.wait;
    var return_promise = options.promise;
    var promise = return_promise && getResolveablePromise();
    model = this._prepareModel(model, options);
    if (!model) return false;
    if (!wait) this.add(model, options);
    var collection = this;
    var success = options.success;
    var error = options.error;
    options.success = function (m, resp, callbackOpts) {
      if (wait) {
        collection.add(m, callbackOpts);
      }
      if (success) {
        success.call(callbackOpts.context, m, resp, callbackOpts);
      }
      if (return_promise) {
        promise.resolve(m);
      }
    };
    options.error = function (model, e, options) {
      error && error.call(options.context, model, e, options);
      return_promise && promise.reject(e);
    };
    model.save(null, Object.assign(options, {
      'promise': false
    }));
    if (return_promise) {
      return promise;
    } else {
      return model;
    }
  },
  // **parse** converts a response into a list of models to be added to the
  // collection. The default implementation is just to pass it through.
  parse: function parse(resp, options) {
    return resp;
  },
  // Create a new collection with an identical list of models as this one.
  clone: function clone() {
    return new this.constructor(this.models, {
      model: this.model,
      comparator: this.comparator
    });
  },
  // Define how to uniquely identify models in the collection.
  modelId: function modelId(attrs) {
    var _this$model$prototype;
    return attrs[((_this$model$prototype = this.model.prototype) === null || _this$model$prototype === void 0 ? void 0 : _this$model$prototype.idAttribute) || 'id'];
  },
  // Get an iterator of all models in this collection.
  values: function values() {
    return new CollectionIterator(this, ITERATOR_VALUES);
  },
  // Get an iterator of all model IDs in this collection.
  keys: function keys() {
    return new CollectionIterator(this, ITERATOR_KEYS);
  },
  // Get an iterator of all [ID, model] tuples in this collection.
  entries: function entries() {
    return new CollectionIterator(this, ITERATOR_KEYSVALUES);
  },
  // Private method to reset all internal state. Called when the collection
  // is first initialized or reset.
  _reset: function _reset() {
    this.length = 0;
    this.models = [];
    this._byId = {};
  },
  // Prepare a hash of attributes (or other model) to be added to this
  // collection.
  _prepareModel: function _prepareModel(attrs, options) {
    if (this._isModel(attrs)) {
      if (!attrs.collection) attrs.collection = this;
      return attrs;
    }
    options = options ? lodash_es_clone(options) : {};
    options.collection = this;
    var model = new this.model(attrs, options);
    if (!model.validationError) return model;
    this.trigger('invalid', this, model.validationError, options);
    return false;
  },
  // Internal method called by both remove and set.
  _removeModels: function _removeModels(models, options) {
    var removed = [];
    for (var i = 0; i < models.length; i++) {
      var model = this.get(models[i]);
      if (!model) continue;
      var index = this.indexOf(model);
      this.models.splice(index, 1);
      this.length--;

      // Remove references before triggering 'remove' event to prevent an
      // infinite loop. #3693
      delete this._byId[model.cid];
      var id = this.modelId(model.attributes);
      if (id != null) delete this._byId[id];
      if (!options.silent) {
        options.index = index;
        model.trigger('remove', model, this, options);
      }
      removed.push(model);
      this._removeReference(model, options);
    }
    return removed;
  },
  // Method for checking whether an object should be considered a model for
  // the purposes of adding to the collection.
  _isModel: function _isModel(model) {
    return model instanceof Model;
  },
  // Internal method to create a model's ties to a collection.
  _addReference: function _addReference(model, options) {
    this._byId[model.cid] = model;
    var id = this.modelId(model.attributes);
    if (id != null) this._byId[id] = model;
    model.on('all', this._onModelEvent, this);
  },
  // Internal method to sever a model's ties to a collection.
  _removeReference: function _removeReference(model, options) {
    delete this._byId[model.cid];
    var id = this.modelId(model.attributes);
    if (id != null) delete this._byId[id];
    if (this === model.collection) delete model.collection;
    model.off('all', this._onModelEvent, this);
  },
  // Internal method called every time a model in the set fires an event.
  // Sets need to update their indexes when models change ids. All other
  // events simply proxy through. "add" and "remove" events that originate
  // in other collections are ignored.
  _onModelEvent: function _onModelEvent(event, model, collection, options) {
    if (model) {
      if ((event === 'add' || event === 'remove') && collection !== this) return;
      if (event === 'destroy') this.remove(model, options);
      if (event === 'change') {
        var prevId = this.modelId(model.previousAttributes());
        var id = this.modelId(model.attributes);
        if (prevId !== id) {
          if (prevId != null) delete this._byId[prevId];
          if (id != null) this._byId[id] = model;
        }
      }
    }
    this.trigger.apply(this, arguments);
  }
});

// Defining an @@iterator method implements JavaScript's Iterable protocol.
// In modern ES2015 browsers, this value is found at Symbol.iterator.
/* global Symbol */
var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
if ($$iterator) {
  Collection.prototype[$$iterator] = Collection.prototype.values;
}

// CollectionIterator
// ------------------

// A CollectionIterator implements JavaScript's Iterator protocol, allowing the
// use of `for of` loops in modern browsers and interoperation between
// Collection and other JavaScript functions and third-party libraries
// which can operate on Iterables.
var CollectionIterator = function CollectionIterator(collection, kind) {
  this._collection = collection;
  this._kind = kind;
  this._index = 0;
};

// This "enum" defines the three possible kinds of values which can be emitted
// by a CollectionIterator that correspond to the values(), keys() and entries()
// methods on Collection, respectively.
var ITERATOR_VALUES = 1;
var ITERATOR_KEYS = 2;
var ITERATOR_KEYSVALUES = 3;

// All Iterators should themselves be Iterable.
if ($$iterator) {
  CollectionIterator.prototype[$$iterator] = function () {
    return this;
  };
}
CollectionIterator.prototype.next = function () {
  if (this._collection) {
    // Only continue iterating if the iterated collection is long enough.
    if (this._index < this._collection.length) {
      var model = this._collection.at(this._index);
      this._index++;

      // Construct a value depending on what kind of values should be iterated.
      var value;
      if (this._kind === ITERATOR_VALUES) {
        value = model;
      } else {
        var id = this._collection.modelId(model.attributes);
        if (this._kind === ITERATOR_KEYS) {
          value = id;
        } else {
          // ITERATOR_KEYSVALUES
          value = [id, model];
        }
      }
      return {
        value: value,
        done: false
      };
    }

    // Once exhausted, remove the reference to the collection so future
    // calls to the next method always return done.
    this._collection = undefined;
  }
  return {
    value: undefined,
    done: true
  };
};
;// CONCATENATED MODULE: external "filesize"
const external_filesize_namespaceObject = filesize;
;// CONCATENATED MODULE: external "lit"
const external_lit_namespaceObject = lit;
;// CONCATENATED MODULE: ./src/headless/shared/api/public.js
function public_typeof(obj) {
  "@babel/helpers - typeof";

  return public_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;
  }, public_typeof(obj);
}
function public_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  public_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" == public_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 public_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 public_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        public_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        public_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}




















/**
 * ### The Public API
 *
 * This namespace contains public API methods which are are
 * accessible on the global `converse` object.
 * They are public, because any JavaScript in the
 * page can call them. Public methods therefore don’t expose any sensitive
 * or closured data. To do that, you’ll need to create a plugin, which has
 * access to the private API method.
 *
 * @global
 * @namespace converse
 */
var public_converse = Object.assign(window.converse || {}, {
  CHAT_STATES: CHAT_STATES,
  keycodes: KEYCODES,
  /**
   * Public API method which initializes Converse.
   * This method must always be called when using Converse.
   * @async
   * @memberOf converse
   * @method initialize
   * @param { object } config A map of [configuration-settings](https://conversejs.org/docs/html/configuration.html#configuration-settings).
   * @example
   * converse.initialize({
   *     auto_list_rooms: false,
   *     auto_subscribe: false,
   *     bosh_service_url: 'https://bind.example.com',
   *     hide_muc_server: false,
   *     i18n: 'en',
   *     play_sounds: true,
   *     show_controlbox_by_default: true,
   *     debug: false,
   *     roster_groups: true
   * });
   */
  initialize: function initialize(settings) {
    return public_asyncToGenerator( /*#__PURE__*/public_regeneratorRuntime().mark(function _callee() {
      var _api$elements, _plugins$converseBos;
      var api, plugins;
      return public_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            api = shared_converse.api;
            _context.next = 3;
            return cleanup(shared_converse);
          case 3:
            setUnloadEvent();
            initAppSettings(settings);
            shared_converse.strict_plugin_dependencies = settings.strict_plugin_dependencies; // Needed by pluggable.js
            log.setLogLevel(api.settings.get("loglevel"));
            if (!(api.settings.get("authentication") === ANONYMOUS)) {
              _context.next = 10;
              break;
            }
            if (!(api.settings.get("auto_login") && !api.settings.get('jid'))) {
              _context.next = 10;
              break;
            }
            throw new Error("Config Error: you need to provide the server's " + "domain via the 'jid' option when using anonymous " + "authentication with auto_login.");
          case 10:
            shared_converse.router.route(/^converse\?loglevel=(debug|info|warn|error|fatal)$/, 'loglevel', function (l) {
              return log.setLogLevel(l);
            });
            shared_converse.connfeedback = new feedback();

            /* When reloading the page:
             * For new sessions, we need to send out a presence stanza to notify
             * the server/network that we're online.
             * When re-attaching to an existing session we don't need to again send out a presence stanza,
             * because it's as if "we never left" (see onConnectStatusChanged).
             * https://github.com/conversejs/converse.js/issues/521
             */
            shared_converse.send_initial_presence = true;
            _context.next = 15;
            return initSessionStorage(shared_converse);
          case 15:
            _context.next = 17;
            return initClientConfig(shared_converse);
          case 17:
            _context.next = 19;
            return i18n.initialize();
          case 19:
            initPlugins(shared_converse);

            // Register all custom elements
            // XXX: api.elements is defined in the UI part of Converse, outside of @converse/headless.
            // This line should probably be moved to the UI code as part of a larger refactoring.
            (_api$elements = api.elements) === null || _api$elements === void 0 ? void 0 : _api$elements.register();
            registerGlobalEventHandlers(shared_converse);
            try {
              !History.started && shared_converse.router.history.start();
            } catch (e) {
              log.error(e);
            }
            plugins = shared_converse.pluggable.plugins;
            if (!(api.settings.get("auto_login") || api.settings.get("keepalive") && (_plugins$converseBos = plugins['converse-bosh']) !== null && _plugins$converseBos !== void 0 && _plugins$converseBos.enabled())) {
              _context.next = 27;
              break;
            }
            _context.next = 27;
            return api.user.login(null, null, true);
          case 27:
            /**
             * Triggered once converse.initialize has finished.
             * @event _converse#initialized
             */
            api.trigger('initialized');
            if (!shared_converse.isTestEnv()) {
              _context.next = 30;
              break;
            }
            return _context.abrupt("return", shared_converse);
          case 30:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * Exposes methods for adding and removing plugins. You'll need to write a plugin
   * if you want to have access to the private API methods defined further down below.
   *
   * For more information on plugins, read the documentation on [writing a plugin](/docs/html/plugin_development.html).
   * @namespace plugins
   * @memberOf converse
   */
  plugins: {
    /**
     * Registers a new plugin.
     * @method converse.plugins.add
     * @param { string } name The name of the plugin
     * @param { object } plugin The plugin object
     * @example
     *  const plugin = {
     *      initialize: function () {
     *          // Gets called as soon as the plugin has been loaded.
     *
     *          // Inside this method, you have access to the private
     *          // API via `_covnerse.api`.
     *
     *          // The private _converse object contains the core logic
     *          // and data-structures of Converse.
     *      }
     *  }
     *  converse.plugins.add('myplugin', plugin);
     */
    add: function add(name, plugin) {
      plugin.__name__ = name;
      if (shared_converse.pluggable.plugins[name] !== undefined) {
        throw new TypeError("Error: plugin with name \"".concat(name, "\" has already been ") + 'registered!');
      } else {
        shared_converse.pluggable.plugins[name] = plugin;
      }
    }
  },
  /**
   * Utility methods and globals from bundled 3rd party libraries.
   * @typedef ConverseEnv
   * @property { Error } converse.env.TimeoutError
   * @property { function } converse.env.$build    - Creates a Strophe.Builder, for creating stanza objects.
   * @property { function } converse.env.$iq       - Creates a Strophe.Builder with an <iq/> element as the root.
   * @property { function } converse.env.$msg      - Creates a Strophe.Builder with an <message/> element as the root.
   * @property { function } converse.env.$pres     - Creates a Strophe.Builder with an <presence/> element as the root.
   * @property { function } converse.env.Promise   - The Promise implementation used by Converse.
   * @property { function } converse.env.Strophe   - The [Strophe](http://strophe.im/strophejs) XMPP library used by Converse.
   * @property { function } converse.env.f         - And instance of Lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
   * @property { function } converse.env.sizzle    - [Sizzle](https://sizzlejs.com) CSS selector engine.
   * @property { function } converse.env.sprintf
   * @property { object } converse.env._           - The instance of [lodash-es](http://lodash.com) used by Converse.
   * @property { object } converse.env.dayjs       - [DayJS](https://github.com/iamkun/dayjs) date manipulation library.
   * @property { object } converse.env.utils       - Module containing common utility methods used by Converse.
   * @memberOf converse
   */
  'env': {
    $build: external_strophe_namespaceObject.$build,
    $iq: external_strophe_namespaceObject.$iq,
    $msg: external_strophe_namespaceObject.$msg,
    $pres: external_strophe_namespaceObject.$pres,
    'utils': core,
    Collection: Collection,
    Model: Model,
    Promise: Promise,
    Strophe: external_strophe_namespaceObject.Strophe,
    TimeoutError: TimeoutError,
    URI: (external_urijs_default()),
    VERSION_NAME: VERSION_NAME,
    dayjs: (dayjs_min_default()),
    filesize: external_filesize_namespaceObject.filesize,
    html: external_lit_namespaceObject.html,
    log: log,
    sizzle: (external_sizzle_default()),
    sprintf: sprintf.sprintf,
    stx: stx,
    u: core
  }
});
;// CONCATENATED MODULE: ./src/headless/core.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */










dayjs_min_default().extend((advancedFormat_default()));
;// CONCATENATED MODULE: ./src/headless/plugins/chat/model-with-contact.js
function model_with_contact_typeof(obj) {
  "@babel/helpers - typeof";

  return model_with_contact_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;
  }, model_with_contact_typeof(obj);
}
function model_with_contact_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  model_with_contact_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" == model_with_contact_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 model_with_contact_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 model_with_contact_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        model_with_contact_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        model_with_contact_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var ModelWithContact = Model.extend({
  initialize: function initialize() {
    this.rosterContactAdded = getOpenPromise();
  },
  setRosterContact: function setRosterContact(jid) {
    var _this = this;
    return model_with_contact_asyncToGenerator( /*#__PURE__*/model_with_contact_regeneratorRuntime().mark(function _callee() {
      var contact;
      return model_with_contact_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return shared_api.contacts.get(jid);
          case 2:
            contact = _context.sent;
            if (contact) {
              _this.contact = contact;
              _this.set('nickname', contact.get('nickname'));
              _this.rosterContactAdded.resolve();
            }
          case 4:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  }
});
/* harmony default export */ const model_with_contact = (ModelWithContact);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isMatch.js



/**
 * Performs a partial deep comparison between `object` and `source` to
 * determine if `object` contains equivalent property values.
 *
 * **Note:** This method is equivalent to `_.matches` when `source` is
 * partially applied.
 *
 * Partial comparisons will match empty array and empty object `source`
 * values against any array or object value, respectively. See `_.isEqual`
 * for a list of supported value comparisons.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 *
 * _.isMatch(object, { 'b': 2 });
 * // => true
 *
 * _.isMatch(object, { 'b': 1 });
 * // => false
 */
function isMatch(object, source) {
  return object === source || _baseIsMatch(object, source, _getMatchData(source));
}
/* harmony default export */ const lodash_es_isMatch = (isMatch);
;// CONCATENATED MODULE: ./src/headless/shared/chat/utils.js
function chat_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_utils_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;
  }, chat_utils_typeof(obj);
}
function chat_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chat_utils_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" == chat_utils_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 chat_utils_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 chat_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var utils_u = public_converse.env.u;
function pruneHistory(model) {
  var max_history = shared_api.settings.get('prune_messages_above');
  if (max_history && typeof max_history === 'number') {
    if (model.messages.length > max_history) {
      var non_empty_messages = model.messages.filter(function (m) {
        return !utils_u.isEmptyMessage(m);
      });
      if (non_empty_messages.length > max_history) {
        while (non_empty_messages.length > max_history) {
          non_empty_messages.shift().destroy();
        }
        /**
         * Triggered once the message history has been pruned, i.e.
         * once older messages have been removed to keep the
         * number of messages below the value set in `prune_messages_above`.
         * @event _converse#historyPruned
         * @type { _converse.ChatBox | _converse.ChatRoom }
         * @example _converse.api.listen.on('historyPruned', this => { ... });
         */
        shared_api.trigger('historyPruned', model);
      }
    }
  }
}

/**
 * Given an array of {@link MediaURLMetadata} objects and text, return an
 * array of {@link MediaURL} objects.
 * @param { Array<MediaURLMetadata> } arr
 * @param { String } text
 * @returns{ Array<MediaURL> }
 */
function utils_getMediaURLs(arr, text) {
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  /**
   * @typedef { Object } MediaURLData
   * An object representing a URL found in a chat message
   * @property { Boolean } is_audio
   * @property { Boolean } is_image
   * @property { Boolean } is_video
   * @property { String } end
   * @property { String } start
   * @property { String } url
   */
  return arr.map(function (o) {
    var start = o.start - offset;
    var end = o.end - offset;
    if (start < 0 || start >= text.length) {
      return null;
    }
    return Object.assign({}, o, {
      start: start,
      end: end,
      'url': text.substring(o.start - offset, o.end - offset)
    });
  }).filter(function (o) {
    return o;
  });
}

/**
 * Determines whether the given attributes of an incoming message
 * represent a XEP-0308 correction and, if so, handles it appropriately.
 * @private
 * @method _converse.ChatBox#handleCorrection
 * @param { _converse.ChatBox | _converse.ChatRoom }
 * @param { object } attrs - Attributes representing a received
 *  message, as returned by {@link parseMessage}
 * @returns { _converse.Message|undefined } Returns the corrected
 *  message or `undefined` if not applicable.
 */
function handleCorrection(_x, _x2) {
  return _handleCorrection.apply(this, arguments);
}
function _handleCorrection() {
  _handleCorrection = chat_utils_asyncToGenerator( /*#__PURE__*/chat_utils_regeneratorRuntime().mark(function _callee(model, attrs) {
    var query, message, older_versions;
    return chat_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!(!attrs.replace_id || !attrs.from)) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return");
        case 2:
          query = attrs.type === 'groupchat' && attrs.occupant_id ? function (_ref) {
            var m = _ref.attributes;
            return m.msgid === attrs.replace_id && m.occupant_id == attrs.occupant_id;
          }
          // eslint-disable-next-line no-eq-null
          : function (_ref2) {
            var m = _ref2.attributes;
            return m.msgid === attrs.replace_id && m.from === attrs.from && m.occupant_id == null;
          };
          message = model.messages.models.find(query);
          if (message) {
            _context.next = 9;
            break;
          }
          attrs['older_versions'] = {};
          _context.next = 8;
          return model.createMessage(attrs);
        case 8:
          return _context.abrupt("return", _context.sent);
        case 9:
          older_versions = message.get('older_versions') || {};
          if (attrs.time < message.get('time') && message.get('edited')) {
            // This is an older message which has been corrected afterwards
            older_versions[attrs.time] = attrs['message'];
            message.save({
              'older_versions': older_versions
            });
          } else {
            // This is a correction of an earlier message we already received
            if (Object.keys(older_versions).length) {
              older_versions[message.get('edited')] = message.getMessageText();
            } else {
              older_versions[message.get('time')] = message.getMessageText();
            }
            attrs = Object.assign(attrs, {
              older_versions: older_versions
            });
            delete attrs['msgid']; // We want to keep the msgid of the original message
            delete attrs['id']; // Delete id, otherwise a new cache entry gets created
            attrs['time'] = message.get('time');
            message.save(attrs);
          }
          return _context.abrupt("return", message);
        case 12:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _handleCorrection.apply(this, arguments);
}
var debouncedPruneHistory = lodash_es_debounce(pruneHistory, 500);
;// CONCATENATED MODULE: ./src/headless/shared/actions.js



var actions_u = public_converse.env.utils;
function rejectMessage(stanza, text) {
  // Reject an incoming message by replying with an error message of type "cancel".
  shared_api.send((0,external_strophe_namespaceObject.$msg)({
    'to': stanza.getAttribute('from'),
    'type': 'error',
    'id': stanza.getAttribute('id')
  }).c('error', {
    'type': 'cancel'
  }).c('not-allowed', {
    xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  }).up().c('text', {
    xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  }).t(text));
  log.warn("Rejecting message stanza with the following reason: ".concat(text));
  log.warn(stanza);
}

/**
 * Send out a XEP-0333 chat marker
 * @param { String } to_jid
 * @param { String } id - The id of the message being marked
 * @param { String } type - The marker type
 * @param { String } msg_type
 */
function sendMarker(to_jid, id, type, msg_type) {
  var stanza = (0,external_strophe_namespaceObject.$msg)({
    'from': shared_converse.connection.jid,
    'id': actions_u.getUniqueId(),
    'to': to_jid,
    'type': msg_type ? msg_type : 'chat'
  }).c(type, {
    'xmlns': external_strophe_namespaceObject.Strophe.NS.MARKERS,
    'id': id
  });
  shared_api.send(stanza);
}
;// CONCATENATED MODULE: ./src/headless/utils/url.js



var url_u = public_converse.env.u;

/**
 * Given a url, check whether the protocol being used is allowed for rendering
 * the media in the chat (as opposed to just rendering a URL hyperlink).
 * @param { String } url
 * @returns { Boolean }
 */
function isAllowedProtocolForMedia(url) {
  var uri = getURI(url);
  var protocol = window.location.protocol;
  if (['chrome-extension:', 'file:'].includes(protocol)) {
    return true;
  }
  return protocol === 'http:' || protocol === 'https:' && ['https', 'aesgcm'].includes(uri.protocol().toLowerCase());
}
function getURI(url) {
  try {
    return url instanceof (external_urijs_default()) ? url : new (external_urijs_default())(url);
  } catch (error) {
    log.debug(error);
    return null;
  }
}

/**
 * Given the an array of file extensions, check whether a URL points to a file
 * ending in one of them.
 * @param { String[] } types - An array of file extensions
 * @param { String } url
 * @returns { Boolean }
 * @example
 *  checkFileTypes(['.gif'], 'https://conversejs.org/cat.gif?foo=bar');
 */
function checkFileTypes(types, url) {
  var uri = getURI(url);
  if (uri === null) {
    throw new Error("checkFileTypes: could not parse url ".concat(url));
  }
  var filename = uri.filename().toLowerCase();
  return !!types.filter(function (ext) {
    return filename.endsWith(ext);
  }).length;
}
function isDomainWhitelisted(whitelist, url) {
  var uri = getURI(url);
  var subdomain = uri.subdomain();
  var domain = uri.domain();
  var fulldomain = "".concat(subdomain ? "".concat(subdomain, ".") : '').concat(domain);
  return whitelist.includes(domain) || whitelist.includes(fulldomain);
}
function shouldRenderMediaFromURL(url_text, type) {
  if (!isAllowedProtocolForMedia(url_text)) {
    return false;
  }
  var may_render = shared_api.settings.get('render_media');
  var is_domain_allowed = isDomainAllowed(url_text, "allowed_".concat(type, "_domains"));
  if (Array.isArray(may_render)) {
    return is_domain_allowed && isDomainWhitelisted(may_render, url_text);
  } else {
    return is_domain_allowed && may_render;
  }
}
function filterQueryParamsFromURL(url) {
  var paramsArray = shared_api.settings.get('filter_url_query_params');
  if (!paramsArray) return url;
  var parsed_uri = getURI(url);
  return parsed_uri.removeQuery(paramsArray).toString();
}
function isDomainAllowed(url, setting) {
  var allowed_domains = shared_api.settings.get(setting);
  if (!Array.isArray(allowed_domains)) {
    return true;
  }
  try {
    return isDomainWhitelisted(allowed_domains, url);
  } catch (error) {
    log.debug(error);
    return false;
  }
}

/**
 * Accepts a {@link MediaURL} object and then checks whether its domain is
 * allowed for rendering in the chat.
 * @param { MediaURL } o
 * @returns { Bool }
 */
function isMediaURLDomainAllowed(o) {
  return o.is_audio && isDomainAllowed(o.url, 'allowed_audio_domains') || o.is_video && isDomainAllowed(o.url, 'allowed_video_domains') || o.is_image && isDomainAllowed(o.url, 'allowed_image_domains');
}
function isURLWithImageExtension(url) {
  return checkFileTypes(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg'], url);
}
function isGIFURL(url) {
  return checkFileTypes(['.gif'], url);
}
function isAudioURL(url) {
  return checkFileTypes(['.ogg', '.mp3', '.m4a'], url);
}
function isVideoURL(url) {
  return checkFileTypes(['.mp4', '.webm'], url);
}
function isImageURL(url) {
  var regex = shared_api.settings.get('image_urls_regex');
  return (regex === null || regex === void 0 ? void 0 : regex.test(url)) || isURLWithImageExtension(url);
}
function isEncryptedFileURL(url) {
  return url.startsWith('aesgcm://');
}
Object.assign(url_u, {
  isAudioURL: isAudioURL,
  isGIFURL: isGIFURL,
  isVideoURL: isVideoURL,
  isImageURL: isImageURL,
  isURLWithImageExtension: isURLWithImageExtension,
  checkFileTypes: checkFileTypes,
  getURI: getURI,
  shouldRenderMediaFromURL: shouldRenderMediaFromURL,
  isAllowedProtocolForMedia: isAllowedProtocolForMedia
});
;// CONCATENATED MODULE: ./src/headless/shared/parsers.js
function parsers_typeof(obj) {
  "@babel/helpers - typeof";

  return parsers_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;
  }, parsers_typeof(obj);
}
function parsers_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, parsers_toPropertyKey(descriptor.key), descriptor);
  }
}
function parsers_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) parsers_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) parsers_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function parsers_toPropertyKey(arg) {
  var key = parsers_toPrimitive(arg, "string");
  return parsers_typeof(key) === "symbol" ? key : String(key);
}
function parsers_toPrimitive(input, hint) {
  if (parsers_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (parsers_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function parsers_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function parsers_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) parsers_setPrototypeOf(subClass, superClass);
}
function parsers_createSuper(Derived) {
  var hasNativeReflectConstruct = parsers_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = parsers_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = parsers_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return parsers_possibleConstructorReturn(this, result);
  };
}
function parsers_possibleConstructorReturn(self, call) {
  if (call && (parsers_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 parsers_assertThisInitialized(self);
}
function parsers_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function parsers_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  parsers_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !parsers_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return parsers_construct(Class, arguments, parsers_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return parsers_setPrototypeOf(Wrapper, Class);
  };
  return parsers_wrapNativeSuper(Class);
}
function parsers_construct(Parent, args, Class) {
  if (parsers_isNativeReflectConstruct()) {
    parsers_construct = Reflect.construct.bind();
  } else {
    parsers_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) parsers_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return parsers_construct.apply(null, arguments);
}
function parsers_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 parsers_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function parsers_setPrototypeOf(o, p) {
  parsers_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return parsers_setPrototypeOf(o, p);
}
function parsers_getPrototypeOf(o) {
  parsers_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return parsers_getPrototypeOf(o);
}










var NS = external_strophe_namespaceObject.Strophe.NS;
var StanzaParseError = /*#__PURE__*/function (_Error) {
  parsers_inherits(StanzaParseError, _Error);
  var _super = parsers_createSuper(StanzaParseError);
  function StanzaParseError(message, stanza) {
    var _this;
    parsers_classCallCheck(this, StanzaParseError);
    _this = _super.call(this, message, stanza);
    _this.name = 'StanzaParseError';
    _this.stanza = stanza;
    return _this;
  }
  return parsers_createClass(StanzaParseError);
}( /*#__PURE__*/parsers_wrapNativeSuper(Error));

/**
 * Extract the XEP-0359 stanza IDs from the passed in stanza
 * and return a map containing them.
 * @private
 * @param { Element } stanza - The message stanza
 * @returns { Object }
 */
function getStanzaIDs(stanza, original_stanza) {
  var attrs = {};
  // Store generic stanza ids
  var sids = external_sizzle_default()("stanza-id[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.SID, "\"]"), stanza);
  var sid_attrs = sids.reduce(function (acc, s) {
    acc["stanza_id ".concat(s.getAttribute('by'))] = s.getAttribute('id');
    return acc;
  }, {});
  Object.assign(attrs, sid_attrs);

  // Store the archive id
  var result = external_sizzle_default()("message > result[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MAM, "\"]"), original_stanza).pop();
  if (result) {
    var by_jid = original_stanza.getAttribute('from') || shared_converse.bare_jid;
    attrs["stanza_id ".concat(by_jid)] = result.getAttribute('id');
  }

  // Store the origin id
  var origin_id = external_sizzle_default()("origin-id[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.SID, "\"]"), stanza).pop();
  if (origin_id) {
    attrs['origin_id'] = origin_id.getAttribute('id');
  }
  return attrs;
}
function getEncryptionAttributes(stanza) {
  var eme_tag = external_sizzle_default()("encryption[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.EME, "\"]"), stanza).pop();
  var namespace = eme_tag === null || eme_tag === void 0 ? void 0 : eme_tag.getAttribute('namespace');
  var attrs = {};
  if (namespace) {
    attrs.is_encrypted = true;
    attrs.encryption_namespace = namespace;
  } else if (external_sizzle_default()("encrypted[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.OMEMO, "\"]"), stanza).pop()) {
    attrs.is_encrypted = true;
    attrs.encryption_namespace = external_strophe_namespaceObject.Strophe.NS.OMEMO;
  }
  return attrs;
}

/**
 * @private
 * @param { Element } stanza - The message stanza
 * @param { Element } original_stanza - The original stanza, that contains the
 *  message stanza, if it was contained, otherwise it's the message stanza itself.
 * @returns { Object }
 */
function getRetractionAttributes(stanza, original_stanza) {
  var fastening = external_sizzle_default()("> apply-to[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.FASTEN, "\"]"), stanza).pop();
  if (fastening) {
    var applies_to_id = fastening.getAttribute('id');
    var retracted = external_sizzle_default()("> retract[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.RETRACT, "\"]"), fastening).pop();
    if (retracted) {
      var delay = external_sizzle_default()("delay[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.DELAY, "\"]"), original_stanza).pop();
      var time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
      return {
        'editable': false,
        'retracted': time,
        'retracted_id': applies_to_id
      };
    }
  } else {
    var tombstone = external_sizzle_default()("> retracted[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.RETRACT, "\"]"), stanza).pop();
    if (tombstone) {
      return {
        'editable': false,
        'is_tombstone': true,
        'retracted': tombstone.getAttribute('stamp')
      };
    }
  }
  return {};
}
function getCorrectionAttributes(stanza, original_stanza) {
  var el = external_sizzle_default()("replace[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MESSAGE_CORRECT, "\"]"), stanza).pop();
  if (el) {
    var replace_id = el.getAttribute('id');
    if (replace_id) {
      var delay = external_sizzle_default()("delay[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.DELAY, "\"]"), original_stanza).pop();
      var time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
      return {
        replace_id: replace_id,
        'edited': time
      };
    }
  }
  return {};
}
function getOpenGraphMetadata(stanza) {
  var fastening = external_sizzle_default()("> apply-to[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.FASTEN, "\"]"), stanza).pop();
  if (fastening) {
    var applies_to_id = fastening.getAttribute('id');
    var meta = external_sizzle_default()("> meta[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.XHTML, "\"]"), fastening);
    if (meta.length) {
      var msg_limit = shared_api.settings.get('message_limit');
      var data = meta.reduce(function (acc, el) {
        var property = el.getAttribute('property');
        if (property) {
          var value = decodeHTMLEntities(el.getAttribute('content') || '');
          if (msg_limit && property === 'og:description' && value.length >= msg_limit) {
            value = "".concat(value.slice(0, msg_limit)).concat(decodeHTMLEntities('&#8230;'));
          }
          acc[property] = value;
        }
        return acc;
      }, {
        'ogp_for_id': applies_to_id
      });
      if ("og:description" in data || "og:title" in data || "og:image" in data) {
        return data;
      }
    }
  }
  return {};
}
function getMediaURLsMetadata(text) {
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var objs = [];
  if (!text) {
    return {};
  }
  try {
    external_urijs_default().withinString(text, function (url, start, end) {
      if (url.startsWith('_')) {
        url = url.slice(1);
        start += 1;
      }
      if (url.endsWith('_')) {
        url = url.slice(0, url.length - 1);
        end -= 1;
      }
      objs.push({
        url: url,
        'start': start + offset,
        'end': end + offset
      });
      return url;
    }, URL_PARSE_OPTIONS);
  } catch (error) {
    log.debug(error);
  }

  /**
   * @typedef { Object } MediaURLMetadata
   * An object representing the metadata of a URL found in a chat message
   * The actual URL is not saved, it can be extracted via the `start` and `end` indexes.
   * @property { Boolean } is_audio
   * @property { Boolean } is_image
   * @property { Boolean } is_video
   * @property { String } end
   * @property { String } start
   */
  var media_urls = objs.map(function (o) {
    return {
      'end': o.end,
      'is_audio': isAudioURL(o.url),
      'is_image': isImageURL(o.url),
      'is_video': isVideoURL(o.url),
      'is_encrypted': isEncryptedFileURL(o.url),
      'start': o.start
    };
  });
  return media_urls.length ? {
    media_urls: media_urls
  } : {};
}
function getSpoilerAttributes(stanza) {
  var spoiler = external_sizzle_default()("spoiler[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.SPOILER, "\"]"), stanza).pop();
  return {
    'is_spoiler': !!spoiler,
    'spoiler_hint': spoiler === null || spoiler === void 0 ? void 0 : spoiler.textContent
  };
}
function getOutOfBandAttributes(stanza) {
  var xform = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.OUTOFBAND, "\"]"), stanza).pop();
  if (xform) {
    var _xform$querySelector, _xform$querySelector2;
    return {
      'oob_url': (_xform$querySelector = xform.querySelector('url')) === null || _xform$querySelector === void 0 ? void 0 : _xform$querySelector.textContent,
      'oob_desc': (_xform$querySelector2 = xform.querySelector('desc')) === null || _xform$querySelector2 === void 0 ? void 0 : _xform$querySelector2.textContent
    };
  }
  return {};
}

/**
 * Returns the human readable error message contained in a `groupchat` message stanza of type `error`.
 * @private
 * @param { Element } stanza - The message stanza
 */
function getErrorAttributes(stanza) {
  if (stanza.getAttribute('type') === 'error') {
    var error = stanza.querySelector('error');
    var text = external_sizzle_default()("text[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), error).pop();
    return {
      'is_error': true,
      'error_text': text === null || text === void 0 ? void 0 : text.textContent,
      'error_type': error.getAttribute('type'),
      'error_condition': error.firstElementChild.nodeName
    };
  }
  return {};
}

/**
 * Given a message stanza, find and return any XEP-0372 references
 * @param { Element } stana - The message stanza
 * @returns { Reference }
 */
function getReferences(stanza) {
  return external_sizzle_default()("reference[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.REFERENCE, "\"]"), stanza).map(function (ref) {
    var _stanza$querySelector;
    var anchor = ref.getAttribute('anchor');
    var text = (_stanza$querySelector = stanza.querySelector(anchor ? "#".concat(anchor) : 'body')) === null || _stanza$querySelector === void 0 ? void 0 : _stanza$querySelector.textContent;
    if (!text) {
      log.warn("Could not find referenced text for ".concat(ref));
      return null;
    }
    var begin = ref.getAttribute('begin');
    var end = ref.getAttribute('end');
    /**
     * @typedef { Object } Reference
     * An object representing XEP-0372 reference data
     * @property { string } begin
     * @property { string } end
     * @property { string } type
     * @property { String } value
     * @property { String } uri
     */
    return {
      begin: begin,
      end: end,
      'type': ref.getAttribute('type'),
      'value': text.slice(begin, end),
      'uri': ref.getAttribute('uri')
    };
  }).filter(function (r) {
    return r;
  });
}
function getReceiptId(stanza) {
  var receipt = external_sizzle_default()("received[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.RECEIPTS, "\"]"), stanza).pop();
  return receipt === null || receipt === void 0 ? void 0 : receipt.getAttribute('id');
}

/**
 * Determines whether the passed in stanza is a XEP-0280 Carbon
 * @private
 * @param { Element } stanza - The message stanza
 * @returns { Boolean }
 */
function isCarbon(stanza) {
  var xmlns = external_strophe_namespaceObject.Strophe.NS.CARBONS;
  return external_sizzle_default()("message > received[xmlns=\"".concat(xmlns, "\"]"), stanza).length > 0 || external_sizzle_default()("message > sent[xmlns=\"".concat(xmlns, "\"]"), stanza).length > 0;
}

/**
 * Returns the XEP-0085 chat state contained in a message stanza
 * @private
 * @param { Element } stanza - The message stanza
 */
function getChatState(stanza) {
  var _sizzle$pop;
  return (_sizzle$pop = external_sizzle_default()("\n        composing[xmlns=\"".concat(NS.CHATSTATES, "\"],\n        paused[xmlns=\"").concat(NS.CHATSTATES, "\"],\n        inactive[xmlns=\"").concat(NS.CHATSTATES, "\"],\n        active[xmlns=\"").concat(NS.CHATSTATES, "\"],\n        gone[xmlns=\"").concat(NS.CHATSTATES, "\"]"), stanza).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.nodeName;
}
function isValidReceiptRequest(stanza, attrs) {
  return attrs.sender !== 'me' && !attrs.is_carbon && !attrs.is_archived && external_sizzle_default()("request[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.RECEIPTS, "\"]"), stanza).length;
}

/**
 * Check whether the passed-in stanza is a forwarded message that is "bare",
 * i.e. it's not forwarded as part of a larger protocol, like MAM.
 * @param { Element } stanza
 */
function throwErrorIfInvalidForward(stanza) {
  var bare_forward = external_sizzle_default()("message > forwarded[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.FORWARD, "\"]"), stanza).length;
  if (bare_forward) {
    rejectMessage(stanza, 'Forwarded messages not part of an encapsulating protocol are not supported');
    var from_jid = stanza.getAttribute('from');
    throw new StanzaParseError("Ignoring unencapsulated forwarded message from ".concat(from_jid), stanza);
  }
}

/**
 * Determines whether the passed in stanza is a XEP-0333 Chat Marker
 * @private
 * @method getChatMarker
 * @param { Element } stanza - The message stanza
 * @returns { Boolean }
 */
function getChatMarker(stanza) {
  // If we receive more than one marker (which shouldn't happen), we take
  // the highest level of acknowledgement.
  return external_sizzle_default()("\n        acknowledged[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MARKERS, "\"],\n        displayed[xmlns=\"").concat(external_strophe_namespaceObject.Strophe.NS.MARKERS, "\"],\n        received[xmlns=\"").concat(external_strophe_namespaceObject.Strophe.NS.MARKERS, "\"]"), stanza).pop();
}
function isHeadline(stanza) {
  return stanza.getAttribute('type') === 'headline';
}
function isServerMessage(stanza) {
  if (external_sizzle_default()("mentions[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MENTIONS, "\"]"), stanza).pop()) {
    return false;
  }
  var from_jid = stanza.getAttribute('from');
  if (stanza.getAttribute('type') !== 'error' && from_jid && !from_jid.includes('@')) {
    // Some servers (e.g. Prosody) don't set the stanza
    // type to "headline" when sending server messages.
    // For now we check if an @ signal is included, and if not,
    // we assume it's a headline stanza.
    return true;
  }
  return false;
}

/**
 * Determines whether the passed in stanza is a XEP-0313 MAM stanza
 * @private
 * @method isArchived
 * @param { Element } stanza - The message stanza
 * @returns { Boolean }
 */
function isArchived(original_stanza) {
  return !!external_sizzle_default()("message > result[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MAM, "\"]"), original_stanza).pop();
}

/**
 * Returns an object containing all attribute names and values for a particular element.
 * @method getAttributes
 * @param { Element } stanza
 * @returns { Object }
 */
function getAttributes(stanza) {
  return stanza.getAttributeNames().reduce(function (acc, name) {
    acc[name] = external_strophe_namespaceObject.Strophe.xmlunescape(stanza.getAttribute(name));
    return acc;
  }, {});
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/parsers.js
function chat_parsers_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_parsers_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;
  }, chat_parsers_typeof(obj);
}
function parsers_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  parsers_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" == chat_parsers_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 parsers_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 parsers_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        parsers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        parsers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var _converse$env = public_converse.env,
  Strophe = _converse$env.Strophe,
  parsers_sizzle = _converse$env.sizzle;

/**
 * Parses a passed in message stanza and returns an object of attributes.
 * @method st#parseMessage
 * @param { Element } stanza - The message stanza
 * @param { _converse } _converse
 * @returns { (MessageAttributes|Error) }
 */
function parseMessage(_x) {
  return _parseMessage.apply(this, arguments);
}
function _parseMessage() {
  _parseMessage = parsers_asyncToGenerator( /*#__PURE__*/parsers_regeneratorRuntime().mark(function _callee(stanza) {
    var _stanza$querySelector, _stanza$querySelector2, _contact, _contact$attributes, _stanza$querySelector3, _stanza$querySelector4;
    var to_jid, to_resource, original_stanza, from_jid, selector, is_archived, _selector, from_bare_jid, is_me, is_headline, is_server_message, contact, contact_jid, delay, marker, now, attrs, from;
    return parsers_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          throwErrorIfInvalidForward(stanza);
          to_jid = stanza.getAttribute('to');
          to_resource = Strophe.getResourceFromJid(to_jid);
          if (!(shared_api.settings.get('filter_by_resource') && to_resource && to_resource !== shared_converse.resource)) {
            _context.next = 5;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Ignoring incoming message intended for a different resource: ".concat(to_jid), stanza));
        case 5:
          original_stanza = stanza;
          from_jid = stanza.getAttribute('from') || shared_converse.bare_jid;
          if (!isCarbon(stanza)) {
            _context.next = 17;
            break;
          }
          if (!(from_jid === shared_converse.bare_jid)) {
            _context.next = 15;
            break;
          }
          selector = "[xmlns=\"".concat(Strophe.NS.CARBONS, "\"] > forwarded[xmlns=\"").concat(Strophe.NS.FORWARD, "\"] > message");
          stanza = parsers_sizzle(selector, stanza).pop();
          to_jid = stanza.getAttribute('to');
          from_jid = stanza.getAttribute('from');
          _context.next = 17;
          break;
        case 15:
          // Prevent message forging via carbons: https://xmpp.org/extensions/xep-0280.html#security
          rejectMessage(stanza, 'Rejecting carbon from invalid JID');
          return _context.abrupt("return", new StanzaParseError("Rejecting carbon from invalid JID ".concat(to_jid), stanza));
        case 17:
          is_archived = isArchived(stanza);
          if (!is_archived) {
            _context.next = 27;
            break;
          }
          if (!(from_jid === shared_converse.bare_jid)) {
            _context.next = 26;
            break;
          }
          _selector = "[xmlns=\"".concat(Strophe.NS.MAM, "\"] > forwarded[xmlns=\"").concat(Strophe.NS.FORWARD, "\"] > message");
          stanza = parsers_sizzle(_selector, stanza).pop();
          to_jid = stanza.getAttribute('to');
          from_jid = stanza.getAttribute('from');
          _context.next = 27;
          break;
        case 26:
          return _context.abrupt("return", new StanzaParseError("Invalid Stanza: alleged MAM message from ".concat(stanza.getAttribute('from')), stanza));
        case 27:
          from_bare_jid = Strophe.getBareJidFromJid(from_jid);
          is_me = from_bare_jid === shared_converse.bare_jid;
          if (!(is_me && to_jid === null)) {
            _context.next = 31;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Don't know how to handle message stanza without 'to' attribute. ".concat(stanza.outerHTML), stanza));
        case 31:
          is_headline = isHeadline(stanza);
          is_server_message = isServerMessage(stanza);
          if (!(!is_headline && !is_server_message)) {
            _context.next = 41;
            break;
          }
          contact_jid = is_me ? Strophe.getBareJidFromJid(to_jid) : from_bare_jid;
          _context.next = 37;
          return shared_api.contacts.get(contact_jid);
        case 37:
          contact = _context.sent;
          if (!(contact === undefined && !shared_api.settings.get('allow_non_roster_messaging'))) {
            _context.next = 41;
            break;
          }
          log.error(stanza);
          return _context.abrupt("return", new StanzaParseError("Blocking messaging with a JID not in our roster because allow_non_roster_messaging is false.", stanza));
        case 41:
          /**
           * @typedef { Object } MessageAttributes
           * The object which {@link parseMessage} returns
           * @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
           * @property { Array<Object> } references - A list of objects representing XEP-0372 references
           * @property { Boolean } editable - Is this message editable via XEP-0308?
           * @property { Boolean } is_archived -  Is this message from a XEP-0313 MAM archive?
           * @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
           * @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
           * @property { Boolean } is_encrypted -  Is this message XEP-0384  encrypted?
           * @property { Boolean } is_error - Whether an error was received for this message
           * @property { Boolean } is_headline - Is this a "headline" message?
           * @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
           * @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
           * @property { Boolean } is_only_emojis - Does the message body contain only emojis?
           * @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
           * @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
           * @property { Boolean } is_unstyled - Whether XEP-0393 styling hints should be ignored
           * @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
           * @property { Object } encrypted -  XEP-0384 encryption payload attributes
           * @property { String } body - The contents of the <body> tag of the message stanza
           * @property { String } chat_state - The XEP-0085 chat state notification contained in this message
           * @property { String } contact_jid - The JID of the other person or entity
           * @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
           * @property { String } error_condition - The defined error condition
           * @property { String } error_text - The error text received from the server
           * @property { String } error_type - The type of error received from the server
           * @property { String } from - The sender JID
           * @property { String } fullname - The full name of the sender
           * @property { String } marker - The XEP-0333 Chat Marker value
           * @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
           * @property { String } msgid - The root `id` attribute of the stanza
           * @property { String } nick - The roster nickname of the sender
           * @property { String } oob_desc - The description of the XEP-0066 out of band data
           * @property { String } oob_url - The URL of the XEP-0066 out of band data
           * @property { String } origin_id - The XEP-0359 Origin ID
           * @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
           * @property { String } received - An ISO8601 string recording the time that the message was received
           * @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
           * @property { String } retracted - An ISO8601 string recording the time that the message was retracted
           * @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
           * @property { String } spoiler_hint  The XEP-0382 spoiler hint
           * @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
           * @property { String } subject - The <subject> element value
           * @property { String } thread - The <thread> element value
           * @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
           * @property { String } to - The recipient JID
           * @property { String } type - The type of message
           */
          delay = parsers_sizzle("delay[xmlns=\"".concat(Strophe.NS.DELAY, "\"]"), original_stanza).pop();
          marker = getChatMarker(stanza);
          now = new Date().toISOString();
          attrs = Object.assign({
            contact_jid: contact_jid,
            is_archived: is_archived,
            is_headline: is_headline,
            is_server_message: is_server_message,
            'body': (_stanza$querySelector = stanza.querySelector('body')) === null || _stanza$querySelector === void 0 ? void 0 : (_stanza$querySelector2 = _stanza$querySelector.textContent) === null || _stanza$querySelector2 === void 0 ? void 0 : _stanza$querySelector2.trim(),
            'chat_state': getChatState(stanza),
            'from': Strophe.getBareJidFromJid(stanza.getAttribute('from')),
            'is_carbon': isCarbon(original_stanza),
            'is_delayed': !!delay,
            'is_markable': !!parsers_sizzle("markable[xmlns=\"".concat(Strophe.NS.MARKERS, "\"]"), stanza).length,
            'is_marker': !!marker,
            'is_unstyled': !!parsers_sizzle("unstyled[xmlns=\"".concat(Strophe.NS.STYLING, "\"]"), stanza).length,
            'marker_id': marker && marker.getAttribute('id'),
            'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
            'nick': (_contact = contact) === null || _contact === void 0 ? void 0 : (_contact$attributes = _contact.attributes) === null || _contact$attributes === void 0 ? void 0 : _contact$attributes.nickname,
            'receipt_id': getReceiptId(stanza),
            'received': new Date().toISOString(),
            'references': getReferences(stanza),
            'sender': is_me ? 'me' : 'them',
            'subject': (_stanza$querySelector3 = stanza.querySelector('subject')) === null || _stanza$querySelector3 === void 0 ? void 0 : _stanza$querySelector3.textContent,
            'thread': (_stanza$querySelector4 = stanza.querySelector('thread')) === null || _stanza$querySelector4 === void 0 ? void 0 : _stanza$querySelector4.textContent,
            'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : now,
            'to': stanza.getAttribute('to'),
            'type': stanza.getAttribute('type') || 'normal'
          }, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getRetractionAttributes(stanza, original_stanza), getEncryptionAttributes(stanza, shared_converse));
          if (!attrs.is_archived) {
            _context.next = 49;
            break;
          }
          from = original_stanza.getAttribute('from');
          if (!(from && from !== shared_converse.bare_jid)) {
            _context.next = 49;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Invalid Stanza: Forged MAM message from ".concat(from), stanza));
        case 49:
          _context.next = 51;
          return shared_api.emojis.initialize();
        case 51:
          attrs = Object.assign({
            'message': attrs.body || attrs.error,
            // TODO: Remove and use body and error attributes instead
            'is_only_emojis': attrs.body ? core.isOnlyEmojis(attrs.body) : false,
            'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs)
          }, attrs);

          // We prefer to use one of the XEP-0359 unique and stable stanza IDs
          // as the Model id, to avoid duplicates.
          attrs['id'] = attrs['origin_id'] || attrs["stanza_id ".concat(attrs.from)] || core.getUniqueId();

          /**
           * *Hook* which allows plugins to add additional parsing
           * @event _converse#parseMessage
           */
          _context.next = 55;
          return shared_api.hook('parseMessage', stanza, attrs);
        case 55:
          attrs = _context.sent;
          return _context.abrupt("return", Object.assign(attrs, getMediaURLsMetadata(attrs.is_encrypted ? attrs.plaintext : attrs.body)));
        case 57:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _parseMessage.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/model.js
function chat_model_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_model_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;
  }, chat_model_typeof(obj);
}
function model_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 model_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? model_ownKeys(Object(source), !0).forEach(function (key) {
      model_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : model_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function model_defineProperty(obj, key, value) {
  key = model_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 model_toPropertyKey(arg) {
  var key = model_toPrimitive(arg, "string");
  return chat_model_typeof(key) === "symbol" ? key : String(key);
}
function model_toPrimitive(input, hint) {
  if (chat_model_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chat_model_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || model_unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function model_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return model_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 model_arrayLikeToArray(o, minLen);
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return model_arrayLikeToArray(arr);
}
function model_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 model_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  model_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" == chat_model_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 model_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 model_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        model_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        model_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
















var model_converse$env = public_converse.env,
  model_Strophe = model_converse$env.Strophe,
  $msg = model_converse$env.$msg;
var model_u = public_converse.env.utils;

/**
 * Represents an open/ongoing chat conversation.
 *
 * @class
 * @namespace _converse.ChatBox
 * @memberOf _converse
 */
var ChatBox = model_with_contact.extend({
  defaults: function defaults() {
    return {
      'bookmarked': false,
      'chat_state': undefined,
      'hidden': isUniView() && !shared_api.settings.get('singleton'),
      'message_type': 'chat',
      'nickname': undefined,
      'num_unread': 0,
      'time_opened': this.get('time_opened') || new Date().getTime(),
      'time_sent': new Date(0).toISOString(),
      'type': shared_converse.PRIVATE_CHAT_TYPE,
      'url': ''
    };
  },
  initialize: function initialize() {
    var _arguments = arguments,
      _this = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee() {
      var jid;
      return model_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.initialized = getOpenPromise();
            model_with_contact.prototype.initialize.apply(_this, _arguments);
            jid = _this.get('jid');
            if (jid) {
              _context.next = 5;
              break;
            }
            return _context.abrupt("return");
          case 5:
            _this.set({
              'box_id': "box-".concat(jid)
            });
            _this.initNotifications();
            _this.initUI();
            _this.initMessages();
            if (!(_this.get('type') === shared_converse.PRIVATE_CHAT_TYPE)) {
              _context.next = 14;
              break;
            }
            _this.presence = shared_converse.presences.get(jid) || shared_converse.presences.create({
              jid: jid
            });
            _context.next = 13;
            return _this.setRosterContact(jid);
          case 13:
            _this.presence.on('change:show', function (item) {
              return _this.onPresenceChanged(item);
            });
          case 14:
            _this.on('change:chat_state', _this.sendChatState, _this);
            _this.ui.on('change:scrolled', _this.onScrolledChanged, _this);
            _context.next = 18;
            return _this.fetchMessages();
          case 18:
            _context.next = 20;
            return shared_api.trigger('chatBoxInitialized', _this, {
              'Synchronous': true
            });
          case 20:
            _this.initialized.resolve();
          case 21:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  getMessagesCollection: function getMessagesCollection() {
    return new shared_converse.Messages();
  },
  getMessagesCacheKey: function getMessagesCacheKey() {
    return "converse.messages-".concat(this.get('jid'), "-").concat(shared_converse.bare_jid);
  },
  initMessages: function initMessages() {
    this.messages = this.getMessagesCollection();
    this.messages.fetched = getOpenPromise();
    this.messages.chatbox = this;
    initStorage(this.messages, this.getMessagesCacheKey());
    this.listenTo(this.messages, 'change:upload', this.onMessageUploadChanged, this);
    this.listenTo(this.messages, 'add', this.onMessageAdded, this);
  },
  initUI: function initUI() {
    this.ui = new Model();
  },
  initNotifications: function initNotifications() {
    this.notifications = new Model();
  },
  getNotificationsText: function getNotificationsText() {
    var _this$notifications, _this$notifications2, _this$notifications3;
    var __ = shared_converse.__;
    if (((_this$notifications = this.notifications) === null || _this$notifications === void 0 ? void 0 : _this$notifications.get('chat_state')) === shared_converse.COMPOSING) {
      return __('%1$s is typing', this.getDisplayName());
    } else if (((_this$notifications2 = this.notifications) === null || _this$notifications2 === void 0 ? void 0 : _this$notifications2.get('chat_state')) === shared_converse.PAUSED) {
      return __('%1$s has stopped typing', this.getDisplayName());
    } else if (((_this$notifications3 = this.notifications) === null || _this$notifications3 === void 0 ? void 0 : _this$notifications3.get('chat_state')) === shared_converse.GONE) {
      return __('%1$s has gone away', this.getDisplayName());
    } else {
      return '';
    }
  },
  afterMessagesFetched: function afterMessagesFetched() {
    this.pruneHistoryWhenScrolledDown();
    /**
     * Triggered whenever a { @link _converse.ChatBox } or ${ @link _converse.ChatRoom }
     * has fetched its messages from the local cache.
     * @event _converse#afterMessagesFetched
     * @type { _converse.ChatBox| _converse.ChatRoom }
     * @example _converse.api.listen.on('afterMessagesFetched', (chat) => { ... });
     */
    shared_api.trigger('afterMessagesFetched', this);
  },
  fetchMessages: function fetchMessages() {
    var _this2 = this;
    if (this.messages.fetched_flag) {
      log.info("Not re-fetching messages for ".concat(this.get('jid')));
      return;
    }
    this.messages.fetched_flag = true;
    var resolve = this.messages.fetched.resolve;
    this.messages.fetch({
      'add': true,
      'success': function success(msgs) {
        _this2.afterMessagesFetched(msgs);
        resolve();
      },
      'error': function error() {
        _this2.afterMessagesFetched();
        resolve();
      }
    });
    return this.messages.fetched;
  },
  handleErrorMessageStanza: function handleErrorMessageStanza(stanza) {
    var _this3 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee2() {
      var __, attrs, message, new_attrs;
      return model_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            __ = shared_converse.__;
            _context2.next = 3;
            return parseMessage(stanza, shared_converse);
          case 3:
            attrs = _context2.sent;
            _context2.next = 6;
            return _this3.shouldShowErrorMessage(attrs);
          case 6:
            if (_context2.sent) {
              _context2.next = 8;
              break;
            }
            return _context2.abrupt("return");
          case 8:
            message = _this3.getMessageReferencedByError(attrs);
            if (message) {
              new_attrs = {
                'error': attrs.error,
                'error_condition': attrs.error_condition,
                'error_text': attrs.error_text,
                'error_type': attrs.error_type,
                'editable': false
              };
              if (attrs.msgid === message.get('retraction_id')) {
                // The error message refers to a retraction
                new_attrs.retraction_id = undefined;
                if (!attrs.error) {
                  if (attrs.error_condition === 'forbidden') {
                    new_attrs.error = __("You're not allowed to retract your message.");
                  } else {
                    new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
                  }
                }
              } else if (!attrs.error) {
                if (attrs.error_condition === 'forbidden') {
                  new_attrs.error = __("You're not allowed to send a message.");
                } else {
                  new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
                }
              }
              message.save(new_attrs);
            } else {
              _this3.createMessage(attrs);
            }
          case 10:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  /**
   * Queue an incoming `chat` message stanza for processing.
   * @async
   * @private
   * @method _converse.ChatBox#queueMessage
   * @param { Promise<MessageAttributes> } attrs - A promise which resolves to the message attributes
   */
  queueMessage: function queueMessage(attrs) {
    var _this4 = this;
    this.msg_chain = (this.msg_chain || this.messages.fetched).then(function () {
      return _this4.onMessage(attrs);
    }).catch(function (e) {
      return log.error(e);
    });
    return this.msg_chain;
  },
  /**
   * @async
   * @private
   * @method _converse.ChatBox#onMessage
   * @param { MessageAttributes } attrs_promse - A promise which resolves to the message attributes.
   */
  onMessage: function onMessage(attrs) {
    var _this5 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee3() {
      var message, msg;
      return model_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return attrs;
          case 2:
            attrs = _context3.sent;
            if (!model_u.isErrorObject(attrs)) {
              _context3.next = 6;
              break;
            }
            attrs.stanza && log.error(attrs.stanza);
            return _context3.abrupt("return", log.error(attrs.message));
          case 6:
            message = _this5.getDuplicateMessage(attrs);
            if (!message) {
              _context3.next = 11;
              break;
            }
            _this5.updateMessage(message, attrs);
            _context3.next = 30;
            break;
          case 11:
            _context3.t0 = !_this5.handleReceipt(attrs) && !_this5.handleChatMarker(attrs);
            if (!_context3.t0) {
              _context3.next = 16;
              break;
            }
            _context3.next = 15;
            return _this5.handleRetraction(attrs);
          case 15:
            _context3.t0 = !_context3.sent;
          case 16:
            if (!_context3.t0) {
              _context3.next = 30;
              break;
            }
            _this5.setEditable(attrs, attrs.time);
            if (attrs['chat_state'] && attrs.sender === 'them') {
              _this5.notifications.set('chat_state', attrs.chat_state);
            }
            if (!model_u.shouldCreateMessage(attrs)) {
              _context3.next = 30;
              break;
            }
            _context3.next = 22;
            return handleCorrection(_this5, attrs);
          case 22:
            _context3.t1 = _context3.sent;
            if (_context3.t1) {
              _context3.next = 27;
              break;
            }
            _context3.next = 26;
            return _this5.createMessage(attrs);
          case 26:
            _context3.t1 = _context3.sent;
          case 27:
            msg = _context3.t1;
            _this5.notifications.set({
              'chat_state': null
            });
            _this5.handleUnreadMessage(msg);
          case 30:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  },
  onMessageUploadChanged: function onMessageUploadChanged(message) {
    var _this6 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee4() {
      var attrs;
      return model_regeneratorRuntime().wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            if (!(message.get('upload') === shared_converse.SUCCESS)) {
              _context4.next = 5;
              break;
            }
            attrs = {
              'body': message.get('body'),
              'spoiler_hint': message.get('spoiler_hint'),
              'oob_url': message.get('oob_url')
            };
            _context4.next = 4;
            return _this6.sendMessage(attrs);
          case 4:
            message.destroy();
          case 5:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }))();
  },
  onMessageAdded: function onMessageAdded(message) {
    if (shared_api.settings.get('prune_messages_above') && (shared_api.settings.get('pruning_behavior') === 'scrolled' || !this.ui.get('scrolled')) && !isEmptyMessage(message)) {
      debouncedPruneHistory(this);
    }
  },
  clearMessages: function clearMessages() {
    var _this7 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee5() {
      return model_regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            _context5.prev = 0;
            _context5.next = 3;
            return _this7.messages.clearStore();
          case 3:
            _context5.next = 9;
            break;
          case 5:
            _context5.prev = 5;
            _context5.t0 = _context5["catch"](0);
            _this7.messages.trigger('reset');
            log.error(_context5.t0);
          case 9:
            _context5.prev = 9;
            // No point in fetching messages from the cache if it's been cleared.
            // Make sure to resolve the fetched promise to avoid freezes.
            _this7.messages.fetched.resolve();
            return _context5.finish(9);
          case 12:
          case "end":
            return _context5.stop();
        }
      }, _callee5, null, [[0, 5, 9, 12]]);
    }))();
  },
  close: function close() {
    var _this8 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee6() {
      return model_regeneratorRuntime().wrap(function _callee6$(_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            if (shared_api.connection.connected()) {
              // Immediately sending the chat state, because the
              // model is going to be destroyed afterwards.
              _this8.setChatState(shared_converse.INACTIVE);
              _this8.sendChatState();
            }
            _context6.prev = 1;
            _context6.next = 4;
            return new Promise(function (success, reject) {
              return _this8.destroy({
                success: success,
                'error': function error(m, e) {
                  return reject(e);
                }
              });
            });
          case 4:
            _context6.next = 9;
            break;
          case 6:
            _context6.prev = 6;
            _context6.t0 = _context6["catch"](1);
            log.error(_context6.t0);
          case 9:
            _context6.prev = 9;
            if (!shared_api.settings.get('clear_messages_on_reconnection')) {
              _context6.next = 13;
              break;
            }
            _context6.next = 13;
            return _this8.clearMessages();
          case 13:
            return _context6.finish(9);
          case 14:
            /**
             * Triggered once a chatbox has been closed.
             * @event _converse#chatBoxClosed
             * @type {_converse.ChatBox | _converse.ChatRoom}
             * @example _converse.api.listen.on('chatBoxClosed', chat => { ... });
             */
            shared_api.trigger('chatBoxClosed', _this8);
          case 15:
          case "end":
            return _context6.stop();
        }
      }, _callee6, null, [[1, 6, 9, 14]]);
    }))();
  },
  announceReconnection: function announceReconnection() {
    /**
     * Triggered whenever a `_converse.ChatBox` instance has reconnected after an outage
     * @event _converse#onChatReconnected
     * @type {_converse.ChatBox | _converse.ChatRoom}
     * @example _converse.api.listen.on('onChatReconnected', chat => { ... });
     */
    shared_api.trigger('chatReconnected', this);
  },
  onReconnection: function onReconnection() {
    var _this9 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee7() {
      return model_regeneratorRuntime().wrap(function _callee7$(_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            if (!shared_api.settings.get('clear_messages_on_reconnection')) {
              _context7.next = 3;
              break;
            }
            _context7.next = 3;
            return _this9.clearMessages();
          case 3:
            _this9.announceReconnection();
          case 4:
          case "end":
            return _context7.stop();
        }
      }, _callee7);
    }))();
  },
  onPresenceChanged: function onPresenceChanged(item) {
    var __ = shared_converse.__;
    var show = item.get('show');
    var fullname = this.getDisplayName();
    var text;
    if (show === 'offline') {
      text = __('%1$s has gone offline', fullname);
    } else if (show === 'away') {
      text = __('%1$s has gone away', fullname);
    } else if (show === 'dnd') {
      text = __('%1$s is busy', fullname);
    } else if (show === 'online') {
      text = __('%1$s is online', fullname);
    }
    text && this.createMessage({
      'message': text,
      'type': 'info'
    });
  },
  onScrolledChanged: function onScrolledChanged() {
    if (!this.ui.get('scrolled')) {
      this.clearUnreadMsgCounter();
      this.pruneHistoryWhenScrolledDown();
    }
  },
  pruneHistoryWhenScrolledDown: function pruneHistoryWhenScrolledDown() {
    if (shared_api.settings.get('prune_messages_above') && shared_api.settings.get('pruning_behavior') === 'unscrolled' && !this.ui.get('scrolled')) {
      debouncedPruneHistory(this);
    }
  },
  validate: function validate(attrs) {
    if (!attrs.jid) {
      return 'Ignored ChatBox without JID';
    }
    var room_jids = shared_api.settings.get('auto_join_rooms').map(function (s) {
      return lodash_es_isObject(s) ? s.jid : s;
    });
    var auto_join = shared_api.settings.get('auto_join_private_chats').concat(room_jids);
    if (shared_api.settings.get("singleton") && !auto_join.includes(attrs.jid) && !shared_api.settings.get('auto_join_on_invite')) {
      var msg = "".concat(attrs.jid, " is not allowed because singleton is true and it's not being auto_joined");
      log.warn(msg);
      return msg;
    }
  },
  getDisplayName: function getDisplayName() {
    if (this.contact) {
      return this.contact.getDisplayName();
    } else if (this.vcard) {
      return this.vcard.getDisplayName();
    } else {
      return this.get('jid');
    }
  },
  createMessageFromError: function createMessageFromError(error) {
    var _this10 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee8() {
      var msg;
      return model_regeneratorRuntime().wrap(function _callee8$(_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            if (!(error instanceof TimeoutError)) {
              _context8.next = 5;
              break;
            }
            _context8.next = 3;
            return _this10.createMessage({
              'type': 'error',
              'message': error.message,
              'retry_event_id': error.retry_event_id,
              'is_ephemeral': 30000
            });
          case 3:
            msg = _context8.sent;
            msg.error = error;
          case 5:
          case "end":
            return _context8.stop();
        }
      }, _callee8);
    }))();
  },
  editEarlierMessage: function editEarlierMessage() {
    var message;
    var idx = this.messages.findLastIndex('correcting');
    if (idx >= 0) {
      this.messages.at(idx).save('correcting', false);
      while (idx > 0) {
        idx -= 1;
        var candidate = this.messages.at(idx);
        if (candidate.get('editable')) {
          message = candidate;
          break;
        }
      }
    }
    message = message || this.messages.filter({
      'sender': 'me'
    }).reverse().find(function (m) {
      return m.get('editable');
    });
    if (message) {
      message.save('correcting', true);
    }
  },
  editLaterMessage: function editLaterMessage() {
    var message;
    var idx = this.messages.findLastIndex('correcting');
    if (idx >= 0) {
      this.messages.at(idx).save('correcting', false);
      while (idx < this.messages.length - 1) {
        idx += 1;
        var candidate = this.messages.at(idx);
        if (candidate.get('editable')) {
          message = candidate;
          message.save('correcting', true);
          break;
        }
      }
    }
    return message;
  },
  getOldestMessage: function getOldestMessage() {
    for (var i = 0; i < this.messages.length; i++) {
      var message = this.messages.at(i);
      if (message.get('type') === this.get('message_type')) {
        return message;
      }
    }
  },
  getMostRecentMessage: function getMostRecentMessage() {
    for (var i = this.messages.length - 1; i >= 0; i--) {
      var message = this.messages.at(i);
      if (message.get('type') === this.get('message_type')) {
        return message;
      }
    }
  },
  getUpdatedMessageAttributes: function getUpdatedMessageAttributes(message, attrs) {
    if (!attrs.error_type && message.get('error_type') === 'Decryption') {
      // Looks like we have a failed decrypted message stored, and now
      // we have a properly decrypted version of the same message.
      // See issue: https://github.com/conversejs/converse.js/issues/2733#issuecomment-1035493594
      return Object.assign({}, attrs, {
        error_condition: undefined,
        error_message: undefined,
        error_text: undefined,
        error_type: undefined,
        is_archived: attrs.is_archived,
        is_ephemeral: false,
        is_error: false
      });
    } else {
      return {
        is_archived: attrs.is_archived
      };
    }
  },
  updateMessage: function updateMessage(message, attrs) {
    var new_attrs = this.getUpdatedMessageAttributes(message, attrs);
    new_attrs && message.save(new_attrs);
  },
  /**
   * Mutator for setting the chat state of this chat session.
   * Handles clearing of any chat state notification timeouts and
   * setting new ones if necessary.
   * Timeouts are set when the  state being set is COMPOSING or PAUSED.
   * After the timeout, COMPOSING will become PAUSED and PAUSED will become INACTIVE.
   * See XEP-0085 Chat State Notifications.
   * @private
   * @method _converse.ChatBox#setChatState
   * @param { string } state - The chat state (consts ACTIVE, COMPOSING, PAUSED, INACTIVE, GONE)
   */
  setChatState: function setChatState(state, options) {
    if (this.chat_state_timeout !== undefined) {
      window.clearTimeout(this.chat_state_timeout);
      delete this.chat_state_timeout;
    }
    if (state === shared_converse.COMPOSING) {
      this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), shared_converse.TIMEOUTS.PAUSED, shared_converse.PAUSED);
    } else if (state === shared_converse.PAUSED) {
      this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), shared_converse.TIMEOUTS.INACTIVE, shared_converse.INACTIVE);
    }
    this.set('chat_state', state, options);
    return this;
  },
  /**
   * Given an error `<message>` stanza's attributes, find the saved message model which is
   * referenced by that error.
   * @param { Object } attrs
   */
  getMessageReferencedByError: function getMessageReferencedByError(attrs) {
    var id = attrs.msgid;
    return id && this.messages.models.find(function (m) {
      return [m.get('msgid'), m.get('retraction_id')].includes(id);
    });
  },
  /**
   * @private
   * @method _converse.ChatBox#shouldShowErrorMessage
   * @returns {boolean}
   */
  shouldShowErrorMessage: function shouldShowErrorMessage(attrs) {
    var msg = this.getMessageReferencedByError(attrs);
    if (!msg && attrs.chat_state) {
      // If the error refers to a message not included in our store,
      // and it has a chat state tag, we assume that this was a
      // CSI message (which we don't store).
      // See https://github.com/conversejs/converse.js/issues/1317
      return;
    }
    // Gets overridden in ChatRoom
    return true;
  },
  isSameUser: function isSameUser(jid1, jid2) {
    return model_u.isSameBareJID(jid1, jid2);
  },
  /**
   * Looks whether we already have a retraction for this
   * incoming message. If so, it's considered "dangling" because it
   * probably hasn't been applied to anything yet, given that the
   * relevant message is only coming in now.
   * @private
   * @method _converse.ChatBox#findDanglingRetraction
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMessage}
   * @returns { _converse.Message }
   */
  findDanglingRetraction: function findDanglingRetraction(attrs) {
    if (!attrs.origin_id || !this.messages.length) {
      return null;
    }
    // Only look for dangling retractions if there are newer
    // messages than this one, since retractions come after.
    if (this.messages.last().get('time') > attrs.time) {
      // Search from latest backwards
      var messages = Array.from(this.messages.models);
      messages.reverse();
      return messages.find(function (_ref) {
        var attributes = _ref.attributes;
        return attributes.retracted_id === attrs.origin_id && attributes.from === attrs.from && !attributes.moderated_by;
      });
    }
  },
  /**
   * Handles message retraction based on the passed in attributes.
   * @private
   * @method _converse.ChatBox#handleRetraction
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMessage}
   * @returns { Boolean } Returns `true` or `false` depending on
   *  whether a message was retracted or not.
   */
  handleRetraction: function handleRetraction(attrs) {
    var _this11 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee9() {
      var RETRACTION_ATTRIBUTES, message, _message, retraction_attrs, new_attrs;
      return model_regeneratorRuntime().wrap(function _callee9$(_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            RETRACTION_ATTRIBUTES = ['retracted', 'retracted_id', 'editable'];
            if (!attrs.retracted) {
              _context9.next = 14;
              break;
            }
            if (!attrs.is_tombstone) {
              _context9.next = 4;
              break;
            }
            return _context9.abrupt("return", false);
          case 4:
            message = _this11.messages.findWhere({
              'origin_id': attrs.retracted_id,
              'from': attrs.from
            });
            if (message) {
              _context9.next = 10;
              break;
            }
            attrs['dangling_retraction'] = true;
            _context9.next = 9;
            return _this11.createMessage(attrs);
          case 9:
            return _context9.abrupt("return", true);
          case 10:
            message.save(lodash_es_pick(attrs, RETRACTION_ATTRIBUTES));
            return _context9.abrupt("return", true);
          case 14:
            // Check if we have dangling retraction
            _message = _this11.findDanglingRetraction(attrs);
            if (!_message) {
              _context9.next = 21;
              break;
            }
            retraction_attrs = lodash_es_pick(_message.attributes, RETRACTION_ATTRIBUTES);
            new_attrs = Object.assign({
              'dangling_retraction': false
            }, attrs, retraction_attrs);
            delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created
            _message.save(new_attrs);
            return _context9.abrupt("return", true);
          case 21:
            return _context9.abrupt("return", false);
          case 22:
          case "end":
            return _context9.stop();
        }
      }, _callee9);
    }))();
  },
  /**
   * Returns an already cached message (if it exists) based on the
   * passed in attributes map.
   * @private
   * @method _converse.ChatBox#getDuplicateMessage
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMessage}
   * @returns {Promise<_converse.Message>}
   */
  getDuplicateMessage: function getDuplicateMessage(attrs) {
    var queries = [].concat(_toConsumableArray(this.getStanzaIdQueryAttrs(attrs)), [this.getOriginIdQueryAttrs(attrs), this.getMessageBodyQueryAttrs(attrs)]).filter(function (s) {
      return s;
    });
    var msgs = this.messages.models;
    return msgs.find(function (m) {
      return queries.reduce(function (out, q) {
        return out || lodash_es_isMatch(m.attributes, q);
      }, false);
    });
  },
  getOriginIdQueryAttrs: function getOriginIdQueryAttrs(attrs) {
    return attrs.origin_id && {
      'origin_id': attrs.origin_id,
      'from': attrs.from
    };
  },
  getStanzaIdQueryAttrs: function getStanzaIdQueryAttrs(attrs) {
    var keys = Object.keys(attrs).filter(function (k) {
      return k.startsWith('stanza_id ');
    });
    return keys.map(function (key) {
      var by_jid = key.replace(/^stanza_id /, '');
      var query = {};
      query["stanza_id ".concat(by_jid)] = attrs[key];
      return query;
    });
  },
  getMessageBodyQueryAttrs: function getMessageBodyQueryAttrs(attrs) {
    if (attrs.msgid) {
      var query = {
        'from': attrs.from,
        'msgid': attrs.msgid
      };
      // XXX: Need to take XEP-428 <fallback> into consideration
      if (!attrs.is_encrypted && attrs.body) {
        // We can't match the message if it's a reflected
        // encrypted message (e.g. via MAM or in a MUC)
        query['body'] = attrs.body;
      }
      return query;
    }
  },
  /**
   * Retract one of your messages in this chat
   * @private
   * @method _converse.ChatBoxView#retractOwnMessage
   * @param { _converse.Message } message - The message which we're retracting.
   */
  retractOwnMessage: function retractOwnMessage(message) {
    this.sendRetractionMessage(message);
    message.save({
      'retracted': new Date().toISOString(),
      'retracted_id': message.get('origin_id'),
      'retraction_id': message.get('id'),
      'is_ephemeral': true,
      'editable': false
    });
  },
  /**
   * Sends a message stanza to retract a message in this chat
   * @private
   * @method _converse.ChatBox#sendRetractionMessage
   * @param { _converse.Message } message - The message which we're retracting.
   */
  sendRetractionMessage: function sendRetractionMessage(message) {
    var origin_id = message.get('origin_id');
    if (!origin_id) {
      throw new Error("Can't retract message without a XEP-0359 Origin ID");
    }
    var msg = $msg({
      'id': model_u.getUniqueId(),
      'to': this.get('jid'),
      'type': "chat"
    }).c('store', {
      xmlns: model_Strophe.NS.HINTS
    }).up().c("apply-to", {
      'id': origin_id,
      'xmlns': model_Strophe.NS.FASTEN
    }).c('retract', {
      xmlns: model_Strophe.NS.RETRACT
    });
    return shared_converse.connection.send(msg);
  },
  /**
   * Finds the last eligible message and then sends a XEP-0333 chat marker for it.
   * @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
   * @param { Boolean } force - Whether a marker should be sent for the
   *  message, even if it didn't include a `markable` element.
   */
  sendMarkerForLastMessage: function sendMarkerForLastMessage() {
    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'displayed';
    var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    var msgs = Array.from(this.messages.models);
    msgs.reverse();
    var msg = msgs.find(function (m) {
      return m.get('sender') === 'them' && (force || m.get('is_markable'));
    });
    msg && this.sendMarkerForMessage(msg, type, force);
  },
  /**
   * Given the passed in message object, send a XEP-0333 chat marker.
   * @param { _converse.Message } msg
   * @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
   * @param { Boolean } force - Whether a marker should be sent for the
   *  message, even if it didn't include a `markable` element.
   */
  sendMarkerForMessage: function sendMarkerForMessage(msg) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'displayed';
    var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    if (!msg || !shared_api.settings.get('send_chat_markers').includes(type)) {
      return;
    }
    if (msg !== null && msg !== void 0 && msg.get('is_markable') || force) {
      var from_jid = model_Strophe.getBareJidFromJid(msg.get('from'));
      sendMarker(from_jid, msg.get('msgid'), type, msg.get('type'));
    }
  },
  handleChatMarker: function handleChatMarker(attrs) {
    var to_bare_jid = model_Strophe.getBareJidFromJid(attrs.to);
    if (to_bare_jid !== shared_converse.bare_jid) {
      return false;
    }
    if (attrs.is_markable) {
      if (this.contact && !attrs.is_archived && !attrs.is_carbon) {
        sendMarker(attrs.from, attrs.msgid, 'received');
      }
      return false;
    } else if (attrs.marker_id) {
      var message = this.messages.findWhere({
        'msgid': attrs.marker_id
      });
      var field_name = "marker_".concat(attrs.marker);
      if (message && !message.get(field_name)) {
        message.save({
          field_name: new Date().toISOString()
        });
      }
      return true;
    }
  },
  sendReceiptStanza: function sendReceiptStanza(to_jid, id) {
    var receipt_stanza = $msg({
      'from': shared_converse.connection.jid,
      'id': model_u.getUniqueId(),
      'to': to_jid,
      'type': 'chat'
    }).c('received', {
      'xmlns': model_Strophe.NS.RECEIPTS,
      'id': id
    }).up().c('store', {
      'xmlns': model_Strophe.NS.HINTS
    }).up();
    shared_api.send(receipt_stanza);
  },
  handleReceipt: function handleReceipt(attrs) {
    if (attrs.sender === 'them') {
      if (attrs.is_valid_receipt_request) {
        this.sendReceiptStanza(attrs.from, attrs.msgid);
      } else if (attrs.receipt_id) {
        var message = this.messages.findWhere({
          'msgid': attrs.receipt_id
        });
        if (message && !message.get('received')) {
          message.save({
            'received': new Date().toISOString()
          });
        }
        return true;
      }
    }
    return false;
  },
  /**
   * Given a {@link _converse.Message} return the XML stanza that represents it.
   * @private
   * @method _converse.ChatBox#createMessageStanza
   * @param { _converse.Message } message - The message object
   */
  createMessageStanza: function createMessageStanza(message) {
    var _this12 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee10() {
      var stanza, data;
      return model_regeneratorRuntime().wrap(function _callee10$(_context10) {
        while (1) switch (_context10.prev = _context10.next) {
          case 0:
            stanza = $msg({
              'from': shared_converse.connection.jid,
              'to': _this12.get('jid'),
              'type': _this12.get('message_type'),
              'id': message.get('edited') && model_u.getUniqueId() || message.get('msgid')
            }).c('body').t(message.get('body')).up().c(shared_converse.ACTIVE, {
              'xmlns': model_Strophe.NS.CHATSTATES
            }).root();
            if (message.get('type') === 'chat') {
              stanza.c('request', {
                'xmlns': model_Strophe.NS.RECEIPTS
              }).root();
            }
            if (!message.get('is_encrypted')) {
              if (message.get('is_spoiler')) {
                if (message.get('spoiler_hint')) {
                  stanza.c('spoiler', {
                    'xmlns': model_Strophe.NS.SPOILER
                  }, message.get('spoiler_hint')).root();
                } else {
                  stanza.c('spoiler', {
                    'xmlns': model_Strophe.NS.SPOILER
                  }).root();
                }
              }
              (message.get('references') || []).forEach(function (reference) {
                var attrs = {
                  'xmlns': model_Strophe.NS.REFERENCE,
                  'begin': reference.begin,
                  'end': reference.end,
                  'type': reference.type
                };
                if (reference.uri) {
                  attrs.uri = reference.uri;
                }
                stanza.c('reference', attrs).root();
              });
              if (message.get('oob_url')) {
                stanza.c('x', {
                  'xmlns': model_Strophe.NS.OUTOFBAND
                }).c('url').t(message.get('oob_url')).root();
              }
            }
            if (message.get('edited')) {
              stanza.c('replace', {
                'xmlns': model_Strophe.NS.MESSAGE_CORRECT,
                'id': message.get('msgid')
              }).root();
            }
            if (message.get('origin_id')) {
              stanza.c('origin-id', {
                'xmlns': model_Strophe.NS.SID,
                'id': message.get('origin_id')
              }).root();
            }
            stanza.root();
            /**
             * *Hook* which allows plugins to update an outgoing message stanza
             * @event _converse#createMessageStanza
             * @param { _converse.ChatBox | _converse.ChatRoom } - The chat from
             *      which this message stanza is being sent.
             * @param { Object } data - Message data
             * @param { _converse.Message | _converse.ChatRoomMessage } data.message
             *      The message object from which the stanza is created and which gets persisted to storage.
             * @param { Strophe.Builder } data.stanza
             *      The stanza that will be sent out, as a Strophe.Builder object.
             *      You can use the Strophe.Builder functions to extend the stanza.
             *      See http://strophe.im/strophejs/doc/1.4.3/files/strophe-umd-js.html#Strophe.Builder.Functions
             */
            _context10.next = 8;
            return shared_api.hook('createMessageStanza', _this12, {
              message: message,
              stanza: stanza
            });
          case 8:
            data = _context10.sent;
            return _context10.abrupt("return", data.stanza);
          case 10:
          case "end":
            return _context10.stop();
        }
      }, _callee10);
    }))();
  },
  getOutgoingMessageAttributes: function getOutgoingMessageAttributes(attrs) {
    var _this13 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee11() {
      var _attrs;
      var is_spoiler, origin_id, text, body;
      return model_regeneratorRuntime().wrap(function _callee11$(_context11) {
        while (1) switch (_context11.prev = _context11.next) {
          case 0:
            _context11.next = 2;
            return shared_api.emojis.initialize();
          case 2:
            is_spoiler = !!_this13.get('composing_spoiler');
            origin_id = model_u.getUniqueId();
            text = (_attrs = attrs) === null || _attrs === void 0 ? void 0 : _attrs.body;
            body = text ? model_u.shortnamesToUnicode(text) : undefined;
            attrs = Object.assign({}, attrs, {
              'from': shared_converse.bare_jid,
              'fullname': shared_converse.xmppstatus.get('fullname'),
              'id': origin_id,
              'is_only_emojis': text ? model_u.isOnlyEmojis(text) : false,
              'jid': _this13.get('jid'),
              'message': body,
              'msgid': origin_id,
              'nickname': _this13.get('nickname'),
              'sender': 'me',
              'time': new Date().toISOString(),
              'type': _this13.get('message_type'),
              body: body,
              is_spoiler: is_spoiler,
              origin_id: origin_id
            }, getMediaURLsMetadata(text));

            /**
             * *Hook* which allows plugins to update the attributes of an outgoing message.
             * These attributes get set on the { @link _converse.Message } or
             * { @link _converse.ChatRoomMessage } and persisted to storage.
             * @event _converse#getOutgoingMessageAttributes
             * @param { _converse.ChatBox | _converse.ChatRoom } chat
             *      The chat from which this message will be sent.
             * @param { MessageAttributes } attrs
             *      The message attributes, from which the stanza will be created.
             */
            _context11.next = 9;
            return shared_api.hook('getOutgoingMessageAttributes', _this13, attrs);
          case 9:
            attrs = _context11.sent;
            return _context11.abrupt("return", attrs);
          case 11:
          case "end":
            return _context11.stop();
        }
      }, _callee11);
    }))();
  },
  /**
   * Responsible for setting the editable attribute of messages.
   * If api.settings.get('allow_message_corrections') is "last", then only the last
   * message sent from me will be editable. If set to "all" all messages
   * will be editable. Otherwise no messages will be editable.
   * @method _converse.ChatBox#setEditable
   * @memberOf _converse.ChatBox
   * @param { Object } attrs An object containing message attributes.
   * @param { String } send_time - time when the message was sent
   */
  setEditable: function setEditable(attrs, send_time) {
    if (attrs.is_headline || isEmptyMessage(attrs) || attrs.sender !== 'me') {
      return;
    }
    if (shared_api.settings.get('allow_message_corrections') === 'all') {
      attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
    } else if (shared_api.settings.get('allow_message_corrections') === 'last' && send_time > this.get('time_sent')) {
      var _this$messages$findWh;
      this.set({
        'time_sent': send_time
      });
      (_this$messages$findWh = this.messages.findWhere({
        'editable': true
      })) === null || _this$messages$findWh === void 0 ? void 0 : _this$messages$findWh.save({
        'editable': false
      });
      attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
    }
  },
  /**
   * Queue the creation of a message, to make sure that we don't run
   * into a race condition whereby we're creating a new message
   * before the collection has been fetched.
   * @async
   * @private
   * @method _converse.ChatBox#createMessage
   * @param { Object } attrs
   */
  createMessage: function createMessage(attrs, options) {
    var _this14 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee12() {
      return model_regeneratorRuntime().wrap(function _callee12$(_context12) {
        while (1) switch (_context12.prev = _context12.next) {
          case 0:
            attrs.time = attrs.time || new Date().toISOString();
            _context12.next = 3;
            return _this14.messages.fetched;
          case 3:
            return _context12.abrupt("return", _this14.messages.create(attrs, options));
          case 4:
          case "end":
            return _context12.stop();
        }
      }, _callee12);
    }))();
  },
  /**
   * Responsible for sending off a text message inside an ongoing chat conversation.
   * @private
   * @method _converse.ChatBox#sendMessage
   * @memberOf _converse.ChatBox
   * @param { Object } [attrs] - A map of attributes to be saved on the message
   * @returns { _converse.Message }
   * @example
   * const chat = api.chats.get('buddy1@example.org');
   * chat.sendMessage({'body': 'hello world'});
   */
  sendMessage: function sendMessage(attrs) {
    var _this15 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee13() {
      var message, older_versions, edited_time, stanza;
      return model_regeneratorRuntime().wrap(function _callee13$(_context13) {
        while (1) switch (_context13.prev = _context13.next) {
          case 0:
            _context13.next = 2;
            return _this15.getOutgoingMessageAttributes(attrs);
          case 2:
            attrs = _context13.sent;
            message = _this15.messages.findWhere('correcting');
            if (!message) {
              _context13.next = 11;
              break;
            }
            older_versions = message.get('older_versions') || {};
            edited_time = message.get('edited') || message.get('time');
            older_versions[edited_time] = message.getMessageText();
            message.save(model_objectSpread(model_objectSpread({}, lodash_es_pick(attrs, ['body', 'is_only_emojis', 'media_urls', 'references', 'is_encrypted'])), {
              'correcting': false,
              'edited': new Date().toISOString(),
              'message': attrs.body,
              'ogp_metadata': [],
              'origin_id': model_u.getUniqueId(),
              'received': undefined,
              older_versions: older_versions,
              plaintext: attrs.is_encrypted ? attrs.message : undefined
            }));
            _context13.next = 15;
            break;
          case 11:
            _this15.setEditable(attrs, new Date().toISOString());
            _context13.next = 14;
            return _this15.createMessage(attrs);
          case 14:
            message = _context13.sent;
          case 15:
            _context13.prev = 15;
            _context13.next = 18;
            return _this15.createMessageStanza(message);
          case 18:
            stanza = _context13.sent;
            shared_api.send(stanza);
            _context13.next = 27;
            break;
          case 22:
            _context13.prev = 22;
            _context13.t0 = _context13["catch"](15);
            message.destroy();
            log.error(_context13.t0);
            return _context13.abrupt("return");
          case 27:
            /**
             * Triggered when a message is being sent out
             * @event _converse#sendMessage
             * @type { Object }
             * @param { Object } data
             * @property { (_converse.ChatBox | _converse.ChatRoom) } data.chatbox
             * @property { (_converse.Message | _converse.ChatRoomMessage) } data.message
             */
            shared_api.trigger('sendMessage', {
              'chatbox': _this15,
              message: message
            });
            return _context13.abrupt("return", message);
          case 29:
          case "end":
            return _context13.stop();
        }
      }, _callee13, null, [[15, 22]]);
    }))();
  },
  /**
   * Sends a message with the current XEP-0085 chat state of the user
   * as taken from the `chat_state` attribute of the {@link _converse.ChatBox}.
   * @private
   * @method _converse.ChatBox#sendChatState
   */
  sendChatState: function sendChatState() {
    if (shared_api.settings.get('send_chat_state_notifications') && this.get('chat_state')) {
      var allowed = shared_api.settings.get('send_chat_state_notifications');
      if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
        return;
      }
      shared_api.send($msg({
        'id': model_u.getUniqueId(),
        'to': this.get('jid'),
        'type': 'chat'
      }).c(this.get('chat_state'), {
        'xmlns': model_Strophe.NS.CHATSTATES
      }).up().c('no-store', {
        'xmlns': model_Strophe.NS.HINTS
      }).up().c('no-permanent-store', {
        'xmlns': model_Strophe.NS.HINTS
      }));
    }
  },
  sendFiles: function sendFiles(files) {
    var _this16 = this;
    return model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee15() {
      var _maxFileSize;
      var __, result, item, data, max_file_size, slot_request_url;
      return model_regeneratorRuntime().wrap(function _callee15$(_context15) {
        while (1) switch (_context15.prev = _context15.next) {
          case 0:
            __ = shared_converse.__;
            _context15.next = 3;
            return shared_api.disco.features.get(model_Strophe.NS.HTTPUPLOAD, shared_converse.domain);
          case 3:
            result = _context15.sent;
            item = result.pop();
            if (item) {
              _context15.next = 8;
              break;
            }
            _this16.createMessage({
              'message': __("Sorry, looks like file upload is not supported by your server."),
              'type': 'error',
              'is_ephemeral': true
            });
            return _context15.abrupt("return");
          case 8:
            data = item.dataforms.where({
              'FORM_TYPE': {
                'value': model_Strophe.NS.HTTPUPLOAD,
                'type': "hidden"
              }
            }).pop();
            max_file_size = window.parseInt((_maxFileSize = ((data === null || data === void 0 ? void 0 : data.attributes) || {})['max-file-size']) === null || _maxFileSize === void 0 ? void 0 : _maxFileSize.value);
            slot_request_url = item === null || item === void 0 ? void 0 : item.id;
            if (slot_request_url) {
              _context15.next = 14;
              break;
            }
            _this16.createMessage({
              'message': __("Sorry, looks like file upload is not supported by your server."),
              'type': 'error',
              'is_ephemeral': true
            });
            return _context15.abrupt("return");
          case 14:
            Array.from(files).forEach( /*#__PURE__*/function () {
              var _ref2 = model_asyncToGenerator( /*#__PURE__*/model_regeneratorRuntime().mark(function _callee14(file) {
                var initial_attrs, attrs, message;
                return model_regeneratorRuntime().wrap(function _callee14$(_context14) {
                  while (1) switch (_context14.prev = _context14.next) {
                    case 0:
                      _context14.next = 2;
                      return shared_api.hook('beforeFileUpload', _this16, file);
                    case 2:
                      file = _context14.sent;
                      if (!(!window.isNaN(max_file_size) && window.parseInt(file.size) > max_file_size)) {
                        _context14.next = 7;
                        break;
                      }
                      return _context14.abrupt("return", _this16.createMessage({
                        'message': __('The size of your file, %1$s, exceeds the maximum allowed by your server, which is %2$s.', file.name, (0,external_filesize_namespaceObject.filesize)(max_file_size)),
                        'type': 'error',
                        'is_ephemeral': true
                      }));
                    case 7:
                      _context14.next = 9;
                      return _this16.getOutgoingMessageAttributes();
                    case 9:
                      initial_attrs = _context14.sent;
                      attrs = Object.assign(initial_attrs, {
                        'file': true,
                        'progress': 0,
                        'slot_request_url': slot_request_url
                      });
                      _this16.setEditable(attrs, new Date().toISOString());
                      _context14.next = 14;
                      return _this16.createMessage(attrs, {
                        'silent': true
                      });
                    case 14:
                      message = _context14.sent;
                      message.file = file;
                      _this16.messages.trigger('add', message);
                      message.getRequestSlotURL();
                    case 18:
                    case "end":
                      return _context14.stop();
                  }
                }, _callee14);
              }));
              return function (_x) {
                return _ref2.apply(this, arguments);
              };
            }());
          case 15:
          case "end":
            return _context15.stop();
        }
      }, _callee15);
    }))();
  },
  maybeShow: function maybeShow(force) {
    var _this17 = this;
    if (isUniView()) {
      var filter = function filter(c) {
        return !c.get('hidden') && c.get('jid') !== _this17.get('jid') && c.get('id') !== 'controlbox';
      };
      var other_chats = shared_converse.chatboxes.filter(filter);
      if (force || other_chats.length === 0) {
        // We only have one chat visible at any one time.
        // So before opening a chat, we make sure all other chats are hidden.
        other_chats.forEach(function (c) {
          return model_u.safeSave(c, {
            'hidden': true
          });
        });
        model_u.safeSave(this, {
          'hidden': false
        });
      }
      return;
    }
    model_u.safeSave(this, {
      'hidden': false
    });
    this.trigger('show');
    return this;
  },
  /**
   * Indicates whether the chat is hidden and therefore
   * whether a newly received message will be visible
   * to the user or not.
   * @returns {boolean}
   */
  isHidden: function isHidden() {
    // Note: This methods gets overridden by converse-minimize
    return this.get('hidden') || this.isScrolledUp() || shared_converse.windowState === 'hidden';
  },
  /**
   * Given a newly received {@link _converse.Message} instance,
   * update the unread counter if necessary.
   * @private
   * @method _converse.ChatBox#handleUnreadMessage
   * @param {_converse.Message} message
   */
  handleUnreadMessage: function handleUnreadMessage(message) {
    if (!(message !== null && message !== void 0 && message.get('body'))) {
      return;
    }
    if (model_u.isNewMessage(message)) {
      if (message.get('sender') === 'me') {
        // We remove the "scrolled" flag so that the chat area
        // gets scrolled down. We always want to scroll down
        // when the user writes a message as opposed to when a
        // message is received.
        this.ui.set('scrolled', false);
      } else if (this.isHidden()) {
        this.incrementUnreadMsgsCounter(message);
      } else {
        this.sendMarkerForMessage(message);
      }
    }
  },
  incrementUnreadMsgsCounter: function incrementUnreadMsgsCounter(message) {
    var settings = {
      'num_unread': this.get('num_unread') + 1
    };
    if (this.get('num_unread') === 0) {
      settings['first_unread_id'] = message.get('id');
    }
    this.save(settings);
  },
  clearUnreadMsgCounter: function clearUnreadMsgCounter() {
    if (this.get('num_unread') > 0) {
      this.sendMarkerForMessage(this.messages.last());
    }
    model_u.safeSave(this, {
      'num_unread': 0
    });
  },
  isScrolledUp: function isScrolledUp() {
    return this.ui.get('scrolled');
  }
});
/* harmony default export */ const model = (ChatBox);
;// CONCATENATED MODULE: ./src/headless/plugins/chat/message.js
function message_typeof(obj) {
  "@babel/helpers - typeof";

  return message_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;
  }, message_typeof(obj);
}
function message_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  message_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" == message_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 message_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 message_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        message_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        message_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var message_converse$env = public_converse.env,
  message_Strophe = message_converse$env.Strophe,
  message_sizzle = message_converse$env.sizzle,
  message_u = message_converse$env.u;

/**
 * Mixin which turns a `ModelWithContact` model into a non-MUC message.
 * These can be either `chat`, `normal` or `headline` messages.
 * @mixin
 * @namespace _converse.Message
 * @memberOf _converse
 * @example const msg = new _converse.Message({'message': 'hello world!'});
 */
var MessageMixin = {
  defaults: function defaults() {
    return {
      'msgid': message_u.getUniqueId(),
      'time': new Date().toISOString(),
      'is_ephemeral': false
    };
  },
  initialize: function initialize() {
    var _this = this;
    return message_asyncToGenerator( /*#__PURE__*/message_regeneratorRuntime().mark(function _callee() {
      return message_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (_this.checkValidity()) {
              _context.next = 2;
              break;
            }
            return _context.abrupt("return");
          case 2:
            _this.initialized = getOpenPromise();
            if (_this.get('file')) {
              _this.on('change:put', function () {
                return _this.uploadFile();
              });
            }
            // If `type` changes from `error` to `chat`, we want to set the contact. See #2733
            _this.on('change:type', function () {
              return _this.setContact();
            });
            _this.on('change:is_ephemeral', function () {
              return _this.setTimerForEphemeralMessage();
            });
            _context.next = 8;
            return _this.setContact();
          case 8:
            _this.setTimerForEphemeralMessage();
            /**
             * Triggered once a {@link _converse.Message} has been created and initialized.
             * @event _converse#messageInitialized
             * @type { _converse.Message}
             * @example _converse.api.listen.on('messageInitialized', model => { ... });
             */
            _context.next = 11;
            return shared_api.trigger('messageInitialized', _this, {
              'Synchronous': true
            });
          case 11:
            _this.initialized.resolve();
          case 12:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  setContact: function setContact() {
    if (['chat', 'normal'].includes(this.get('type'))) {
      model_with_contact.prototype.initialize.apply(this, arguments);
      this.setRosterContact(message_Strophe.getBareJidFromJid(this.get('from')));
    }
  },
  /**
   * Sets an auto-destruct timer for this message, if it's is_ephemeral.
   * @private
   * @method _converse.Message#setTimerForEphemeralMessage
   */
  setTimerForEphemeralMessage: function setTimerForEphemeralMessage() {
    var _this2 = this;
    if (this.ephemeral_timer) {
      clearTimeout(this.ephemeral_timer);
    }
    var is_ephemeral = this.isEphemeral();
    if (is_ephemeral) {
      var timeout = typeof is_ephemeral === "number" ? is_ephemeral : 10000;
      this.ephemeral_timer = window.setTimeout(function () {
        return _this2.safeDestroy();
      }, timeout);
    }
  },
  checkValidity: function checkValidity() {
    if (Object.keys(this.attributes).length === 3) {
      // XXX: This is an empty message with only the 3 default values.
      // This seems to happen when saving a newly created message
      // fails for some reason.
      // TODO: This is likely fixable by setting `wait` when
      // creating messages. See the wait-for-messages branch.
      this.validationError = 'Empty message';
      this.safeDestroy();
      return false;
    }
    return true;
  },
  /**
   * Determines whether this messsage may be retracted by the current user.
   * @private
   * @method _converse.Messages#mayBeRetracted
   * @returns { Boolean }
   */
  mayBeRetracted: function mayBeRetracted() {
    var is_own_message = this.get('sender') === 'me';
    var not_canceled = this.get('error_type') !== 'cancel';
    return is_own_message && not_canceled && ['all', 'own'].includes(shared_api.settings.get('allow_message_retraction'));
  },
  safeDestroy: function safeDestroy() {
    try {
      this.destroy();
    } catch (e) {
      log.warn("safeDestroy: ".concat(e));
    }
  },
  /**
   * Returns a boolean indicating whether this message is ephemeral,
   * meaning it will get automatically removed after ten seconds.
   * @returns { boolean }
   */
  isEphemeral: function isEphemeral() {
    return this.get('is_ephemeral');
  },
  /**
   * Returns a boolean indicating whether this message is a XEP-0245 /me command.
   * @returns { boolean }
   */
  isMeCommand: function isMeCommand() {
    var text = this.getMessageText();
    if (!text) {
      return false;
    }
    return text.startsWith('/me ');
  },
  /**
   * Returns a boolean indicating whether this message is considered a followup
   * message from the previous one. Followup messages are shown grouped together
   * under one author heading.
   * A message is considered a followup of it's predecessor when it's a chat
   * message from the same author, within 10 minutes.
   * @returns { boolean }
   */
  isFollowup: function isFollowup() {
    var messages = this.collection.models;
    var idx = messages.indexOf(this);
    var prev_model = idx ? messages[idx - 1] : null;
    if (prev_model === null) {
      return false;
    }
    var date = dayjs_min_default()(this.get('time'));
    return this.get('from') === prev_model.get('from') && !this.isMeCommand() && !prev_model.isMeCommand() && !!this.get('is_encrypted') === !!prev_model.get('is_encrypted') && this.get('type') === prev_model.get('type') && this.get('type') !== 'info' && date.isBefore(dayjs_min_default()(prev_model.get('time')).add(10, 'minutes')) && (this.get('type') === 'groupchat' ? this.get('occupant_id') === prev_model.get('occupant_id') : true);
  },
  getDisplayName: function getDisplayName() {
    if (this.contact) {
      return this.contact.getDisplayName();
    } else if (this.vcard) {
      return this.vcard.getDisplayName();
    } else {
      return this.get('from');
    }
  },
  getMessageText: function getMessageText() {
    if (this.get('is_encrypted')) {
      var __ = shared_converse.__;
      return this.get('plaintext') || this.get('body') || __('Undecryptable OMEMO message');
    } else if (['groupchat', 'chat', 'normal'].includes(this.get('type'))) {
      return this.get('body');
    } else {
      return this.get('message');
    }
  },
  /**
   * Send out an IQ stanza to request a file upload slot.
   * https://xmpp.org/extensions/xep-0363.html#request
   * @private
   * @method _converse.Message#sendSlotRequestStanza
   */
  sendSlotRequestStanza: function sendSlotRequestStanza() {
    if (!this.file) {
      return Promise.reject(new Error('file is undefined'));
    }
    var iq = public_converse.env.$iq({
      'from': shared_converse.jid,
      'to': this.get('slot_request_url'),
      'type': 'get'
    }).c('request', {
      'xmlns': message_Strophe.NS.HTTPUPLOAD,
      'filename': this.file.name,
      'size': this.file.size,
      'content-type': this.file.type
    });
    return shared_api.sendIQ(iq);
  },
  getUploadRequestMetadata: function getUploadRequestMetadata(stanza) {
    var headers = message_sizzle("slot[xmlns=\"".concat(message_Strophe.NS.HTTPUPLOAD, "\"] put header"), stanza);
    // https://xmpp.org/extensions/xep-0363.html#request
    // TODO: Can't set the Cookie header in JavaScipt, instead cookies need
    // to be manually set via document.cookie, so we're leaving it out here.
    return {
      'headers': headers.map(function (h) {
        return {
          'name': h.getAttribute('name'),
          'value': h.textContent
        };
      }).filter(function (h) {
        return ['Authorization', 'Expires'].includes(h.name);
      })
    };
  },
  getRequestSlotURL: function getRequestSlotURL() {
    var _this3 = this;
    return message_asyncToGenerator( /*#__PURE__*/message_regeneratorRuntime().mark(function _callee2() {
      var __, stanza, slot;
      return message_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            __ = shared_converse.__;
            _context2.prev = 1;
            _context2.next = 4;
            return _this3.sendSlotRequestStanza();
          case 4:
            stanza = _context2.sent;
            _context2.next = 11;
            break;
          case 7:
            _context2.prev = 7;
            _context2.t0 = _context2["catch"](1);
            log.error(_context2.t0);
            return _context2.abrupt("return", _this3.save({
              'type': 'error',
              'message': __('Sorry, could not determine upload URL.'),
              'is_ephemeral': true
            }));
          case 11:
            slot = message_sizzle("slot[xmlns=\"".concat(message_Strophe.NS.HTTPUPLOAD, "\"]"), stanza).pop();
            if (!slot) {
              _context2.next = 17;
              break;
            }
            _this3.upload_metadata = _this3.getUploadRequestMetadata(stanza);
            _this3.save({
              'get': slot.querySelector('get').getAttribute('url'),
              'put': slot.querySelector('put').getAttribute('url')
            });
            _context2.next = 18;
            break;
          case 17:
            return _context2.abrupt("return", _this3.save({
              'type': 'error',
              'message': __('Sorry, could not determine file upload URL.'),
              'is_ephemeral': true
            }));
          case 18:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[1, 7]]);
    }))();
  },
  uploadFile: function uploadFile() {
    var _this4 = this,
      _this$upload_metadata;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = /*#__PURE__*/message_asyncToGenerator( /*#__PURE__*/message_regeneratorRuntime().mark(function _callee3() {
      var attrs;
      return message_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            if (!(xhr.readyState === XMLHttpRequest.DONE)) {
              _context3.next = 11;
              break;
            }
            log.info('Status: ' + xhr.status);
            if (!(xhr.status === 200 || xhr.status === 201)) {
              _context3.next = 10;
              break;
            }
            attrs = {
              'upload': shared_converse.SUCCESS,
              'oob_url': _this4.get('get'),
              'message': _this4.get('get'),
              'body': _this4.get('get')
            };
            /**
             * *Hook* which allows plugins to change the attributes
             * saved on the message once a file has been uploaded.
             * @event _converse#afterFileUploaded
             */
            _context3.next = 6;
            return shared_api.hook('afterFileUploaded', _this4, attrs);
          case 6:
            attrs = _context3.sent;
            _this4.save(attrs);
            _context3.next = 11;
            break;
          case 10:
            xhr.onerror();
          case 11:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    xhr.upload.addEventListener('progress', function (evt) {
      if (evt.lengthComputable) {
        _this4.set('progress', evt.loaded / evt.total);
      }
    }, false);
    xhr.onerror = function () {
      var __ = shared_converse.__;
      var message;
      if (xhr.responseText) {
        message = __('Sorry, could not succesfully upload your file. Your server’s response: "%1$s"', xhr.responseText);
      } else {
        message = __('Sorry, could not succesfully upload your file.');
      }
      _this4.save({
        'type': 'error',
        'upload': shared_converse.FAILURE,
        'message': message,
        'is_ephemeral': true
      });
    };
    xhr.open('PUT', this.get('put'), true);
    xhr.setRequestHeader('Content-type', this.file.type);
    (_this$upload_metadata = this.upload_metadata.headers) === null || _this$upload_metadata === void 0 ? void 0 : _this$upload_metadata.forEach(function (h) {
      return xhr.setRequestHeader(h.name, h.value);
    });
    xhr.send(this.file);
  }
};
/* harmony default export */ const message = (MessageMixin);
;// CONCATENATED MODULE: ./src/headless/plugins/chat/api.js
function chat_api_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_api_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;
  }, chat_api_typeof(obj);
}
function chat_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chat_api_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" == chat_api_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 chat_api_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 chat_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chat_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chat_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


/* harmony default export */ const chat_api = ({
  /**
   * The "chats" namespace (used for one-on-one chats)
   *
   * @namespace api.chats
   * @memberOf api
   */
  chats: {
    /**
     * @method api.chats.create
     * @param {string|string[]} jid|jids An jid or array of jids
     * @param { object } [attrs] An object containing configuration attributes.
     */
    create: function create(jids, attrs) {
      return chat_api_asyncToGenerator( /*#__PURE__*/chat_api_regeneratorRuntime().mark(function _callee2() {
        var _contact$attributes, contact, chatbox;
        return chat_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (!(typeof jids === 'string')) {
                _context2.next = 11;
                break;
              }
              if (!(attrs && !(attrs !== null && attrs !== void 0 && attrs.fullname))) {
                _context2.next = 6;
                break;
              }
              _context2.next = 4;
              return shared_api.contacts.get(jids);
            case 4:
              contact = _context2.sent;
              attrs.fullname = contact === null || contact === void 0 ? void 0 : (_contact$attributes = contact.attributes) === null || _contact$attributes === void 0 ? void 0 : _contact$attributes.fullname;
            case 6:
              chatbox = shared_api.chats.get(jids, attrs, true);
              if (chatbox) {
                _context2.next = 10;
                break;
              }
              log.error("Could not open chatbox for JID: " + jids);
              return _context2.abrupt("return");
            case 10:
              return _context2.abrupt("return", chatbox);
            case 11:
              if (!Array.isArray(jids)) {
                _context2.next = 13;
                break;
              }
              return _context2.abrupt("return", Promise.all(jids.forEach( /*#__PURE__*/function () {
                var _ref = chat_api_asyncToGenerator( /*#__PURE__*/chat_api_regeneratorRuntime().mark(function _callee(jid) {
                  var _contact$attributes2;
                  var contact;
                  return chat_api_regeneratorRuntime().wrap(function _callee$(_context) {
                    while (1) switch (_context.prev = _context.next) {
                      case 0:
                        _context.next = 2;
                        return shared_api.contacts.get(jids);
                      case 2:
                        contact = _context.sent;
                        attrs.fullname = contact === null || contact === void 0 ? void 0 : (_contact$attributes2 = contact.attributes) === null || _contact$attributes2 === void 0 ? void 0 : _contact$attributes2.fullname;
                        return _context.abrupt("return", shared_api.chats.get(jid, attrs, true).maybeShow());
                      case 5:
                      case "end":
                        return _context.stop();
                    }
                  }, _callee);
                }));
                return function (_x) {
                  return _ref.apply(this, arguments);
                };
              }())));
            case 13:
              log.error("chats.create: You need to provide at least one JID");
              return _context2.abrupt("return", null);
            case 15:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    },
    /**
     * Opens a new one-on-one chat.
     *
     * @method api.chats.open
     * @param {String|string[]} name - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
     * @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
     * @param { Boolean } [attrs.minimized] - Should the chat be created in minimized state.
     * @param { Boolean } [force=false] - By default, a minimized
     *   chat won't be maximized (in `overlayed` view mode) and in
     *   `fullscreen` view mode a newly opened chat won't replace
     *   another chat already in the foreground.
     *   Set `force` to `true` if you want to force the chat to be
     *   maximized or shown.
     * @returns {Promise} Promise which resolves with the
     *   _converse.ChatBox representing the chat.
     *
     * @example
     * // To open a single chat, provide the JID of the contact you're chatting with in that chat:
     * converse.plugins.add('myplugin', {
     *     initialize: function() {
     *         const _converse = this._converse;
     *         // Note, buddy@example.org must be in your contacts roster!
     *         api.chats.open('buddy@example.com').then(chat => {
     *             // Now you can do something with the chat model
     *         });
     *     }
     * });
     *
     * @example
     * // To open an array of chats, provide an array of JIDs:
     * converse.plugins.add('myplugin', {
     *     initialize: function () {
     *         const _converse = this._converse;
     *         // Note, these users must first be in your contacts roster!
     *         api.chats.open(['buddy1@example.com', 'buddy2@example.com']).then(chats => {
     *             // Now you can do something with the chat models
     *         });
     *     }
     * });
     */
    open: function open(jids, attrs, force) {
      return chat_api_asyncToGenerator( /*#__PURE__*/chat_api_regeneratorRuntime().mark(function _callee3() {
        var chat, err_msg;
        return chat_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (!(typeof jids === 'string')) {
                _context3.next = 9;
                break;
              }
              _context3.next = 3;
              return shared_api.chats.get(jids, attrs, true);
            case 3:
              chat = _context3.sent;
              if (!chat) {
                _context3.next = 6;
                break;
              }
              return _context3.abrupt("return", chat.maybeShow(force));
            case 6:
              return _context3.abrupt("return", chat);
            case 9:
              if (!Array.isArray(jids)) {
                _context3.next = 11;
                break;
              }
              return _context3.abrupt("return", Promise.all(jids.map(function (j) {
                return shared_api.chats.get(j, attrs, true).then(function (c) {
                  return c && c.maybeShow(force);
                });
              }).filter(function (c) {
                return c;
              })));
            case 11:
              err_msg = "chats.open: You need to provide at least one JID";
              log.error(err_msg);
              throw new Error(err_msg);
            case 14:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }))();
    },
    /**
     * Retrieves a chat or all chats.
     *
     * @method api.chats.get
     * @param {String|string[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
     * @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
     * @param { Boolean } [create=false] - Whether the chat should be created if it's not found.
     * @returns { Promise<_converse.ChatBox> }
     *
     * @example
     * // To return a single chat, provide the JID of the contact you're chatting with in that chat:
     * const model = await api.chats.get('buddy@example.com');
     *
     * @example
     * // To return an array of chats, provide an array of JIDs:
     * const models = await api.chats.get(['buddy1@example.com', 'buddy2@example.com']);
     *
     * @example
     * // To return all open chats, call the method without any parameters::
     * const models = await api.chats.get();
     *
     */
    get: function get(jids) {
      var _arguments = arguments;
      return chat_api_asyncToGenerator( /*#__PURE__*/chat_api_regeneratorRuntime().mark(function _callee5() {
        var attrs, create, _get, _get2, chats;
        return chat_api_regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              _get2 = function _get4() {
                _get2 = chat_api_asyncToGenerator( /*#__PURE__*/chat_api_regeneratorRuntime().mark(function _callee4(jid) {
                  var model;
                  return chat_api_regeneratorRuntime().wrap(function _callee4$(_context4) {
                    while (1) switch (_context4.prev = _context4.next) {
                      case 0:
                        _context4.next = 2;
                        return shared_api.chatboxes.get(jid);
                      case 2:
                        model = _context4.sent;
                        if (!(!model && create)) {
                          _context4.next = 9;
                          break;
                        }
                        _context4.next = 6;
                        return shared_api.chatboxes.create(jid, attrs, shared_converse.ChatBox);
                      case 6:
                        model = _context4.sent;
                        _context4.next = 11;
                        break;
                      case 9:
                        model = model && model.get('type') === shared_converse.PRIVATE_CHAT_TYPE ? model : null;
                        if (model && Object.keys(attrs).length) {
                          model.save(attrs);
                        }
                      case 11:
                        return _context4.abrupt("return", model);
                      case 12:
                      case "end":
                        return _context4.stop();
                    }
                  }, _callee4);
                }));
                return _get2.apply(this, arguments);
              };
              _get = function _get3(_x2) {
                return _get2.apply(this, arguments);
              };
              attrs = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
              create = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : false;
              _context5.next = 6;
              return shared_api.waitUntil('chatBoxesFetched');
            case 6:
              if (!(jids === undefined)) {
                _context5.next = 13;
                break;
              }
              _context5.next = 9;
              return shared_api.chatboxes.get();
            case 9:
              chats = _context5.sent;
              return _context5.abrupt("return", chats.filter(function (c) {
                return c.get('type') === shared_converse.PRIVATE_CHAT_TYPE;
              }));
            case 13:
              if (!(typeof jids === 'string')) {
                _context5.next = 15;
                break;
              }
              return _context5.abrupt("return", _get(jids));
            case 15:
              return _context5.abrupt("return", Promise.all(jids.map(function (jid) {
                return _get(jid);
              })));
            case 16:
            case "end":
              return _context5.stop();
          }
        }, _callee5);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/chat/utils.js
function plugins_chat_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return plugins_chat_utils_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;
  }, plugins_chat_utils_typeof(obj);
}
function plugins_chat_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  plugins_chat_utils_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" == plugins_chat_utils_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 plugins_chat_utils_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 plugins_chat_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        plugins_chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        plugins_chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var utils_converse$env = public_converse.env,
  utils_Strophe = utils_converse$env.Strophe,
  chat_utils_u = utils_converse$env.u;
function openChat(jid) {
  if (!chat_utils_u.isValidJID(jid)) {
    return log.warn("Invalid JID \"".concat(jid, "\" provided in URL fragment"));
  }
  shared_api.chats.open(jid);
}
function onClearSession() {
  return _onClearSession.apply(this, arguments);
}
function _onClearSession() {
  _onClearSession = plugins_chat_utils_asyncToGenerator( /*#__PURE__*/plugins_chat_utils_regeneratorRuntime().mark(function _callee() {
    var filter;
    return plugins_chat_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!shouldClearCache()) {
            _context.next = 5;
            break;
          }
          _context.next = 3;
          return Promise.all(shared_converse.chatboxes.map(function (c) {
            return c.messages && c.messages.clearStore({
              'silent': true
            });
          }));
        case 3:
          filter = function filter(o) {
            return o.get('type') !== shared_converse.CONTROLBOX_TYPE;
          };
          shared_converse.chatboxes.clearStore({
            'silent': true
          }, filter);
        case 5:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _onClearSession.apply(this, arguments);
}
function handleErrorMessage(_x) {
  return _handleErrorMessage.apply(this, arguments);
}
function _handleErrorMessage() {
  _handleErrorMessage = plugins_chat_utils_asyncToGenerator( /*#__PURE__*/plugins_chat_utils_regeneratorRuntime().mark(function _callee2(stanza) {
    var from_jid, chatbox;
    return plugins_chat_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          from_jid = utils_Strophe.getBareJidFromJid(stanza.getAttribute('from'));
          if (!chat_utils_u.isSameBareJID(from_jid, shared_converse.bare_jid)) {
            _context2.next = 3;
            break;
          }
          return _context2.abrupt("return");
        case 3:
          _context2.next = 5;
          return shared_api.chatboxes.get(from_jid);
        case 5:
          chatbox = _context2.sent;
          if ((chatbox === null || chatbox === void 0 ? void 0 : chatbox.get('type')) === shared_converse.PRIVATE_CHAT_TYPE) {
            chatbox === null || chatbox === void 0 ? void 0 : chatbox.handleErrorMessageStanza(stanza);
          }
        case 7:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _handleErrorMessage.apply(this, arguments);
}
function autoJoinChats() {
  // Automatically join private chats, based on the
  // "auto_join_private_chats" configuration setting.
  shared_api.settings.get('auto_join_private_chats').forEach(function (jid) {
    if (shared_converse.chatboxes.where({
      'jid': jid
    }).length) {
      return;
    }
    if (typeof jid === 'string') {
      shared_api.chats.open(jid);
    } else {
      log.error('Invalid jid criteria specified for "auto_join_private_chats"');
    }
  });
  /**
   * Triggered once any private chats have been automatically joined as
   * specified by the `auto_join_private_chats` setting.
   * See: https://conversejs.org/docs/html/configuration.html#auto-join-private-chats
   * @event _converse#privateChatsAutoJoined
   * @example _converse.api.listen.on('privateChatsAutoJoined', () => { ... });
   * @example _converse.api.waitUntil('privateChatsAutoJoined').then(() => { ... });
   */
  shared_api.trigger('privateChatsAutoJoined');
}
function registerMessageHandlers() {
  shared_converse.connection.addHandler(function (stanza) {
    if (['groupchat', 'error'].includes(stanza.getAttribute('type')) || isHeadline(stanza) || isServerMessage(stanza) || isArchived(stanza)) {
      return true;
    }
    return shared_converse.handleMessageStanza(stanza) || true;
  }, null, 'message');
  shared_converse.connection.addHandler(function (stanza) {
    return handleErrorMessage(stanza) || true;
  }, null, 'message', 'error');
}

/**
 * Handler method for all incoming single-user chat "message" stanzas.
 * @param { MessageAttributes } attrs - The message attributes
 */
function handleMessageStanza(_x2) {
  return _handleMessageStanza.apply(this, arguments);
}

/**
 * Ask the XMPP server to enable Message Carbons
 * See [XEP-0280](https://xmpp.org/extensions/xep-0280.html#enabling)
 * @param { Boolean } reconnecting
 */
function _handleMessageStanza() {
  _handleMessageStanza = plugins_chat_utils_asyncToGenerator( /*#__PURE__*/plugins_chat_utils_regeneratorRuntime().mark(function _callee3(stanza) {
    var _stanza$tree, _stanza$tree2, _stanza;
    var from, attrs, has_body, chatbox, data;
    return plugins_chat_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          stanza = (_stanza$tree = (_stanza$tree2 = (_stanza = stanza).tree) === null || _stanza$tree2 === void 0 ? void 0 : _stanza$tree2.call(_stanza)) !== null && _stanza$tree !== void 0 ? _stanza$tree : stanza;
          if (!isServerMessage(stanza)) {
            _context3.next = 4;
            break;
          }
          // Prosody sends headline messages with type `chat`, so we need to filter them out here.
          from = stanza.getAttribute('from');
          return _context3.abrupt("return", log.info("handleMessageStanza: Ignoring incoming server message from JID: ".concat(from)));
        case 4:
          _context3.prev = 4;
          _context3.next = 7;
          return parseMessage(stanza);
        case 7:
          attrs = _context3.sent;
          _context3.next = 13;
          break;
        case 10:
          _context3.prev = 10;
          _context3.t0 = _context3["catch"](4);
          return _context3.abrupt("return", log.error(_context3.t0));
        case 13:
          if (!chat_utils_u.isErrorObject(attrs)) {
            _context3.next = 16;
            break;
          }
          attrs.stanza && log.error(attrs.stanza);
          return _context3.abrupt("return", log.error(attrs.message));
        case 16:
          // XXX: Need to take XEP-428 <fallback> into consideration
          has_body = !!(attrs.body || attrs.plaintext);
          _context3.next = 19;
          return shared_api.chats.get(attrs.contact_jid, {
            'nickname': attrs.nick
          }, has_body);
        case 19:
          chatbox = _context3.sent;
          _context3.next = 22;
          return chatbox === null || chatbox === void 0 ? void 0 : chatbox.queueMessage(attrs);
        case 22:
          /**
           * @typedef { Object } MessageData
           * An object containing the original message stanza, as well as the
           * parsed attributes.
           * @property { Element } stanza
           * @property { MessageAttributes } stanza
           * @property { ChatBox } chatbox
           */
          data = {
            stanza: stanza,
            attrs: attrs,
            chatbox: chatbox
          };
          /**
           * Triggered when a message stanza is been received and processed.
           * @event _converse#message
           * @type { object }
           * @property { module:converse-chat~MessageData } data
           */
          shared_api.trigger('message', data);
        case 24:
        case "end":
          return _context3.stop();
      }
    }, _callee3, null, [[4, 10]]);
  }));
  return _handleMessageStanza.apply(this, arguments);
}
function enableCarbons() {
  return _enableCarbons.apply(this, arguments);
}
function _enableCarbons() {
  _enableCarbons = plugins_chat_utils_asyncToGenerator( /*#__PURE__*/plugins_chat_utils_regeneratorRuntime().mark(function _callee4() {
    var domain, supported, iq, result;
    return plugins_chat_utils_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          domain = utils_Strophe.getDomainFromJid(shared_converse.bare_jid);
          _context4.next = 3;
          return shared_api.disco.supports(utils_Strophe.NS.CARBONS, domain);
        case 3:
          supported = _context4.sent;
          if (supported) {
            _context4.next = 7;
            break;
          }
          log.warn("Not enabling carbons because it's not supported!");
          return _context4.abrupt("return");
        case 7:
          iq = new utils_Strophe.Builder('iq', {
            'from': shared_converse.connection.jid,
            'type': 'set'
          }).c('enable', {
            xmlns: utils_Strophe.NS.CARBONS
          });
          _context4.next = 10;
          return shared_api.sendIQ(iq, null, false);
        case 10:
          result = _context4.sent;
          if (result === null) {
            log.warn("A timeout occurred while trying to enable carbons");
          } else if (chat_utils_u.isErrorStanza(result)) {
            log.warn('An error occurred while trying to enable message carbons.');
            log.error(result);
          } else {
            log.debug('Message carbons have been enabled.');
          }
        case 12:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _enableCarbons.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







public_converse.plugins.add('converse-chat', {
  dependencies: ['converse-chatboxes', 'converse-disco'],
  initialize: function initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'allow_message_corrections': 'all',
      'allow_message_retraction': 'all',
      'allow_message_styling': true,
      'auto_join_private_chats': [],
      'clear_messages_on_reconnection': false,
      'filter_by_resource': false,
      'prune_messages_above': undefined,
      'pruning_behavior': 'unscrolled',
      'send_chat_markers': ['received', 'displayed', 'acknowledged'],
      'send_chat_state_notifications': true
    });
    shared_converse.Message = model_with_contact.extend(message);
    shared_converse.Messages = Collection.extend({
      model: shared_converse.Message,
      comparator: 'time'
    });
    Object.assign(shared_converse, {
      ChatBox: model,
      handleMessageStanza: handleMessageStanza
    });
    Object.assign(shared_api, chat_api);
    shared_converse.router.route('converse/chat?jid=:jid', openChat);
    shared_api.listen.on('chatBoxesFetched', autoJoinChats);
    shared_api.listen.on('presencesInitialized', registerMessageHandlers);
    shared_api.listen.on('clearSession', onClearSession);
    shared_api.listen.on('connected', function () {
      return enableCarbons();
    });
    shared_api.listen.on('reconnected', function () {
      return enableCarbons();
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/disco/entity.js
function entity_typeof(obj) {
  "@babel/helpers - typeof";

  return entity_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;
  }, entity_typeof(obj);
}
function entity_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  entity_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" == entity_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 entity_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 entity_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        entity_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        entity_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var entity_Strophe = public_converse.env.Strophe;

/**
 * @class
 * @namespace _converse.DiscoEntity
 * @memberOf _converse
 *
 * A Disco Entity is a JID addressable entity that can be queried for features.
 *
 * See XEP-0030: https://xmpp.org/extensions/xep-0030.html
 */
var DiscoEntity = Model.extend({
  idAttribute: 'jid',
  initialize: function initialize(_, options) {
    this.waitUntilFeaturesDiscovered = getOpenPromise();
    this.dataforms = new Collection();
    var id = "converse.dataforms-".concat(this.get('jid'));
    this.dataforms.browserStorage = shared_converse.createStore(id, 'session');
    this.features = new Collection();
    id = "converse.features-".concat(this.get('jid'));
    this.features.browserStorage = shared_converse.createStore(id, 'session');
    this.listenTo(this.features, 'add', this.onFeatureAdded);
    this.fields = new Collection();
    id = "converse.fields-".concat(this.get('jid'));
    this.fields.browserStorage = shared_converse.createStore(id, 'session');
    this.listenTo(this.fields, 'add', this.onFieldAdded);
    this.identities = new Collection();
    id = "converse.identities-".concat(this.get('jid'));
    this.identities.browserStorage = shared_converse.createStore(id, 'session');
    this.fetchFeatures(options);
  },
  /**
   * Returns a Promise which resolves with a map indicating
   * whether a given identity is provided by this entity.
   * @private
   * @method _converse.DiscoEntity#getIdentity
   * @param { String } category - The identity category
   * @param { String } type - The identity type
   */
  getIdentity: function getIdentity(category, type) {
    var _this = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee() {
      return entity_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return _this.waitUntilFeaturesDiscovered;
          case 2:
            return _context.abrupt("return", _this.identities.findWhere({
              'category': category,
              'type': type
            }));
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * Returns a Promise which resolves with a map indicating
   * whether a given feature is supported.
   * @private
   * @method _converse.DiscoEntity#getFeature
   * @param { String } feature - The feature that might be supported.
   */
  getFeature: function getFeature(feature) {
    var _this2 = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee2() {
      return entity_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return _this2.waitUntilFeaturesDiscovered;
          case 2:
            if (!_this2.features.findWhere({
              'var': feature
            })) {
              _context2.next = 4;
              break;
            }
            return _context2.abrupt("return", _this2);
          case 4:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  onFeatureAdded: function onFeatureAdded(feature) {
    feature.entity = this;
    /**
     * Triggered when Converse has learned of a service provided by the XMPP server.
     * See XEP-0030.
     * @event _converse#serviceDiscovered
     * @type { Model }
     * @example _converse.api.listen.on('featuresDiscovered', feature => { ... });
     */
    shared_api.trigger('serviceDiscovered', feature);
  },
  onFieldAdded: function onFieldAdded(field) {
    field.entity = this;
    /**
     * Triggered when Converse has learned of a disco extension field.
     * See XEP-0030.
     * @event _converse#discoExtensionFieldDiscovered
     * @example _converse.api.listen.on('discoExtensionFieldDiscovered', () => { ... });
     */
    shared_api.trigger('discoExtensionFieldDiscovered', field);
  },
  fetchFeatures: function fetchFeatures(options) {
    var _this3 = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee3() {
      var store_id, result;
      return entity_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            if (!options.ignore_cache) {
              _context3.next = 4;
              break;
            }
            _this3.queryInfo();
            _context3.next = 9;
            break;
          case 4:
            store_id = _this3.features.browserStorage.name;
            _context3.next = 7;
            return _this3.features.browserStorage.store.getItem(store_id);
          case 7:
            result = _context3.sent;
            if (result && result.length === 0 || result === null) {
              _this3.queryInfo();
            } else {
              _this3.features.fetch({
                add: true,
                success: function success() {
                  _this3.waitUntilFeaturesDiscovered.resolve(_this3);
                  _this3.trigger('featuresDiscovered');
                }
              });
              _this3.identities.fetch({
                add: true
              });
            }
          case 9:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  },
  queryInfo: function queryInfo() {
    var _this4 = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee4() {
      var stanza;
      return entity_regeneratorRuntime().wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return shared_api.disco.info(_this4.get('jid'), null);
          case 3:
            stanza = _context4.sent;
            _context4.next = 11;
            break;
          case 6:
            _context4.prev = 6;
            _context4.t0 = _context4["catch"](0);
            _context4.t0 === null ? log.error("Timeout for disco#info query for ".concat(_this4.get('jid'))) : log.error(_context4.t0);
            _this4.waitUntilFeaturesDiscovered.resolve(_this4);
            return _context4.abrupt("return");
          case 11:
            _this4.onInfo(stanza);
          case 12:
          case "end":
            return _context4.stop();
        }
      }, _callee4, null, [[0, 6]]);
    }))();
  },
  onDiscoItems: function onDiscoItems(stanza) {
    var _this5 = this;
    external_sizzle_default()("query[xmlns=\"".concat(entity_Strophe.NS.DISCO_ITEMS, "\"] item"), stanza).forEach(function (item) {
      if (item.getAttribute('node')) {
        // XXX: Ignore nodes for now.
        // See: https://xmpp.org/extensions/xep-0030.html#items-nodes
        return;
      }
      var jid = item.getAttribute('jid');
      var entity = shared_converse.disco_entities.get(jid);
      if (entity) {
        entity.set({
          parent_jids: [_this5.get('jid')]
        });
      } else {
        shared_api.disco.entities.create({
          jid: jid,
          'parent_jids': [_this5.get('jid')],
          'name': item.getAttribute('name')
        });
      }
    });
  },
  queryForItems: function queryForItems() {
    var _this6 = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee5() {
      var stanza;
      return entity_regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            if (!(_this6.identities.where({
              'category': 'server'
            }).length === 0)) {
              _context5.next = 2;
              break;
            }
            return _context5.abrupt("return");
          case 2:
            _context5.next = 4;
            return shared_api.disco.items(_this6.get('jid'));
          case 4:
            stanza = _context5.sent;
            _this6.onDiscoItems(stanza);
          case 6:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    }))();
  },
  onInfo: function onInfo(stanza) {
    var _this7 = this;
    return entity_asyncToGenerator( /*#__PURE__*/entity_regeneratorRuntime().mark(function _callee6() {
      return entity_regeneratorRuntime().wrap(function _callee6$(_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            Array.from(stanza.querySelectorAll('identity')).forEach(function (identity) {
              _this7.identities.create({
                'category': identity.getAttribute('category'),
                'type': identity.getAttribute('type'),
                'name': identity.getAttribute('name')
              });
            });
            external_sizzle_default()("x[type=\"result\"][xmlns=\"".concat(entity_Strophe.NS.XFORM, "\"]"), stanza).forEach(function (form) {
              var data = {};
              external_sizzle_default()('field', form).forEach(function (field) {
                var _field$querySelector;
                data[field.getAttribute('var')] = {
                  'value': (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent,
                  'type': field.getAttribute('type')
                };
              });
              _this7.dataforms.create(data);
            });
            if (!stanza.querySelector("feature[var=\"".concat(entity_Strophe.NS.DISCO_ITEMS, "\"]"))) {
              _context6.next = 5;
              break;
            }
            _context6.next = 5;
            return _this7.queryForItems();
          case 5:
            Array.from(stanza.querySelectorAll('feature')).forEach(function (feature) {
              _this7.features.create({
                'var': feature.getAttribute('var'),
                'from': stanza.getAttribute('from')
              });
            });

            // XEP-0128 Service Discovery Extensions
            external_sizzle_default()('x[type="result"][xmlns="jabber:x:data"] field', stanza).forEach(function (field) {
              var _field$querySelector2;
              _this7.fields.create({
                'var': field.getAttribute('var'),
                'value': (_field$querySelector2 = field.querySelector('value')) === null || _field$querySelector2 === void 0 ? void 0 : _field$querySelector2.textContent,
                'from': stanza.getAttribute('from')
              });
            });
            _this7.waitUntilFeaturesDiscovered.resolve(_this7);
            _this7.trigger('featuresDiscovered');
          case 9:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    }))();
  }
});
/* harmony default export */ const entity = (DiscoEntity);
;// CONCATENATED MODULE: ./src/headless/plugins/disco/entities.js



var DiscoEntities = Collection.extend({
  model: entity,
  fetchEntities: function fetchEntities() {
    var _this = this;
    return new Promise(function (resolve, reject) {
      _this.fetch({
        add: true,
        success: resolve,
        error: function error(_m, e) {
          log.error(e);
          reject(new Error("Could not fetch disco entities"));
        }
      });
    });
  }
});
/* harmony default export */ const entities = (DiscoEntities);
;// CONCATENATED MODULE: ./src/headless/plugins/disco/utils.js
function disco_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return disco_utils_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;
  }, disco_utils_typeof(obj);
}
function disco_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  disco_utils_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" == disco_utils_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 disco_utils_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 disco_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        disco_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        disco_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var disco_utils_converse$env = public_converse.env,
  disco_utils_Strophe = disco_utils_converse$env.Strophe,
  $iq = disco_utils_converse$env.$iq;
function onDiscoInfoRequest(stanza) {
  var node = stanza.getElementsByTagName('query')[0].getAttribute('node');
  var attrs = {
    xmlns: disco_utils_Strophe.NS.DISCO_INFO
  };
  if (node) {
    attrs.node = node;
  }
  var iqresult = $iq({
    'type': 'result',
    'id': stanza.getAttribute('id')
  });
  var from = stanza.getAttribute('from');
  if (from !== null) {
    iqresult.attrs({
      'to': from
    });
  }
  iqresult.c('query', attrs);
  shared_converse.disco._identities.forEach(function (identity) {
    var attrs = {
      'category': identity.category,
      'type': identity.type
    };
    if (identity.name) {
      attrs.name = identity.name;
    }
    if (identity.lang) {
      attrs['xml:lang'] = identity.lang;
    }
    iqresult.c('identity', attrs).up();
  });
  shared_converse.disco._features.forEach(function (f) {
    return iqresult.c('feature', {
      'var': f
    }).up();
  });
  shared_api.send(iqresult.tree());
  return true;
}
function addClientFeatures() {
  // See https://xmpp.org/registrar/disco-categories.html
  shared_api.disco.own.identities.add('client', 'web', 'Converse');
  shared_api.disco.own.features.add(disco_utils_Strophe.NS.CHATSTATES);
  shared_api.disco.own.features.add(disco_utils_Strophe.NS.DISCO_INFO);
  shared_api.disco.own.features.add(disco_utils_Strophe.NS.ROSTERX); // Limited support
  shared_api.disco.own.features.add(disco_utils_Strophe.NS.CARBONS);
  /**
   * Triggered in converse-disco once the core disco features of
   * Converse have been added.
   * @event _converse#addClientFeatures
   * @example _converse.api.listen.on('addClientFeatures', () => { ... });
   */
  shared_api.trigger('addClientFeatures');
  return this;
}
function initializeDisco() {
  return _initializeDisco.apply(this, arguments);
}
function _initializeDisco() {
  _initializeDisco = disco_utils_asyncToGenerator( /*#__PURE__*/disco_utils_regeneratorRuntime().mark(function _callee() {
    var id, collection;
    return disco_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          addClientFeatures();
          shared_converse.connection.addHandler(function (stanza) {
            return onDiscoInfoRequest(stanza);
          }, disco_utils_Strophe.NS.DISCO_INFO, 'iq', 'get', null, null);
          shared_converse.disco_entities = new shared_converse.DiscoEntities();
          id = "converse.disco-entities-".concat(shared_converse.bare_jid);
          shared_converse.disco_entities.browserStorage = shared_converse.createStore(id, 'session');
          _context.next = 7;
          return shared_converse.disco_entities.fetchEntities();
        case 7:
          collection = _context.sent;
          if (collection.length === 0 || !collection.get(shared_converse.domain)) {
            // If we don't have an entity for our own XMPP server, create one.
            shared_api.disco.entities.create({
              'jid': shared_converse.domain
            }, {
              'ignore_cache': true
            });
          }
          /**
           * Triggered once the `converse-disco` plugin has been initialized and the
           * `_converse.disco_entities` collection will be available and populated with at
           * least the service discovery features of the user's own server.
           * @event _converse#discoInitialized
           * @example _converse.api.listen.on('discoInitialized', () => { ... });
           */
          shared_api.trigger('discoInitialized');
        case 10:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _initializeDisco.apply(this, arguments);
}
function initStreamFeatures() {
  // Initialize the stream_features collection, and if we're
  // re-attaching to a pre-existing BOSH session, we restore the
  // features from cache.
  // Otherwise the features will be created once we've received them
  // from the server (see populateStreamFeatures).
  if (!shared_converse.stream_features) {
    var bare_jid = disco_utils_Strophe.getBareJidFromJid(shared_converse.jid);
    var id = "converse.stream-features-".concat(bare_jid);
    shared_api.promises.add('streamFeaturesAdded');
    shared_converse.stream_features = new Collection();
    shared_converse.stream_features.browserStorage = shared_converse.createStore(id, "session");
  }
}
function notifyStreamFeaturesAdded() {
  /**
   * Triggered as soon as the stream features are known.
   * If you want to check whether a stream feature is supported before proceeding,
   * then you'll first want to wait for this event.
   * @event _converse#streamFeaturesAdded
   * @example _converse.api.listen.on('streamFeaturesAdded', () => { ... });
   */
  shared_api.trigger('streamFeaturesAdded');
}
function populateStreamFeatures() {
  // Strophe.js sets the <stream:features> element on the
  // Strophe.Connection instance (_converse.connection).
  //
  // Once this is we populate the _converse.stream_features collection
  // and trigger streamFeaturesAdded.
  initStreamFeatures();
  Array.from(shared_converse.connection.features.childNodes).forEach(function (feature) {
    shared_converse.stream_features.create({
      'name': feature.nodeName,
      'xmlns': feature.getAttribute('xmlns')
    });
  });
  notifyStreamFeaturesAdded();
}
function utils_clearSession() {
  var _converse$disco_entit, _converse$disco_entit2, _converse$disco_entit3, _converse$disco_entit4, _converse$disco_entit5;
  (_converse$disco_entit = shared_converse.disco_entities) === null || _converse$disco_entit === void 0 ? void 0 : _converse$disco_entit.forEach(function (e) {
    return e.features.clearStore();
  });
  (_converse$disco_entit2 = shared_converse.disco_entities) === null || _converse$disco_entit2 === void 0 ? void 0 : _converse$disco_entit2.forEach(function (e) {
    return e.identities.clearStore();
  });
  (_converse$disco_entit3 = shared_converse.disco_entities) === null || _converse$disco_entit3 === void 0 ? void 0 : _converse$disco_entit3.forEach(function (e) {
    return e.dataforms.clearStore();
  });
  (_converse$disco_entit4 = shared_converse.disco_entities) === null || _converse$disco_entit4 === void 0 ? void 0 : _converse$disco_entit4.forEach(function (e) {
    return e.fields.clearStore();
  });
  (_converse$disco_entit5 = shared_converse.disco_entities) === null || _converse$disco_entit5 === void 0 ? void 0 : _converse$disco_entit5.clearStore();
  delete shared_converse.disco_entities;
}
;// CONCATENATED MODULE: ./src/headless/plugins/disco/api.js
function disco_api_typeof(obj) {
  "@babel/helpers - typeof";

  return disco_api_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;
  }, disco_api_typeof(obj);
}
function api_toConsumableArray(arr) {
  return api_arrayWithoutHoles(arr) || api_iterableToArray(arr) || api_unsupportedIterableToArray(arr) || api_nonIterableSpread();
}
function api_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function api_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return api_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 api_arrayLikeToArray(o, minLen);
}
function api_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function api_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return api_arrayLikeToArray(arr);
}
function api_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 disco_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  disco_api_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" == disco_api_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 disco_api_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 disco_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        disco_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        disco_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}




var api_converse$env = public_converse.env,
  api_Strophe = api_converse$env.Strophe,
  api_$iq = api_converse$env.$iq;
/* harmony default export */ const disco_api = ({
  /**
   * The XEP-0030 service discovery API
   *
   * This API lets you discover information about entities on the
   * XMPP network.
   *
   * @namespace api.disco
   * @memberOf api
   */
  disco: {
    /**
     * @namespace api.disco.stream
     * @memberOf api.disco
     */
    stream: {
      /**
       * @method api.disco.stream.getFeature
       * @param { String } name The feature name
       * @param { String } xmlns The XML namespace
       * @example _converse.api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver')
       */
      getFeature: function getFeature(name, xmlns) {
        return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee() {
          var msg;
          return disco_api_regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return shared_api.waitUntil('streamFeaturesAdded');
              case 2:
                if (!(!name || !xmlns)) {
                  _context.next = 4;
                  break;
                }
                throw new Error("name and xmlns need to be provided when calling disco.stream.getFeature");
              case 4:
                if (!(shared_converse.stream_features === undefined && !shared_api.connection.connected())) {
                  _context.next = 8;
                  break;
                }
                // Happens during tests when disco lookups happen asynchronously after teardown.
                msg = "Tried to get feature ".concat(name, " ").concat(xmlns, " but _converse.stream_features has been torn down");
                log.warn(msg);
                return _context.abrupt("return");
              case 8:
                return _context.abrupt("return", shared_converse.stream_features.findWhere({
                  'name': name,
                  'xmlns': xmlns
                }));
              case 9:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }))();
      }
    },
    /**
     * @namespace api.disco.own
     * @memberOf api.disco
     */
    own: {
      /**
       * @namespace api.disco.own.identities
       * @memberOf api.disco.own
       */
      identities: {
        /**
         * Lets you add new identities for this client (i.e. instance of Converse)
         * @method api.disco.own.identities.add
         *
         * @param { String } category - server, client, gateway, directory, etc.
         * @param { String } type - phone, pc, web, etc.
         * @param { String } name - "Converse"
         * @param { String } lang - en, el, de, etc.
         *
         * @example _converse.api.disco.own.identities.clear();
         */
        add: function add(category, type, name, lang) {
          for (var i = 0; i < shared_converse.disco._identities.length; i++) {
            if (shared_converse.disco._identities[i].category == category && shared_converse.disco._identities[i].type == type && shared_converse.disco._identities[i].name == name && shared_converse.disco._identities[i].lang == lang) {
              return false;
            }
          }
          shared_converse.disco._identities.push({
            category: category,
            type: type,
            name: name,
            lang: lang
          });
        },
        /**
         * Clears all previously registered identities.
         * @method api.disco.own.identities.clear
         * @example _converse.api.disco.own.identities.clear();
         */
        clear: function clear() {
          shared_converse.disco._identities = [];
        },
        /**
         * Returns all of the identities registered for this client
         * (i.e. instance of Converse).
         * @method api.disco.identities.get
         * @example const identities = api.disco.own.identities.get();
         */
        get: function get() {
          return shared_converse.disco._identities;
        }
      },
      /**
       * @namespace api.disco.own.features
       * @memberOf api.disco.own
       */
      features: {
        /**
         * Lets you register new disco features for this client (i.e. instance of Converse)
         * @method api.disco.own.features.add
         * @param { String } name - e.g. http://jabber.org/protocol/caps
         * @example _converse.api.disco.own.features.add("http://jabber.org/protocol/caps");
         */
        add: function add(name) {
          for (var i = 0; i < shared_converse.disco._features.length; i++) {
            if (shared_converse.disco._features[i] == name) {
              return false;
            }
          }
          shared_converse.disco._features.push(name);
        },
        /**
         * Clears all previously registered features.
         * @method api.disco.own.features.clear
         * @example _converse.api.disco.own.features.clear();
         */
        clear: function clear() {
          shared_converse.disco._features = [];
        },
        /**
         * Returns all of the features registered for this client (i.e. instance of Converse).
         * @method api.disco.own.features.get
         * @example const features = api.disco.own.features.get();
         */
        get: function get() {
          return shared_converse.disco._features;
        }
      }
    },
    /**
     * Query for information about an XMPP entity
     *
     * @method api.disco.info
     * @param { string } jid The Jabber ID of the entity to query
     * @param { string } [node] A specific node identifier associated with the JID
     * @returns {promise} Promise which resolves once we have a result from the server.
     */
    info: function info(jid, node) {
      var attrs = {
        xmlns: api_Strophe.NS.DISCO_INFO
      };
      if (node) {
        attrs.node = node;
      }
      var info = api_$iq({
        'from': shared_converse.connection.jid,
        'to': jid,
        'type': 'get'
      }).c('query', attrs);
      return shared_api.sendIQ(info);
    },
    /**
     * Query for items associated with an XMPP entity
     *
     * @method api.disco.items
     * @param { string } jid The Jabber ID of the entity to query for items
     * @param { string } [node] A specific node identifier associated with the JID
     * @returns {promise} Promise which resolves once we have a result from the server.
     */
    items: function items(jid, node) {
      var attrs = {
        'xmlns': api_Strophe.NS.DISCO_ITEMS
      };
      if (node) {
        attrs.node = node;
      }
      return shared_api.sendIQ(api_$iq({
        'from': shared_converse.connection.jid,
        'to': jid,
        'type': 'get'
      }).c('query', attrs));
    },
    /**
     * Namespace for methods associated with disco entities
     *
     * @namespace api.disco.entities
     * @memberOf api.disco
     */
    entities: {
      /**
       * Get the corresponding `DiscoEntity` instance.
       *
       * @method api.disco.entities.get
       * @param { string } jid The Jabber ID of the entity
       * @param { boolean } [create] Whether the entity should be created if it doesn't exist.
       * @example _converse.api.disco.entities.get(jid);
       */
      get: function get(jid) {
        var _arguments = arguments;
        return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee2() {
          var create, entity;
          return disco_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
            while (1) switch (_context2.prev = _context2.next) {
              case 0:
                create = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;
                _context2.next = 3;
                return shared_api.waitUntil('discoInitialized');
              case 3:
                if (jid) {
                  _context2.next = 5;
                  break;
                }
                return _context2.abrupt("return", shared_converse.disco_entities);
              case 5:
                if (!(shared_converse.disco_entities === undefined)) {
                  _context2.next = 8;
                  break;
                }
                // Happens during tests when disco lookups happen asynchronously after teardown.
                log.warn("Tried to look up entity ".concat(jid, " but _converse.disco_entities has been torn down"));
                return _context2.abrupt("return");
              case 8:
                entity = shared_converse.disco_entities.get(jid);
                if (!(entity || !create)) {
                  _context2.next = 11;
                  break;
                }
                return _context2.abrupt("return", entity);
              case 11:
                return _context2.abrupt("return", shared_api.disco.entities.create({
                  jid: jid
                }));
              case 12:
              case "end":
                return _context2.stop();
            }
          }, _callee2);
        }))();
      },
      /**
       * Return any disco items advertised on this entity
       *
       * @method api.disco.entities.items
       * @param { string } jid The Jabber ID of the entity for which we want to fetch items
       * @example api.disco.entities.items(jid);
       */
      items: function items(jid) {
        return shared_converse.disco_entities.filter(function (e) {
          var _e$get;
          return (_e$get = e.get('parent_jids')) === null || _e$get === void 0 ? void 0 : _e$get.includes(jid);
        });
      },
      /**
       * Create a new  disco entity. It's identity and features
       * will automatically be fetched from cache or from the
       * XMPP server.
       *
       * Fetching from cache can be disabled by passing in
       * `ignore_cache: true` in the options parameter.
       *
       * @method api.disco.entities.create
       * @param { object } data
       * @param { string } data.jid - The Jabber ID of the entity
       * @param { string } data.parent_jid - The Jabber ID of the parent entity
       * @param { string } data.name
       * @param { object } [options] - Additional options
       * @param { boolean } [options.ignore_cache]
       *     If true, fetch all features from the XMPP server instead of restoring them from cache
       * @example _converse.api.disco.entities.create({ jid }, {'ignore_cache': true});
       */
      create: function create(data, options) {
        return shared_converse.disco_entities.create(data, options);
      }
    },
    /**
     * @namespace api.disco.features
     * @memberOf api.disco
     */
    features: {
      /**
       * Return a given feature of a disco entity
       *
       * @method api.disco.features.get
       * @param { string } feature The feature that might be
       *     supported. In the XML stanza, this is the `var`
       *     attribute of the `<feature>` element. For
       *     example: `http://jabber.org/protocol/muc`
       * @param { string } jid The JID of the entity
       *     (and its associated items) which should be queried
       * @returns {promise} A promise which resolves with a list containing
       *     _converse.Entity instances representing the entity
       *     itself or those items associated with the entity if
       *     they support the given feature.
       * @example
       * api.disco.features.get(Strophe.NS.MAM, _converse.bare_jid);
       */
      get: function get(feature, jid) {
        return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee3() {
          var entity, promises, result;
          return disco_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
            while (1) switch (_context3.prev = _context3.next) {
              case 0:
                if (jid) {
                  _context3.next = 2;
                  break;
                }
                throw new TypeError('You need to provide an entity JID');
              case 2:
                _context3.next = 4;
                return shared_api.disco.entities.get(jid, true);
              case 4:
                entity = _context3.sent;
                if (!(shared_converse.disco_entities === undefined && !shared_api.connection.connected())) {
                  _context3.next = 8;
                  break;
                }
                // Happens during tests when disco lookups happen asynchronously after teardown.
                log.warn("Tried to get feature ".concat(feature, " for ").concat(jid, " but _converse.disco_entities has been torn down"));
                return _context3.abrupt("return", []);
              case 8:
                promises = [entity.getFeature(feature)].concat(api_toConsumableArray(shared_api.disco.entities.items(jid).map(function (i) {
                  return i.getFeature(feature);
                })));
                _context3.next = 11;
                return Promise.all(promises);
              case 11:
                result = _context3.sent;
                return _context3.abrupt("return", result.filter(lodash_es_isObject));
              case 13:
              case "end":
                return _context3.stop();
            }
          }, _callee3);
        }))();
      },
      /**
       * Returns true if an entity with the given JID, or if one of its
       * associated items, supports a given feature.
       *
       * @method api.disco.features.has
       * @param { string } feature The feature that might be
       *     supported. In the XML stanza, this is the `var`
       *     attribute of the `<feature>` element. For
       *     example: `http://jabber.org/protocol/muc`
       * @param { string } jid The JID of the entity
       *     (and its associated items) which should be queried
       * @returns {Promise} A promise which resolves with a boolean
       * @example
       *      api.disco.features.has(Strophe.NS.MAM, _converse.bare_jid);
       */
      has: function has(feature, jid) {
        return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee4() {
          var entity, result;
          return disco_api_regeneratorRuntime().wrap(function _callee4$(_context4) {
            while (1) switch (_context4.prev = _context4.next) {
              case 0:
                if (jid) {
                  _context4.next = 2;
                  break;
                }
                throw new TypeError('You need to provide an entity JID');
              case 2:
                _context4.next = 4;
                return shared_api.disco.entities.get(jid, true);
              case 4:
                entity = _context4.sent;
                if (!(shared_converse.disco_entities === undefined && !shared_api.connection.connected())) {
                  _context4.next = 8;
                  break;
                }
                // Happens during tests when disco lookups happen asynchronously after teardown.
                log.warn("Tried to check if ".concat(jid, " supports feature ").concat(feature));
                return _context4.abrupt("return", false);
              case 8:
                _context4.next = 10;
                return entity.getFeature(feature);
              case 10:
                if (!_context4.sent) {
                  _context4.next = 12;
                  break;
                }
                return _context4.abrupt("return", true);
              case 12:
                _context4.next = 14;
                return Promise.all(shared_api.disco.entities.items(jid).map(function (i) {
                  return i.getFeature(feature);
                }));
              case 14:
                result = _context4.sent;
                return _context4.abrupt("return", result.map(lodash_es_isObject).includes(true));
              case 16:
              case "end":
                return _context4.stop();
            }
          }, _callee4);
        }))();
      }
    },
    /**
     * Used to determine whether an entity supports a given feature.
     *
     * @method api.disco.supports
     * @param { string } feature The feature that might be
     *     supported. In the XML stanza, this is the `var`
     *     attribute of the `<feature>` element. For
     *     example: `http://jabber.org/protocol/muc`
     * @param { string } jid The JID of the entity
     *     (and its associated items) which should be queried
     * @returns {promise} A promise which resolves with `true` or `false`.
     * @example
     * if (await api.disco.supports(Strophe.NS.MAM, _converse.bare_jid)) {
     *     // The feature is supported
     * } else {
     *     // The feature is not supported
     * }
     */
    supports: function supports(feature, jid) {
      return shared_api.disco.features.has(feature, jid);
    },
    /**
     * Refresh the features, fields and identities associated with a
     * disco entity by refetching them from the server
     * @method api.disco.refresh
     * @param { string } jid The JID of the entity whose features are refreshed.
     * @returns {promise} A promise which resolves once the features have been refreshed
     * @example
     * await api.disco.refresh('room@conference.example.org');
     */
    refresh: function refresh(jid) {
      return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee5() {
        var entity;
        return disco_api_regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              if (jid) {
                _context5.next = 2;
                break;
              }
              throw new TypeError('api.disco.refresh: You need to provide an entity JID');
            case 2:
              _context5.next = 4;
              return shared_api.waitUntil('discoInitialized');
            case 4:
              _context5.next = 6;
              return shared_api.disco.entities.get(jid);
            case 6:
              entity = _context5.sent;
              if (!entity) {
                _context5.next = 15;
                break;
              }
              entity.features.reset();
              entity.fields.reset();
              entity.identities.reset();
              if (!entity.waitUntilFeaturesDiscovered.isPending) {
                entity.waitUntilFeaturesDiscovered = getOpenPromise();
              }
              entity.queryInfo();
              _context5.next = 18;
              break;
            case 15:
              _context5.next = 17;
              return shared_api.disco.entities.create({
                jid: jid
              }, {
                'ignore_cache': true
              });
            case 17:
              entity = _context5.sent;
            case 18:
              return _context5.abrupt("return", entity.waitUntilFeaturesDiscovered);
            case 19:
            case "end":
              return _context5.stop();
          }
        }, _callee5);
      }))();
    },
    /**
     * @deprecated Use {@link api.disco.refresh} instead.
     * @method api.disco.refreshFeatures
     */
    refreshFeatures: function refreshFeatures(jid) {
      return shared_api.refresh(jid);
    },
    /**
     * Return all the features associated with a disco entity
     *
     * @method api.disco.getFeatures
     * @param { string } jid The JID of the entity whose features are returned.
     * @returns {promise} A promise which resolves with the returned features
     * @example
     * const features = await api.disco.getFeatures('room@conference.example.org');
     */
    getFeatures: function getFeatures(jid) {
      return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee6() {
        var entity;
        return disco_api_regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              if (jid) {
                _context6.next = 2;
                break;
              }
              throw new TypeError('api.disco.getFeatures: You need to provide an entity JID');
            case 2:
              _context6.next = 4;
              return shared_api.waitUntil('discoInitialized');
            case 4:
              _context6.next = 6;
              return shared_api.disco.entities.get(jid, true);
            case 6:
              entity = _context6.sent;
              _context6.next = 9;
              return entity.waitUntilFeaturesDiscovered;
            case 9:
              entity = _context6.sent;
              return _context6.abrupt("return", entity.features);
            case 11:
            case "end":
              return _context6.stop();
          }
        }, _callee6);
      }))();
    },
    /**
     * Return all the service discovery extensions fields
     * associated with an entity.
     *
     * See [XEP-0129: Service Discovery Extensions](https://xmpp.org/extensions/xep-0128.html)
     *
     * @method api.disco.getFields
     * @param { string } jid The JID of the entity whose fields are returned.
     * @example
     * const fields = await api.disco.getFields('room@conference.example.org');
     */
    getFields: function getFields(jid) {
      return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee7() {
        var entity;
        return disco_api_regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              if (jid) {
                _context7.next = 2;
                break;
              }
              throw new TypeError('api.disco.getFields: You need to provide an entity JID');
            case 2:
              _context7.next = 4;
              return shared_api.waitUntil('discoInitialized');
            case 4:
              _context7.next = 6;
              return shared_api.disco.entities.get(jid, true);
            case 6:
              entity = _context7.sent;
              _context7.next = 9;
              return entity.waitUntilFeaturesDiscovered;
            case 9:
              entity = _context7.sent;
              return _context7.abrupt("return", entity.fields);
            case 11:
            case "end":
              return _context7.stop();
          }
        }, _callee7);
      }))();
    },
    /**
     * Get the identity (with the given category and type) for a given disco entity.
     *
     * For example, when determining support for PEP (personal eventing protocol), you
     * want to know whether the user's own JID has an identity with
     * `category='pubsub'` and `type='pep'` as explained in this section of
     * XEP-0163: https://xmpp.org/extensions/xep-0163.html#support
     *
     * @method api.disco.getIdentity
     * @param { string } The identity category.
     *     In the XML stanza, this is the `category`
     *     attribute of the `<identity>` element.
     *     For example: 'pubsub'
     * @param { string } type The identity type.
     *     In the XML stanza, this is the `type`
     *     attribute of the `<identity>` element.
     *     For example: 'pep'
     * @param { string } jid The JID of the entity which might have the identity
     * @returns {promise} A promise which resolves with a map indicating
     *     whether an identity with a given type is provided by the entity.
     * @example
     * api.disco.getIdentity('pubsub', 'pep', _converse.bare_jid).then(
     *     function (identity) {
     *         if (identity) {
     *             // The entity DOES have this identity
     *         } else {
     *             // The entity DOES NOT have this identity
     *         }
     *     }
     * ).catch(e => log.error(e));
     */
    getIdentity: function getIdentity(category, type, jid) {
      return disco_api_asyncToGenerator( /*#__PURE__*/disco_api_regeneratorRuntime().mark(function _callee8() {
        var e, msg;
        return disco_api_regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              _context8.next = 2;
              return shared_api.disco.entities.get(jid, true);
            case 2:
              e = _context8.sent;
              if (!(e === undefined && !shared_api.connection.connected())) {
                _context8.next = 7;
                break;
              }
              // Happens during tests when disco lookups happen asynchronously after teardown.
              msg = "Tried to look up category ".concat(category, " for ").concat(jid, " but _converse.disco_entities has been torn down");
              log.warn(msg);
              return _context8.abrupt("return");
            case 7:
              return _context8.abrupt("return", e.getIdentity(category, type));
            case 8:
            case "end":
              return _context8.stop();
          }
        }, _callee8);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/disco/index.js
function disco_typeof(obj) {
  "@babel/helpers - typeof";

  return disco_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;
  }, disco_typeof(obj);
}
function disco_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  disco_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" == disco_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 disco_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 disco_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        disco_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        disco_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse plugin which add support for XEP-0030: Service Discovery
 */





var disco_Strophe = public_converse.env.Strophe;
public_converse.plugins.add('converse-disco', {
  initialize: function initialize() {
    Object.assign(shared_api, disco_api);
    shared_api.promises.add('discoInitialized');
    shared_api.promises.add('streamFeaturesAdded');
    shared_converse.DiscoEntity = entity;
    shared_converse.DiscoEntities = entities;
    shared_converse.disco = {
      _identities: [],
      _features: []
    };
    shared_api.listen.on('userSessionInitialized', /*#__PURE__*/disco_asyncToGenerator( /*#__PURE__*/disco_regeneratorRuntime().mark(function _callee() {
      return disco_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            initStreamFeatures();
            if (!(shared_converse.connfeedback.get('connection_status') === disco_Strophe.Status.ATTACHED)) {
              _context.next = 5;
              break;
            }
            _context.next = 4;
            return new Promise(function (success, error) {
              return shared_converse.stream_features.fetch({
                success: success,
                error: error
              });
            });
          case 4:
            notifyStreamFeaturesAdded();
          case 5:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    shared_api.listen.on('beforeResourceBinding', populateStreamFeatures);
    shared_api.listen.on('reconnected', initializeDisco);
    shared_api.listen.on('connected', initializeDisco);
    shared_api.listen.on('beforeTearDown', /*#__PURE__*/disco_asyncToGenerator( /*#__PURE__*/disco_regeneratorRuntime().mark(function _callee2() {
      return disco_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            shared_api.promises.add('streamFeaturesAdded');
            if (!shared_converse.stream_features) {
              _context2.next = 5;
              break;
            }
            _context2.next = 4;
            return shared_converse.stream_features.clearStore();
          case 4:
            delete shared_converse.stream_features;
          case 5:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    })));

    // All disco entities stored in sessionStorage and are refetched
    // upon login or reconnection and then stored with new ids, so to
    // avoid sessionStorage filling up, we remove them.
    shared_api.listen.on('will-reconnect', utils_clearSession);
    shared_api.listen.on('clearSession', utils_clearSession);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/regexes.js
var ASCII_REGEX = '(\\*\\\\0\\/\\*|\\*\\\\O\\/\\*|\\-___\\-|\\:\'\\-\\)|\'\\:\\-\\)|\'\\:\\-D|\\>\\:\\-\\)|>\\:\\-\\)|\'\\:\\-\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:\'\\-\\(|O\\:\\-\\)|0\\:\\-3|0\\:\\-\\)|0;\\^\\)|O;\\-\\)|0;\\-\\)|O\\:\\-3|\\-__\\-|\\:\\-Þ|\\:\\-Þ|\\<\\/3|<\\/3|\\:\'\\)|\\:\\-D|\'\\:\\)|\'\\=\\)|\'\\:D|\'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\=\\)|>\\=\\)|;\\-\\)|\\*\\-\\)|;\\-\\]|;\\^\\)|\'\\:\\(|\'\\=\\(|\\:\\-\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\-\\[|\\>\\:\\(|>\\:\\(|\\:\'\\(|;\\-\\(|\\>\\.\\<|>\\.<|#\\-\\)|%\\-\\)|X\\-\\)|\\\\0\\/|\\\\O\\/|0\\:3|0\\:\\)|O\\:\\)|O\\=\\)|O\\:3|B\\-\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\-P|\\:Þ|\\:Þ|\\:\\-b|\\:\\-O|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:\\-#|\\:\\-\\)|\\(y\\)|\\<3|<3|\\:D|\\=D|;\\)|\\*\\)|;\\]|;D|\\:\\*|\\=\\*|\\:\\(|\\:\\[|\\=\\(|\\:@|;\\(|D\\:|\\:\\$|\\=\\$|#\\)|%\\)|X\\)|B\\)|8\\)|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\=P|\\:b|\\:O|\\:X|\\:#|\\=X|\\=#|\\:\\)|\\=\\]|\\=\\)|\\:\\])';
var ASCII_REPLACE_REGEX = new RegExp("<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)" + ASCII_REGEX + "(?=\\s|$|[!,.?]))", "gi");
var CODEPOINTS_REGEX = /(?:\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5\udeeb\udeec\udef4-\udefa\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd71\udd73-\udd76\udd7a-\udda2\udda5-\uddaa\uddae-\uddb4\uddb7\uddba\uddbc-\uddca\uddd0\uddde-\uddff\ude70-\ude73\ude78-\ude7a\ude80-\ude82\ude90-\ude95]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g;
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/utils.js
function utils_toConsumableArray(arr) {
  return utils_arrayWithoutHoles(arr) || utils_iterableToArray(arr) || utils_unsupportedIterableToArray(arr) || utils_nonIterableSpread();
}
function utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return utils_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 utils_arrayLikeToArray(o, minLen);
}
function utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return utils_arrayLikeToArray(arr);
}
function utils_arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}


var emoji_utils_u = public_converse.env.u;

// Closured cache
var emojis_by_attribute = {};
var ASCII_LIST = {
  '*\\0/*': '1f646',
  '*\\O/*': '1f646',
  '-___-': '1f611',
  ':\'-)': '1f602',
  '\':-)': '1f605',
  '\':-D': '1f605',
  '>:-)': '1f606',
  '\':-(': '1f613',
  '>:-(': '1f620',
  ':\'-(': '1f622',
  'O:-)': '1f607',
  '0:-3': '1f607',
  '0:-)': '1f607',
  '0;^)': '1f607',
  'O;-)': '1f607',
  '0;-)': '1f607',
  'O:-3': '1f607',
  '-__-': '1f611',
  ':-Þ': '1f61b',
  '</3': '1f494',
  ':\')': '1f602',
  ':-D': '1f603',
  '\':)': '1f605',
  '\'=)': '1f605',
  '\':D': '1f605',
  '\'=D': '1f605',
  '>:)': '1f606',
  '>;)': '1f606',
  '>=)': '1f606',
  ';-)': '1f609',
  '*-)': '1f609',
  ';-]': '1f609',
  ';^)': '1f609',
  '\':(': '1f613',
  '\'=(': '1f613',
  ':-*': '1f618',
  ':^*': '1f618',
  '>:P': '1f61c',
  'X-P': '1f61c',
  '>:[': '1f61e',
  ':-(': '1f61e',
  ':-[': '1f61e',
  '>:(': '1f620',
  ':\'(': '1f622',
  ';-(': '1f622',
  '>.<': '1f623',
  '#-)': '1f635',
  '%-)': '1f635',
  'X-)': '1f635',
  '\\0/': '1f646',
  '\\O/': '1f646',
  '0:3': '1f607',
  '0:)': '1f607',
  'O:)': '1f607',
  'O=)': '1f607',
  'O:3': '1f607',
  'B-)': '1f60e',
  '8-)': '1f60e',
  'B-D': '1f60e',
  '8-D': '1f60e',
  '-_-': '1f611',
  '>:\\': '1f615',
  '>:/': '1f615',
  ':-/': '1f615',
  ':-.': '1f615',
  ':-P': '1f61b',
  ':Þ': '1f61b',
  ':-b': '1f61b',
  ':-O': '1f62e',
  'O_O': '1f62e',
  '>:O': '1f62e',
  ':-X': '1f636',
  ':-#': '1f636',
  ':-)': '1f642',
  '(y)': '1f44d',
  '<3': '2764',
  ':D': '1f603',
  '=D': '1f603',
  ';)': '1f609',
  '*)': '1f609',
  ';]': '1f609',
  ';D': '1f609',
  ':*': '1f618',
  '=*': '1f618',
  ':(': '1f61e',
  ':[': '1f61e',
  '=(': '1f61e',
  ':@': '1f620',
  ';(': '1f622',
  'D:': '1f628',
  ':$': '1f633',
  '=$': '1f633',
  '#)': '1f635',
  '%)': '1f635',
  'X)': '1f635',
  'B)': '1f60e',
  '8)': '1f60e',
  ':/': '1f615',
  ':\\': '1f615',
  '=/': '1f615',
  '=\\': '1f615',
  ':L': '1f615',
  '=L': '1f615',
  ':P': '1f61b',
  '=P': '1f61b',
  ':b': '1f61b',
  ':O': '1f62e',
  ':X': '1f636',
  ':#': '1f636',
  '=X': '1f636',
  '=#': '1f636',
  ':)': '1f642',
  '=]': '1f642',
  '=)': '1f642',
  ':]': '1f642'
};
function toCodePoint(unicode_surrogates) {
  var r = [];
  var p = 0;
  var i = 0;
  while (i < unicode_surrogates.length) {
    var c = unicode_surrogates.charCodeAt(i++);
    if (p) {
      r.push((0x10000 + (p - 0xD800 << 10) + (c - 0xDC00)).toString(16));
      p = 0;
    } else if (0xD800 <= c && c <= 0xDBFF) {
      p = c;
    } else {
      r.push(c.toString(16));
    }
  }
  return r.join('-');
}
function fromCodePoint(codepoint) {
  var code = typeof codepoint === 'string' ? parseInt(codepoint, 16) : codepoint;
  if (code < 0x10000) {
    return String.fromCharCode(code);
  }
  code -= 0x10000;
  return String.fromCharCode(0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF));
}
function convert(unicode) {
  // Converts unicode code points and code pairs to their respective characters
  if (unicode.indexOf("-") > -1) {
    var parts = [],
      s = unicode.split('-');
    for (var i = 0; i < s.length; i++) {
      var part = parseInt(s[i], 16);
      if (part >= 0x10000 && part <= 0x10FFFF) {
        var hi = Math.floor((part - 0x10000) / 0x400) + 0xD800;
        var lo = (part - 0x10000) % 0x400 + 0xDC00;
        part = String.fromCharCode(hi) + String.fromCharCode(lo);
      } else {
        part = String.fromCharCode(part);
      }
      parts.push(part);
    }
    return parts.join('');
  }
  return fromCodePoint(unicode);
}
function convertASCII2Emoji(str) {
  // Replace ASCII smileys
  return str.replace(ASCII_REPLACE_REGEX, function (entire, _, m2, m3) {
    if (typeof m3 === 'undefined' || m3 === '' || !(emoji_utils_u.unescapeHTML(m3) in ASCII_LIST)) {
      // if the ascii doesnt exist just return the entire match
      return entire;
    }
    m3 = emoji_utils_u.unescapeHTML(m3);
    var unicode = ASCII_LIST[m3].toUpperCase();
    return m2 + convert(unicode);
  });
}
function getShortnameReferences(text) {
  if (!public_converse.emojis.initialized) {
    throw new Error('getShortnameReferences called before emojis are initialized. ' + 'To avoid this problem, first await the converse.emojis.initialized_promise');
  }
  var references = utils_toConsumableArray(text.matchAll(public_converse.emojis.shortnames_regex)).filter(function (ref) {
    return ref[0].length > 0;
  });
  return references.map(function (ref) {
    var cp = public_converse.emojis.by_sn[ref[0]].cp;
    return {
      cp: cp,
      'begin': ref.index,
      'end': ref.index + ref[0].length,
      'shortname': ref[0],
      'emoji': cp ? convert(cp) : null
    };
  });
}
function parseStringForEmojis(str, callback) {
  var UFE0Fg = /\uFE0F/g;
  var U200D = String.fromCharCode(0x200D);
  return String(str).replace(CODEPOINTS_REGEX, function (emoji, _, offset) {
    var icon_id = toCodePoint(emoji.indexOf(U200D) < 0 ? emoji.replace(UFE0Fg, '') : emoji);
    if (icon_id) callback(icon_id, emoji, offset);
  });
}
function getCodePointReferences(text) {
  var references = [];
  parseStringForEmojis(text, function (icon_id, emoji, offset) {
    var _getEmojisByAtrribute;
    references.push({
      'begin': offset,
      'cp': icon_id,
      'emoji': emoji,
      'end': offset + emoji.length,
      'shortname': ((_getEmojisByAtrribute = getEmojisByAtrribute('cp')[icon_id]) === null || _getEmojisByAtrribute === void 0 ? void 0 : _getEmojisByAtrribute.sn) || ''
    });
  });
  return references;
}
function addEmojisMarkup(text) {
  var list = [text];
  [].concat(utils_toConsumableArray(getShortnameReferences(text)), utils_toConsumableArray(getCodePointReferences(text))).sort(function (a, b) {
    return b.begin - a.begin;
  }).forEach(function (ref) {
    var text = list.shift();
    var emoji = ref.emoji || ref.shortname;
    list = [text.slice(0, ref.begin) + emoji + text.slice(ref.end)].concat(utils_toConsumableArray(list));
  });
  return list;
}

/**
 * Replaces all shortnames in the passed in string with their
 * unicode (emoji) representation.
 * @namespace u
 * @method u.shortnamesToUnicode
 * @param { String } str - String containing the shortname(s)
 * @returns { String }
 */
function shortnamesToUnicode(str) {
  return addEmojisMarkup(convertASCII2Emoji(str)).pop();
}

/**
 * Determines whether the passed in string is just a single emoji shortname;
 * @namespace u
 * @method u.isOnlyEmojis
 * @param { String } text - A string which migh be just an emoji shortname
 * @returns { Boolean }
 */
function isOnlyEmojis(text) {
  var words = text.trim().split(/\s+/);
  if (words.length === 0 || words.length > 3) {
    return false;
  }
  var emojis = words.filter(function (text) {
    var refs = getCodePointReferences(emoji_utils_u.shortnamesToUnicode(text));
    return refs.length === 1 && (text === refs[0]['shortname'] || text === refs[0]['emoji']);
  });
  return emojis.length === words.length;
}

/**
 * @namespace u
 * @method u.getEmojisByAtrribute
 * @param { 'category'|'cp'|'sn' } attr
 *  The attribute according to which the returned map should be keyed.
 * @returns { Object }
 *  Map of emojis with the passed in `attr` used as key and a list of emojis as values.
 */
function getEmojisByAtrribute(attr) {
  if (emojis_by_attribute[attr]) {
    return emojis_by_attribute[attr];
  }
  if (attr === 'category') {
    return public_converse.emojis.json;
  }
  var all_variants = public_converse.emojis.list.map(function (e) {
    return e[attr];
  }).filter(function (c, i, arr) {
    return arr.indexOf(c) == i;
  });
  emojis_by_attribute[attr] = {};
  all_variants.forEach(function (v) {
    return emojis_by_attribute[attr][v] = public_converse.emojis.list.find(function (i) {
      return i[attr] === v;
    });
  });
  return emojis_by_attribute[attr];
}
Object.assign(emoji_utils_u, {
  getEmojisByAtrribute: getEmojisByAtrribute,
  isOnlyEmojis: isOnlyEmojis,
  shortnamesToUnicode: shortnamesToUnicode
});
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/index.js
function emoji_typeof(obj) {
  "@babel/helpers - typeof";

  return emoji_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;
  }, emoji_typeof(obj);
}
function emoji_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  emoji_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" == emoji_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 emoji_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 emoji_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        emoji_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        emoji_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @module converse-emoji
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




public_converse.emojis = {
  'initialized': false,
  'initialized_promise': getOpenPromise()
};
public_converse.plugins.add('converse-emoji', {
  initialize: function initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    var ___ = shared_converse.___;
    shared_api.settings.extend({
      'emoji_image_path': 'https://twemoji.maxcdn.com/v/12.1.6/',
      'emoji_categories': {
        "smileys": ":grinning:",
        "people": ":thumbsup:",
        "activity": ":soccer:",
        "travel": ":motorcycle:",
        "objects": ":bomb:",
        "nature": ":rainbow:",
        "food": ":hotdog:",
        "symbols": ":musical_note:",
        "flags": ":flag_ac:",
        "custom": null
      },
      // We use the triple-underscore method which doesn't actually
      // translate but does signify to gettext that these strings should
      // go into the POT file. The translation then happens in the
      // template. We do this so that users can pass in their own
      // strings via converse.initialize, which is before __ is
      // available.
      'emoji_category_labels': {
        "smileys": ___("Smileys and emotions"),
        "people": ___("People"),
        "activity": ___("Activities"),
        "travel": ___("Travel"),
        "objects": ___("Objects"),
        "nature": ___("Animals and nature"),
        "food": ___("Food and drink"),
        "symbols": ___("Symbols"),
        "flags": ___("Flags"),
        "custom": ___("Stickers")
      }
    });

    /**
     * Model for storing data related to the Emoji picker widget
     * @class
     * @namespace _converse.EmojiPicker
     * @memberOf _converse
     */
    shared_converse.EmojiPicker = Model.extend({
      defaults: {
        'current_category': 'smileys',
        'current_skintone': '',
        'scroll_position': 0
      }
    });

    // We extend the default converse.js API to add methods specific to MUC groupchats.
    Object.assign(shared_api, {
      /**
       * @namespace api.emojis
       * @memberOf api
       */
      emojis: {
        /**
         * Initializes Emoji support by downloading the emojis JSON (and any applicable images).
         * @method api.emojis.initialize
         * @returns {Promise}
         */
        initialize: function initialize() {
          return emoji_asyncToGenerator( /*#__PURE__*/emoji_regeneratorRuntime().mark(function _callee() {
            var module, json, getShortNames;
            return emoji_regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  if (public_converse.emojis.initialized) {
                    _context.next = 13;
                    break;
                  }
                  public_converse.emojis.initialized = true;
                  _context.next = 4;
                  return __webpack_require__.e(/* import() | emojis */ 4610).then(__webpack_require__.t.bind(__webpack_require__, 5175, 19));
                case 4:
                  module = _context.sent;
                  json = public_converse.emojis.json = module.default;
                  public_converse.emojis.by_sn = Object.keys(json).reduce(function (result, cat) {
                    return Object.assign(result, json[cat]);
                  }, {});
                  public_converse.emojis.list = Object.values(public_converse.emojis.by_sn);
                  public_converse.emojis.list.sort(function (a, b) {
                    return a.sn < b.sn ? -1 : a.sn > b.sn ? 1 : 0;
                  });
                  public_converse.emojis.shortnames = public_converse.emojis.list.map(function (m) {
                    return m.sn;
                  });
                  getShortNames = function getShortNames() {
                    return public_converse.emojis.shortnames.map(function (s) {
                      return s.replace(/[+]/g, "\\$&");
                    }).join('|');
                  };
                  public_converse.emojis.shortnames_regex = new RegExp(getShortNames(), "gi");
                  public_converse.emojis.initialized_promise.resolve();
                case 13:
                  return _context.abrupt("return", public_converse.emojis.initialized_promise);
                case 14:
                case "end":
                  return _context.stop();
              }
            }, _callee);
          }))();
        }
      }
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/message.js



/**
 * Mixing that turns a Message model into a ChatRoomMessage model.
 * @class
 * @namespace _converse.ChatRoomMessage
 * @memberOf _converse
 */
var ChatRoomMessageMixin = {
  initialize: function initialize() {
    var _this = this,
      _this$collection;
    if (!this.checkValidity()) {
      return;
    }
    if (this.get('file')) {
      this.on('change:put', function () {
        return _this.uploadFile();
      });
    }
    // If `type` changes from `error` to `groupchat`, we want to set the occupant. See #2733
    this.on('change:type', function () {
      return _this.setOccupant();
    });
    this.on('change:is_ephemeral', function () {
      return _this.setTimerForEphemeralMessage();
    });
    this.chatbox = (_this$collection = this.collection) === null || _this$collection === void 0 ? void 0 : _this$collection.chatbox;
    this.setTimerForEphemeralMessage();
    this.setOccupant();
    /**
     * Triggered once a { @link _converse.ChatRoomMessage } has been created and initialized.
     * @event _converse#chatRoomMessageInitialized
     * @type { _converse.ChatRoomMessages}
     * @example _converse.api.listen.on('chatRoomMessageInitialized', model => { ... });
     */
    shared_api.trigger('chatRoomMessageInitialized', this);
  },
  getDisplayName: function getDisplayName() {
    var _this$occupant;
    return ((_this$occupant = this.occupant) === null || _this$occupant === void 0 ? void 0 : _this$occupant.getDisplayName()) || this.get('nick');
  },
  /**
   * Determines whether this messsage may be moderated,
   * based on configuration settings and server support.
   * @async
   * @private
   * @method _converse.ChatRoomMessages#mayBeModerated
   * @returns { Boolean }
   */
  mayBeModerated: function mayBeModerated() {
    if (typeof this.get('from_muc') === 'undefined') {
      // If from_muc is not defined, then this message hasn't been
      // reflected yet, which means we won't have a XEP-0359 stanza id.
      return;
    }
    return ['all', 'moderator'].includes(shared_api.settings.get('allow_message_retraction')) && this.get("stanza_id ".concat(this.get('from_muc'))) && this.chatbox.canModerateMessages();
  },
  checkValidity: function checkValidity() {
    var result = shared_converse.Message.prototype.checkValidity.call(this);
    !result && this.chatbox.debouncedRejoin();
    return result;
  },
  onOccupantRemoved: function onOccupantRemoved() {
    this.stopListening(this.occupant);
    delete this.occupant;
    this.listenTo(this.chatbox.occupants, 'add', this.onOccupantAdded);
  },
  onOccupantAdded: function onOccupantAdded(occupant) {
    if (this.get('occupant_id')) {
      if (occupant.get('occupant_id') !== this.get('occupant_id')) {
        return;
      }
    } else if (occupant.get('nick') !== external_strophe_namespaceObject.Strophe.getResourceFromJid(this.get('from'))) {
      return;
    }
    this.occupant = occupant;
    if (occupant.get('jid')) {
      this.save('from_real_jid', occupant.get('jid'));
    }
    this.trigger('occupantAdded');
    this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
    this.stopListening(this.chatbox.occupants, 'add', this.onOccupantAdded);
  },
  getOccupant: function getOccupant() {
    if (this.occupant) return this.occupant;
    this.setOccupant();
    return this.occupant;
  },
  setOccupant: function setOccupant() {
    if (this.get('type') !== 'groupchat' || this.isEphemeral() || this.occupant) {
      return;
    }
    var nick = external_strophe_namespaceObject.Strophe.getResourceFromJid(this.get('from'));
    var occupant_id = this.get('occupant_id');
    this.occupant = this.chatbox.occupants.findOccupant({
      nick: nick,
      occupant_id: occupant_id
    });
    if (!this.occupant) {
      this.occupant = this.chatbox.occupants.create({
        nick: nick,
        occupant_id: occupant_id,
        jid: this.get('from_real_jid')
      });
      if (shared_api.settings.get('muc_send_probes')) {
        var jid = "".concat(this.chatbox.get('jid'), "/").concat(nick);
        shared_api.user.presence.send('probe', jid);
      }
    }
    this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
  }
};
/* harmony default export */ const muc_message = (ChatRoomMessageMixin);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isElement.js



/**
 * Checks if `value` is likely a DOM element.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
 * @example
 *
 * _.isElement(document.body);
 * // => true
 *
 * _.isElement('<body>');
 * // => false
 */
function isElement_isElement(value) {
  return lodash_es_isObjectLike(value) && value.nodeType === 1 && !lodash_es_isPlainObject(value);
}
/* harmony default export */ const lodash_es_isElement = (isElement_isElement);
;// CONCATENATED MODULE: ./src/headless/utils/parse-helpers.js
function parse_helpers_typeof(obj) {
  "@babel/helpers - typeof";

  return parse_helpers_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;
  }, parse_helpers_typeof(obj);
}
function parse_helpers_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 parse_helpers_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? parse_helpers_ownKeys(Object(source), !0).forEach(function (key) {
      parse_helpers_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : parse_helpers_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function parse_helpers_defineProperty(obj, key, value) {
  key = parse_helpers_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 parse_helpers_toPropertyKey(arg) {
  var key = parse_helpers_toPrimitive(arg, "string");
  return parse_helpers_typeof(key) === "symbol" ? key : String(key);
}
function parse_helpers_toPrimitive(input, hint) {
  if (parse_helpers_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (parse_helpers_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function parse_helpers_toConsumableArray(arr) {
  return parse_helpers_arrayWithoutHoles(arr) || parse_helpers_iterableToArray(arr) || parse_helpers_unsupportedIterableToArray(arr) || parse_helpers_nonIterableSpread();
}
function parse_helpers_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function parse_helpers_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function parse_helpers_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return parse_helpers_arrayLikeToArray(arr);
}
function parse_helpers_slicedToArray(arr, i) {
  return parse_helpers_arrayWithHoles(arr) || parse_helpers_iterableToArrayLimit(arr, i) || parse_helpers_unsupportedIterableToArray(arr, i) || parse_helpers_nonIterableRest();
}
function parse_helpers_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function parse_helpers_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return parse_helpers_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 parse_helpers_arrayLikeToArray(o, minLen);
}
function parse_helpers_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 parse_helpers_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function parse_helpers_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Pure functions to help functionally parse messages.
 * @todo Other parsing helpers can be made more abstract and placed here.
 */
var helpers = {};
var escapeRegexChars = function escapeRegexChars(string, char) {
  return string.replace(RegExp('\\' + char, 'ig'), '\\' + char);
};
helpers.escapeCharacters = function (characters) {
  return function (string) {
    return characters.split('').reduce(escapeRegexChars, string);
  };
};
helpers.escapeRegexString = helpers.escapeCharacters('[\\^$.?*+(){}|');

// `for` is ~25% faster than using `Array.find()`
helpers.findFirstMatchInArray = function (array) {
  return function (text) {
    for (var i = 0; i < array.length; i++) {
      if (text.localeCompare(array[i], undefined, {
        sensitivity: 'base'
      }) === 0) {
        return array[i];
      }
    }
    return null;
  };
};
var reduceReferences = function reduceReferences(_ref, ref, index) {
  var _ref2 = parse_helpers_slicedToArray(_ref, 2),
    text = _ref2[0],
    refs = _ref2[1];
  var updated_text = text;
  var begin = ref.begin,
    end = ref.end;
  var value = ref.value;
  begin = begin - index;
  end = end - index - 1; // -1 to compensate for the removed @
  updated_text = "".concat(updated_text.slice(0, begin)).concat(value).concat(updated_text.slice(end + 1));
  return [updated_text, [].concat(parse_helpers_toConsumableArray(refs), [parse_helpers_objectSpread(parse_helpers_objectSpread({}, ref), {}, {
    begin: begin,
    end: end
  })])];
};
helpers.reduceTextFromReferences = function (text, refs) {
  return refs.reduce(reduceReferences, [text, []]);
};
/* harmony default export */ const parse_helpers = (helpers);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/constants.js
var ROLES = ['moderator', 'participant', 'visitor'];
var AFFILIATIONS = ['owner', 'admin', 'member', 'outcast', 'none'];
var MUC_ROLE_WEIGHTS = {
  'moderator': 1,
  'participant': 2,
  'visitor': 3,
  'none': 2
};
var AFFILIATION_CHANGES = {
  OWNER: 'owner',
  ADMIN: 'admin',
  MEMBER: 'member',
  EXADMIN: 'exadmin',
  EXOWNER: 'exowner',
  EXOUTCAST: 'exoutcast',
  EXMEMBER: 'exmember'
};
var AFFILIATION_CHANGES_LIST = Object.values(AFFILIATION_CHANGES);
var MUC_TRAFFIC_STATES = {
  ENTERED: 'entered',
  EXITED: 'exited'
};
var MUC_TRAFFIC_STATES_LIST = Object.values(MUC_TRAFFIC_STATES);
var MUC_ROLE_CHANGES = {
  OP: 'op',
  DEOP: 'deop',
  VOICE: 'voice',
  MUTE: 'mute'
};
var MUC_ROLE_CHANGES_LIST = Object.values(MUC_ROLE_CHANGES);
var INFO_CODES = {
  'visibility_changes': ['100', '102', '103', '172', '173', '174'],
  'self': ['110'],
  'non_privacy_changes': ['104', '201'],
  'muc_logging_changes': ['170', '171'],
  'nickname_changes': ['210', '303'],
  'disconnected': ['301', '307', '321', '322', '332', '333'],
  'affiliation_changes': [].concat(AFFILIATION_CHANGES_LIST),
  'join_leave_events': [].concat(MUC_TRAFFIC_STATES_LIST),
  'role_changes': [].concat(MUC_ROLE_CHANGES_LIST)
};
var ROOMSTATUS = {
  CONNECTED: 0,
  CONNECTING: 1,
  NICKNAME_REQUIRED: 2,
  PASSWORD_REQUIRED: 3,
  DISCONNECTED: 4,
  ENTERED: 5,
  DESTROYED: 6,
  BANNED: 7,
  CLOSING: 8
};
var ROOM_FEATURES = ['passwordprotected', 'unsecured', 'hidden', 'publicroom', 'membersonly', 'open', 'persistent', 'temporary', 'nonanonymous', 'semianonymous', 'moderated', 'unmoderated', 'mam_enabled'];
var MUC_NICK_CHANGED_CODE = '303';

// No longer used in code, but useful as reference.
//
// const ROOM_FEATURES_MAP = {
//     'passwordprotected': 'unsecured',
//     'unsecured': 'passwordprotected',
//     'hidden': 'publicroom',
//     'publicroom': 'hidden',
//     'membersonly': 'open',
//     'open': 'membersonly',
//     'persistent': 'temporary',
//     'temporary': 'persistent',
//     'nonanonymous': 'semianonymous',
//     'semianonymous': 'nonanonymous',
//     'moderated': 'unmoderated',
//     'unmoderated': 'moderated'
// };
;// CONCATENATED MODULE: ./src/headless/plugins/muc/parsers.js
function muc_parsers_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_parsers_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;
  }, muc_parsers_typeof(obj);
}
function muc_parsers_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_parsers_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" == muc_parsers_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 muc_parsers_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 muc_parsers_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_parsers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_parsers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var parsers_converse$env = public_converse.env,
  parsers_Strophe = parsers_converse$env.Strophe,
  muc_parsers_sizzle = parsers_converse$env.sizzle,
  parsers_u = parsers_converse$env.u;
var parsers_NS = parsers_Strophe.NS;

/**
 * Parses a message stanza for XEP-0317 MEP notification data
 * @param { Element } stanza - The message stanza
 * @returns { Array } Returns an array of objects representing <activity> elements.
 */
function getMEPActivities(stanza) {
  var items_el = muc_parsers_sizzle("items[node=\"".concat(parsers_Strophe.NS.CONFINFO, "\"]"), stanza).pop();
  if (!items_el) {
    return null;
  }
  var from = stanza.getAttribute('from');
  var msgid = stanza.getAttribute('id');
  var selector = "item " + "conference-info[xmlns=\"".concat(parsers_Strophe.NS.CONFINFO, "\"] ") + "activity[xmlns=\"".concat(parsers_Strophe.NS.ACTIVITY, "\"]");
  return muc_parsers_sizzle(selector, items_el).map(function (el) {
    var _el$querySelector;
    var message = (_el$querySelector = el.querySelector('text')) === null || _el$querySelector === void 0 ? void 0 : _el$querySelector.textContent;
    if (message) {
      var _el$querySelector2;
      var references = getReferences(stanza);
      var reason = (_el$querySelector2 = el.querySelector('reason')) === null || _el$querySelector2 === void 0 ? void 0 : _el$querySelector2.textContent;
      return {
        from: from,
        msgid: msgid,
        message: message,
        reason: reason,
        references: references,
        'type': 'mep'
      };
    }
    return {};
  });
}

/**
 * Given a MUC stanza, check whether it has extended message information that
 * includes the sender's real JID, as described here:
 * https://xmpp.org/extensions/xep-0313.html#business-storeret-muc-archives
 *
 * If so, parse and return that data and return the user's JID
 *
 * Note, this function doesn't check whether this is actually a MAM archived stanza.
 *
 * @private
 * @param { Element } stanza - The message stanza
 * @returns { Object }
 */
function getJIDFromMUCUserData(stanza) {
  var item = muc_parsers_sizzle("x[xmlns=\"".concat(parsers_Strophe.NS.MUC_USER, "\"] item"), stanza).pop();
  return item === null || item === void 0 ? void 0 : item.getAttribute('jid');
}

/**
 * @private
 * @param { Element } stanza - The message stanza
 * @param { Element } original_stanza - The original stanza, that contains the
 *  message stanza, if it was contained, otherwise it's the message stanza itself.
 * @returns { Object }
 */
function getModerationAttributes(stanza) {
  var fastening = muc_parsers_sizzle("apply-to[xmlns=\"".concat(parsers_Strophe.NS.FASTEN, "\"]"), stanza).pop();
  if (fastening) {
    var applies_to_id = fastening.getAttribute('id');
    var moderated = muc_parsers_sizzle("moderated[xmlns=\"".concat(parsers_Strophe.NS.MODERATE, "\"]"), fastening).pop();
    if (moderated) {
      var retracted = muc_parsers_sizzle("retract[xmlns=\"".concat(parsers_Strophe.NS.RETRACT, "\"]"), moderated).pop();
      if (retracted) {
        var _moderated$querySelec;
        return {
          'editable': false,
          'moderated': 'retracted',
          'moderated_by': moderated.getAttribute('by'),
          'moderated_id': applies_to_id,
          'moderation_reason': (_moderated$querySelec = moderated.querySelector('reason')) === null || _moderated$querySelec === void 0 ? void 0 : _moderated$querySelec.textContent
        };
      }
    }
  } else {
    var tombstone = muc_parsers_sizzle("> moderated[xmlns=\"".concat(parsers_Strophe.NS.MODERATE, "\"]"), stanza).pop();
    if (tombstone) {
      var _retracted = muc_parsers_sizzle("retracted[xmlns=\"".concat(parsers_Strophe.NS.RETRACT, "\"]"), tombstone).pop();
      if (_retracted) {
        var _tombstone$querySelec;
        return {
          'editable': false,
          'is_tombstone': true,
          'moderated_by': tombstone.getAttribute('by'),
          'retracted': tombstone.getAttribute('stamp'),
          'moderation_reason': (_tombstone$querySelec = tombstone.querySelector('reason')) === null || _tombstone$querySelec === void 0 ? void 0 : _tombstone$querySelec.textContent
        };
      }
    }
  }
  return {};
}
function getOccupantID(stanza, chatbox) {
  if (chatbox.features.get(parsers_Strophe.NS.OCCUPANTID)) {
    var _sizzle$pop;
    return (_sizzle$pop = muc_parsers_sizzle("occupant-id[xmlns=\"".concat(parsers_Strophe.NS.OCCUPANTID, "\"]"), stanza).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.getAttribute('id');
  }
}

/**
 * Determines whether the sender of this MUC message is the current user or
 * someone else.
 * @param { MUCMessageAttributes } attrs
 * @param { _converse.ChatRoom } chatbox
 * @returns { 'me'|'them' }
 */
function getSender(attrs, chatbox) {
  var is_me;
  var own_occupant_id = chatbox.get('occupant_id');
  if (own_occupant_id) {
    is_me = attrs.occupant_id === own_occupant_id;
  } else if (attrs.from_real_jid) {
    is_me = parsers_Strophe.getBareJidFromJid(attrs.from_real_jid) === shared_converse.bare_jid;
  } else {
    is_me = attrs.nick === chatbox.get('nick');
  }
  return is_me ? 'me' : 'them';
}

/**
 * Parses a passed in message stanza and returns an object of attributes.
 * @param { Element } stanza - The message stanza
 * @param { Element } original_stanza - The original stanza, that contains the
 *  message stanza, if it was contained, otherwise it's the message stanza itself.
 * @param { _converse.ChatRoom } chatbox
 * @param { _converse } _converse
 * @returns { Promise<MUCMessageAttributes|Error> }
 */
function parseMUCMessage(_x, _x2) {
  return _parseMUCMessage.apply(this, arguments);
}

/**
 * Given an IQ stanza with a member list, create an array of objects containing
 * known member data (e.g. jid, nick, role, affiliation).
 * @private
 * @method muc_utils#parseMemberListIQ
 * @returns { MemberListItem[] }
 */
function _parseMUCMessage() {
  _parseMUCMessage = muc_parsers_asyncToGenerator( /*#__PURE__*/muc_parsers_regeneratorRuntime().mark(function _callee(stanza, chatbox) {
    var _stanza$querySelector, _stanza$querySelector2, _stanza$querySelector3, _stanza$querySelector4, _chatbox$occupants$fi;
    var selector, original_stanza, delay, from, marker, attrs;
    return muc_parsers_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          throwErrorIfInvalidForward(stanza);
          selector = "[xmlns=\"".concat(parsers_NS.MAM, "\"] > forwarded[xmlns=\"").concat(parsers_NS.FORWARD, "\"] > message");
          original_stanza = stanza;
          stanza = muc_parsers_sizzle(selector, stanza).pop() || stanza;
          if (!muc_parsers_sizzle("message > forwarded[xmlns=\"".concat(parsers_Strophe.NS.FORWARD, "\"]"), stanza).length) {
            _context.next = 6;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Invalid Stanza: Forged MAM groupchat message from ".concat(stanza.getAttribute('from')), stanza));
        case 6:
          delay = muc_parsers_sizzle("delay[xmlns=\"".concat(parsers_Strophe.NS.DELAY, "\"]"), original_stanza).pop();
          from = stanza.getAttribute('from');
          marker = getChatMarker(stanza);
          /**
           * @typedef { Object } MUCMessageAttributes
           * The object which {@link parseMUCMessage} returns
           * @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
           * @property { Array<Object> } activities - A list of objects representing XEP-0316 MEP notification data
           * @property { Array<Object> } references - A list of objects representing XEP-0372 references
           * @property { Boolean } editable - Is this message editable via XEP-0308?
           * @property { Boolean } is_archived -  Is this message from a XEP-0313 MAM archive?
           * @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
           * @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
           * @property { Boolean } is_encrypted -  Is this message XEP-0384  encrypted?
           * @property { Boolean } is_error - Whether an error was received for this message
           * @property { Boolean } is_headline - Is this a "headline" message?
           * @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
           * @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
           * @property { Boolean } is_only_emojis - Does the message body contain only emojis?
           * @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
           * @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
           * @property { Boolean } is_unstyled - Whether XEP-0393 styling hints should be ignored
           * @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
           * @property { Object } encrypted -  XEP-0384 encryption payload attributes
           * @property { String } body - The contents of the <body> tag of the message stanza
           * @property { String } chat_state - The XEP-0085 chat state notification contained in this message
           * @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
           * @property { String } error_condition - The defined error condition
           * @property { String } error_text - The error text received from the server
           * @property { String } error_type - The type of error received from the server
           * @property { String } from - The sender JID (${muc_jid}/${nick})
           * @property { String } from_muc - The JID of the MUC from which this message was sent
           * @property { String } from_real_jid - The real JID of the sender, if available
           * @property { String } fullname - The full name of the sender
           * @property { String } marker - The XEP-0333 Chat Marker value
           * @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
           * @property { String } moderated - The type of XEP-0425 moderation (if any) that was applied
           * @property { String } moderated_by - The JID of the user that moderated this message
           * @property { String } moderated_id - The  XEP-0359 Stanza ID of the message that this one moderates
           * @property { String } moderation_reason - The reason provided why this message moderates another
           * @property { String } msgid - The root `id` attribute of the stanza
           * @property { String } nick - The MUC nickname of the sender
           * @property { String } occupant_id - The XEP-0421 occupant ID
           * @property { String } oob_desc - The description of the XEP-0066 out of band data
           * @property { String } oob_url - The URL of the XEP-0066 out of band data
           * @property { String } origin_id - The XEP-0359 Origin ID
           * @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
           * @property { String } received - An ISO8601 string recording the time that the message was received
           * @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
           * @property { String } retracted - An ISO8601 string recording the time that the message was retracted
           * @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
           * @property { String } spoiler_hint  The XEP-0382 spoiler hint
           * @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
           * @property { String } subject - The <subject> element value
           * @property { String } thread - The <thread> element value
           * @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
           * @property { String } to - The recipient JID
           * @property { String } type - The type of message
           */
          attrs = Object.assign({
            from: from,
            'activities': getMEPActivities(stanza),
            'body': (_stanza$querySelector = stanza.querySelector(':scope > body')) === null || _stanza$querySelector === void 0 ? void 0 : (_stanza$querySelector2 = _stanza$querySelector.textContent) === null || _stanza$querySelector2 === void 0 ? void 0 : _stanza$querySelector2.trim(),
            'chat_state': getChatState(stanza),
            'from_muc': parsers_Strophe.getBareJidFromJid(from),
            'is_archived': isArchived(original_stanza),
            'is_carbon': isCarbon(original_stanza),
            'is_delayed': !!delay,
            'is_forwarded': !!stanza.querySelector('forwarded'),
            'is_headline': isHeadline(stanza),
            'is_markable': !!muc_parsers_sizzle("markable[xmlns=\"".concat(parsers_Strophe.NS.MARKERS, "\"]"), stanza).length,
            'is_marker': !!marker,
            'is_unstyled': !!muc_parsers_sizzle("unstyled[xmlns=\"".concat(parsers_Strophe.NS.STYLING, "\"]"), stanza).length,
            'marker_id': marker && marker.getAttribute('id'),
            'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
            'nick': parsers_Strophe.unescapeNode(parsers_Strophe.getResourceFromJid(from)),
            'occupant_id': getOccupantID(stanza, chatbox),
            'receipt_id': getReceiptId(stanza),
            'received': new Date().toISOString(),
            'references': getReferences(stanza),
            'subject': (_stanza$querySelector3 = stanza.querySelector('subject')) === null || _stanza$querySelector3 === void 0 ? void 0 : _stanza$querySelector3.textContent,
            'thread': (_stanza$querySelector4 = stanza.querySelector('thread')) === null || _stanza$querySelector4 === void 0 ? void 0 : _stanza$querySelector4.textContent,
            'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString(),
            'to': stanza.getAttribute('to'),
            'type': stanza.getAttribute('type')
          }, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getOpenGraphMetadata(stanza), getRetractionAttributes(stanza, original_stanza), getModerationAttributes(stanza), getEncryptionAttributes(stanza, shared_converse));
          _context.next = 12;
          return shared_api.emojis.initialize();
        case 12:
          attrs.from_real_jid = attrs.is_archived && getJIDFromMUCUserData(stanza) || ((_chatbox$occupants$fi = chatbox.occupants.findOccupant(attrs)) === null || _chatbox$occupants$fi === void 0 ? void 0 : _chatbox$occupants$fi.get('jid'));
          attrs = Object.assign({
            'is_only_emojis': attrs.body ? parsers_u.isOnlyEmojis(attrs.body) : false,
            'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs),
            'message': attrs.body || attrs.error,
            // TODO: Should only be used for error and info messages
            'sender': getSender(attrs, chatbox)
          }, attrs);
          if (!(attrs.is_archived && original_stanza.getAttribute('from') !== attrs.from_muc)) {
            _context.next = 18;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Invalid Stanza: Forged MAM message from ".concat(original_stanza.getAttribute('from')), stanza));
        case 18:
          if (!(attrs.is_archived && original_stanza.getAttribute('from') !== chatbox.get('jid'))) {
            _context.next = 22;
            break;
          }
          return _context.abrupt("return", new StanzaParseError("Invalid Stanza: Forged MAM groupchat message from ".concat(stanza.getAttribute('from')), stanza));
        case 22:
          if (!attrs.is_carbon) {
            _context.next = 24;
            break;
          }
          return _context.abrupt("return", new StanzaParseError('Invalid Stanza: MUC messages SHOULD NOT be XEP-0280 carbon copied', stanza));
        case 24:
          // We prefer to use one of the XEP-0359 unique and stable stanza IDs as the Model id, to avoid duplicates.
          attrs['id'] = attrs['origin_id'] || attrs["stanza_id ".concat(attrs.from_muc || attrs.from)] || parsers_u.getUniqueId();

          /**
           * *Hook* which allows plugins to add additional parsing
           * @event _converse#parseMUCMessage
           */
          _context.next = 27;
          return shared_api.hook('parseMUCMessage', stanza, attrs);
        case 27:
          attrs = _context.sent;
          return _context.abrupt("return", Object.assign(attrs, getMediaURLsMetadata(attrs.is_encrypted ? attrs.plaintext : attrs.body)));
        case 29:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _parseMUCMessage.apply(this, arguments);
}
function parseMemberListIQ(iq) {
  return muc_parsers_sizzle("query[xmlns=\"".concat(parsers_Strophe.NS.MUC_ADMIN, "\"] item"), iq).map(function (item) {
    /**
     * @typedef {Object} MemberListItem
     * Either the JID or the nickname (or both) will be available.
     * @property {string} affiliation
     * @property {string} [role]
     * @property {string} [jid]
     * @property {string} [nick]
     */
    var data = {
      'affiliation': item.getAttribute('affiliation')
    };
    var jid = item.getAttribute('jid');
    if (parsers_u.isValidJID(jid)) {
      data['jid'] = jid;
    } else {
      // XXX: Prosody sends nick for the jid attribute value
      // Perhaps for anonymous room?
      data['nick'] = jid;
    }
    var nick = item.getAttribute('nick');
    if (nick) {
      data['nick'] = nick;
    }
    var role = item.getAttribute('role');
    if (role) {
      data['role'] = nick;
    }
    return data;
  });
}

/**
 * Parses a passed in MUC presence stanza and returns an object of attributes.
 * @method parseMUCPresence
 * @param { Element } stanza - The presence stanza
 * @param { _converse.ChatRoom } chatbox
 * @returns { MUCPresenceAttributes }
 */
function parseMUCPresence(stanza, chatbox) {
  /**
   * @typedef { Object } MUCPresenceAttributes
   * The object which {@link parseMUCPresence} returns
   * @property { ("offline|online") } show
   * @property { Array<MUCHat> } hats - An array of XEP-0317 hats
   * @property { Array<string> } states
   * @property { String } from - The sender JID (${muc_jid}/${nick})
   * @property { String } nick - The nickname of the sender
   * @property { String } occupant_id - The XEP-0421 occupant ID
   * @property { String } type - The type of presence
   */
  var from = stanza.getAttribute('from');
  var type = stanza.getAttribute('type');
  var data = {
    'is_me': !!stanza.querySelector("status[code='110']"),
    'from': from,
    'occupant_id': getOccupantID(stanza, chatbox),
    'nick': parsers_Strophe.getResourceFromJid(from),
    'type': type,
    'states': [],
    'hats': [],
    'show': type !== 'unavailable' ? 'online' : 'offline'
  };
  Array.from(stanza.children).forEach(function (child) {
    if (child.matches('status')) {
      data.status = child.textContent || null;
    } else if (child.matches('show')) {
      data.show = child.textContent || 'online';
    } else if (child.matches('x') && child.getAttribute('xmlns') === parsers_Strophe.NS.MUC_USER) {
      Array.from(child.children).forEach(function (item) {
        if (item.nodeName === 'item') {
          data.affiliation = item.getAttribute('affiliation');
          data.role = item.getAttribute('role');
          data.jid = item.getAttribute('jid');
          data.nick = item.getAttribute('nick') || data.nick;
        } else if (item.nodeName == 'status' && item.getAttribute('code')) {
          data.states.push(item.getAttribute('code'));
        }
      });
    } else if (child.matches('x') && child.getAttribute('xmlns') === parsers_Strophe.NS.VCARDUPDATE) {
      var _child$querySelector;
      data.image_hash = (_child$querySelector = child.querySelector('photo')) === null || _child$querySelector === void 0 ? void 0 : _child$querySelector.textContent;
    } else if (child.matches('hats') && child.getAttribute('xmlns') === parsers_Strophe.NS.MUC_HATS) {
      /**
       * @typedef { Object } MUCHat
       * Object representing a XEP-0371 Hat
       * @property { String } title
       * @property { String } uri
       */
      data['hats'] = Array.from(child.children).map(function (c) {
        return c.matches('hat') && {
          'title': c.getAttribute('title'),
          'uri': c.getAttribute('uri')
        };
      });
    }
  });
  return data;
}
;// CONCATENATED MODULE: ./src/headless/plugins/muc/affiliations/utils.js
function affiliations_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return affiliations_utils_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;
  }, affiliations_utils_typeof(obj);
}
function affiliations_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  affiliations_utils_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" == affiliations_utils_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 affiliations_utils_toConsumableArray(arr) {
  return affiliations_utils_arrayWithoutHoles(arr) || affiliations_utils_iterableToArray(arr) || affiliations_utils_unsupportedIterableToArray(arr) || affiliations_utils_nonIterableSpread();
}
function affiliations_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function affiliations_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return affiliations_utils_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 affiliations_utils_arrayLikeToArray(o, minLen);
}
function affiliations_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function affiliations_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return affiliations_utils_arrayLikeToArray(arr);
}
function affiliations_utils_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 affiliations_utils_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 affiliations_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        affiliations_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        affiliations_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






var affiliations_utils_converse$env = public_converse.env,
  affiliations_utils_Strophe = affiliations_utils_converse$env.Strophe,
  utils_$iq = affiliations_utils_converse$env.$iq,
  affiliations_utils_u = affiliations_utils_converse$env.u;

/**
 * Sends an IQ stanza to the server, asking it for the relevant affiliation list .
 * Returns an array of {@link MemberListItem} objects, representing occupants
 * that have the given affiliation.
 * See: https://xmpp.org/extensions/xep-0045.html#modifymember
 * @param { ("admin"|"owner"|"member") } affiliation
 * @param { String } muc_jid - The JID of the MUC for which the affiliation list should be fetched
 * @returns { Promise<MemberListItem[]> }
 */
function getAffiliationList(_x, _x2) {
  return _getAffiliationList.apply(this, arguments);
}

/**
 * Given an occupant model, see which affiliations may be assigned by that user
 * @param { Model } occupant
 * @returns { Array<('owner'|'admin'|'member'|'outcast'|'none')> } - An array of assignable affiliations
 */
function _getAffiliationList() {
  _getAffiliationList = affiliations_utils_asyncToGenerator( /*#__PURE__*/affiliations_utils_regeneratorRuntime().mark(function _callee(affiliation, muc_jid) {
    var __, iq, result, err_msg, err, _err_msg, _err;
    return affiliations_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          __ = shared_converse.__;
          iq = utils_$iq({
            'to': muc_jid,
            'type': 'get'
          }).c('query', {
            xmlns: affiliations_utils_Strophe.NS.MUC_ADMIN
          }).c('item', {
            'affiliation': affiliation
          });
          _context.next = 4;
          return shared_api.sendIQ(iq, null, false);
        case 4:
          result = _context.sent;
          if (!(result === null)) {
            _context.next = 10;
            break;
          }
          err_msg = __('Error: timeout while fetching %1s list for MUC %2s', affiliation, muc_jid);
          err = new Error(err_msg);
          log.warn(err_msg);
          return _context.abrupt("return", err);
        case 10:
          if (!affiliations_utils_u.isErrorStanza(result)) {
            _context.next = 16;
            break;
          }
          _err_msg = __('Error: not allowed to fetch %1s list for MUC %2s', affiliation, muc_jid);
          _err = new Error(_err_msg);
          log.warn(_err_msg);
          log.warn(result);
          return _context.abrupt("return", _err);
        case 16:
          return _context.abrupt("return", parseMemberListIQ(result).filter(function (p) {
            return p;
          }).sort(function (a, b) {
            return a.nick < b.nick ? -1 : a.nick > b.nick ? 1 : 0;
          }));
        case 17:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _getAffiliationList.apply(this, arguments);
}
function getAssignableAffiliations(occupant) {
  var disabled = shared_api.settings.get('modtools_disable_assign');
  if (!Array.isArray(disabled)) {
    disabled = disabled ? muc_AFFILIATIONS : [];
  }
  if ((occupant === null || occupant === void 0 ? void 0 : occupant.get('affiliation')) === 'owner') {
    return muc_AFFILIATIONS.filter(function (a) {
      return !disabled.includes(a);
    });
  } else if ((occupant === null || occupant === void 0 ? void 0 : occupant.get('affiliation')) === 'admin') {
    return muc_AFFILIATIONS.filter(function (a) {
      return !['owner', 'admin'].concat(affiliations_utils_toConsumableArray(disabled)).includes(a);
    });
  } else {
    return [];
  }
}

// Necessary for tests
shared_converse.getAssignableAffiliations = getAssignableAffiliations;

/**
 * Send IQ stanzas to the server to modify affiliations for users in this groupchat.
 * See: https://xmpp.org/extensions/xep-0045.html#modifymember
 * @param { Array<Object> } users
 * @param { string } users[].jid - The JID of the user whose affiliation will change
 * @param { Array } users[].affiliation - The new affiliation for this user
 * @param { string } [users[].reason] - An optional reason for the affiliation change
 * @returns { Promise }
 */
function setAffiliations(muc_jid, users) {
  var affiliations = affiliations_utils_toConsumableArray(new Set(users.map(function (u) {
    return u.affiliation;
  })));
  return Promise.all(affiliations.map(function (a) {
    return setAffiliation(a, muc_jid, users);
  }));
}

/**
 * Send IQ stanzas to the server to set an affiliation for
 * the provided JIDs.
 * See: https://xmpp.org/extensions/xep-0045.html#modifymember
 *
 * Prosody doesn't accept multiple JIDs' affiliations
 * being set in one IQ stanza, so as a workaround we send
 * a separate stanza for each JID.
 * Related ticket: https://issues.prosody.im/345
 *
 * @param { ('outcast'|'member'|'admin'|'owner') } affiliation - The affiliation to be set
 * @param { String|Array<String> } jids - The JID(s) of the MUCs in which the
 *  affiliations need to be set.
 * @param { object } members - A map of jids, affiliations and
 *  optionally reasons. Only those entries with the
 *  same affiliation as being currently set will be considered.
 * @returns { Promise } A promise which resolves and fails depending on the XMPP server response.
 */
function setAffiliation(affiliation, muc_jids, members) {
  if (!Array.isArray(muc_jids)) {
    muc_jids = [muc_jids];
  }
  members = members.filter(function (m) {
    return [undefined, affiliation].includes(m.affiliation);
  });
  return Promise.all(muc_jids.reduce(function (acc, jid) {
    return [].concat(affiliations_utils_toConsumableArray(acc), affiliations_utils_toConsumableArray(members.map(function (m) {
      return sendAffiliationIQ(affiliation, jid, m);
    })));
  }, []));
}

/**
 * Send an IQ stanza specifying an affiliation change.
 * @private
 * @param { String } affiliation: affiliation (could also be stored on the member object).
 * @param { String } muc_jid: The JID of the MUC in which the affiliation should be set.
 * @param { Object } member: Map containing the member's jid and optionally a reason and affiliation.
 */
function sendAffiliationIQ(affiliation, muc_jid, member) {
  var iq = utils_$iq({
    to: muc_jid,
    type: 'set'
  }).c('query', {
    xmlns: affiliations_utils_Strophe.NS.MUC_ADMIN
  }).c('item', {
    'affiliation': member.affiliation || affiliation,
    'nick': member.nick,
    'jid': member.jid
  });
  if (member.reason !== undefined) {
    iq.c('reason', member.reason);
  }
  return shared_api.sendIQ(iq);
}

/**
 * Given two lists of objects with 'jid', 'affiliation' and
 * 'reason' properties, return a new list containing
 * those objects that are new, changed or removed
 * (depending on the 'remove_absentees' boolean).
 *
 * The affiliations for new and changed members stay the
 * same, for removed members, the affiliation is set to 'none'.
 *
 * The 'reason' property is not taken into account when
 * comparing whether affiliations have been changed.
 * @param { boolean } exclude_existing - Indicates whether JIDs from
 *      the new list which are also in the old list
 *      (regardless of affiliation) should be excluded
 *      from the delta. One reason to do this
 *      would be when you want to add a JID only if it
 *      doesn't have *any* existing affiliation at all.
 * @param { boolean } remove_absentees - Indicates whether JIDs
 *      from the old list which are not in the new list
 *      should be considered removed and therefore be
 *      included in the delta with affiliation set
 *      to 'none'.
 * @param { array } new_list - Array containing the new affiliations
 * @param { array } old_list - Array containing the old affiliations
 * @returns { array }
 */
function computeAffiliationsDelta(exclude_existing, remove_absentees, new_list, old_list) {
  var new_jids = new_list.map(function (o) {
    return o.jid;
  });
  var old_jids = old_list.map(function (o) {
    return o.jid;
  });
  // Get the new affiliations
  var delta = lodash_es_difference(new_jids, old_jids).map(function (jid) {
    return new_list[lodash_es_indexOf(new_jids, jid)];
  });
  if (!exclude_existing) {
    // Get the changed affiliations
    delta = delta.concat(new_list.filter(function (item) {
      var idx = lodash_es_indexOf(old_jids, item.jid);
      return idx >= 0 ? item.affiliation !== old_list[idx].affiliation : false;
    }));
  }
  if (remove_absentees) {
    // Get the removed affiliations
    delta = delta.concat(lodash_es_difference(old_jids, new_jids).map(function (jid) {
      return {
        'jid': jid,
        'affiliation': 'none'
      };
    }));
  }
  return delta;
}
;// CONCATENATED MODULE: ./src/headless/plugins/muc/muc.js
function muc_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_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;
  }, muc_typeof(obj);
}
function muc_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 muc_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? muc_ownKeys(Object(source), !0).forEach(function (key) {
      muc_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : muc_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function muc_defineProperty(obj, key, value) {
  key = muc_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 muc_toPropertyKey(arg) {
  var key = muc_toPrimitive(arg, "string");
  return muc_typeof(key) === "symbol" ? key : String(key);
}
function muc_toPrimitive(input, hint) {
  if (muc_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_slicedToArray(arr, i) {
  return muc_arrayWithHoles(arr) || muc_iterableToArrayLimit(arr, i) || muc_unsupportedIterableToArray(arr, i) || muc_nonIterableRest();
}
function muc_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function muc_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function muc_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function muc_toConsumableArray(arr) {
  return muc_arrayWithoutHoles(arr) || muc_iterableToArray(arr) || muc_unsupportedIterableToArray(arr) || muc_nonIterableSpread();
}
function muc_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function muc_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return muc_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 muc_arrayLikeToArray(o, minLen);
}
function muc_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function muc_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return muc_arrayLikeToArray(arr);
}
function muc_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 muc_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_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" == muc_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 muc_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 muc_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



















var muc_u = public_converse.env.u;
var OWNER_COMMANDS = ['owner'];
var ADMIN_COMMANDS = ['admin', 'ban', 'deop', 'destroy', 'member', 'op', 'revoke'];
var MODERATOR_COMMANDS = ['kick', 'mute', 'voice', 'modtools'];
var VISITOR_COMMANDS = ['nick'];
var METADATA_ATTRIBUTES = ["og:article:author", "og:article:published_time", "og:description", "og:image", "og:image:height", "og:image:width", "og:site_name", "og:title", "og:type", "og:url", "og:video:height", "og:video:secure_url", "og:video:tag", "og:video:type", "og:video:url", "og:video:width"];
var ACTION_INFO_CODES = ['301', '303', '333', '307', '321', '322'];
var MUCSession = Model.extend({
  defaults: function defaults() {
    return {
      'connection_status': ROOMSTATUS.DISCONNECTED
    };
  }
});

/**
 * Represents an open/ongoing groupchat conversation.
 * @mixin
 * @namespace _converse.ChatRoom
 * @memberOf _converse
 */
var ChatRoomMixin = {
  defaults: function defaults() {
    return {
      'bookmarked': false,
      'chat_state': undefined,
      'has_activity': false,
      // XEP-437
      'hidden': isUniView() && !shared_api.settings.get('singleton'),
      'hidden_occupants': !!shared_api.settings.get('hide_muc_participants'),
      'message_type': 'groupchat',
      'name': '',
      // For group chats, we distinguish between generally unread
      // messages and those ones that specifically mention the
      // user.
      //
      // To keep things simple, we reuse `num_unread` from
      // _converse.ChatBox to indicate unread messages which
      // mention the user and `num_unread_general` to indicate
      // generally unread messages (which *includes* mentions!).
      'num_unread_general': 0,
      'num_unread': 0,
      'roomconfig': {},
      'time_opened': this.get('time_opened') || new Date().getTime(),
      'time_sent': new Date(0).toISOString(),
      'type': shared_converse.CHATROOMS_TYPE
    };
  },
  initialize: function initialize() {
    var _this = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee() {
      var restored;
      return muc_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.initialized = getOpenPromise();
            _this.debouncedRejoin = lodash_es_debounce(_this.rejoin, 250);
            _this.set('box_id', "box-".concat(_this.get('jid')));
            _this.initNotifications();
            _this.initMessages();
            _this.initUI();
            _this.initOccupants();
            _this.initDiscoModels(); // sendChatState depends on this.features
            _this.registerHandlers();
            _this.on('change:chat_state', _this.sendChatState, _this);
            _this.on('change:hidden', _this.onHiddenChange, _this);
            _this.on('destroy', _this.removeHandlers, _this);
            _this.ui.on('change:scrolled', _this.onScrolledChanged, _this);
            _context.next = 15;
            return _this.restoreSession();
          case 15:
            _this.session.on('change:connection_status', _this.onConnectionStatusChanged, _this);
            _this.listenTo(_this.occupants, 'add', _this.onOccupantAdded);
            _this.listenTo(_this.occupants, 'remove', _this.onOccupantRemoved);
            _this.listenTo(_this.occupants, 'change:show', _this.onOccupantShowChanged);
            _this.listenTo(_this.occupants, 'change:affiliation', _this.createAffiliationChangeMessage);
            _this.listenTo(_this.occupants, 'change:role', _this.createRoleChangeMessage);
            _context.next = 23;
            return _this.restoreFromCache();
          case 23:
            restored = _context.sent;
            if (!restored) {
              _this.join();
            }
            /**
             * Triggered once a {@link _converse.ChatRoom} has been created and initialized.
             * @event _converse#chatRoomInitialized
             * @type { _converse.ChatRoom }
             * @example _converse.api.listen.on('chatRoomInitialized', model => { ... });
             */
            _context.next = 27;
            return shared_api.trigger('chatRoomInitialized', _this, {
              'Synchronous': true
            });
          case 27:
            _this.initialized.resolve();
          case 28:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  isEntered: function isEntered() {
    return this.session.get('connection_status') === ROOMSTATUS.ENTERED;
  },
  /**
   * Checks whether this MUC qualifies for subscribing to XEP-0437 Room Activity Indicators (RAI)
   * @method _converse.ChatRoom#isRAICandidate
   * @returns { Boolean }
   */
  isRAICandidate: function isRAICandidate() {
    return this.get('hidden') && shared_api.settings.get('muc_subscribe_to_rai') && this.getOwnAffiliation() !== 'none';
  },
  /**
   * Checks whether we're still joined and if so, restores the MUC state from cache.
   * @private
   * @method _converse.ChatRoom#restoreFromCache
   * @returns { Boolean } Returns `true` if we're still joined, otherwise returns `false`.
   */
  restoreFromCache: function restoreFromCache() {
    var _this2 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee2() {
      return muc_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            if (!_this2.isEntered()) {
              _context2.next = 19;
              break;
            }
            _context2.next = 3;
            return _this2.fetchOccupants().catch(function (e) {
              return log.error(e);
            });
          case 3:
            if (!_this2.isRAICandidate()) {
              _context2.next = 9;
              break;
            }
            _this2.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
            _this2.enableRAI();
            return _context2.abrupt("return", true);
          case 9:
            _context2.next = 11;
            return _this2.isJoined();
          case 11:
            if (!_context2.sent) {
              _context2.next = 19;
              break;
            }
            _context2.next = 14;
            return new Promise(function (r) {
              return _this2.config.fetch({
                'success': r,
                'error': r
              });
            });
          case 14:
            _context2.next = 16;
            return new Promise(function (r) {
              return _this2.features.fetch({
                'success': r,
                'error': r
              });
            });
          case 16:
            _context2.next = 18;
            return _this2.fetchMessages().catch(function (e) {
              return log.error(e);
            });
          case 18:
            return _context2.abrupt("return", true);
          case 19:
            _this2.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
            _this2.clearOccupantsCache();
            return _context2.abrupt("return", false);
          case 22:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  /**
   * Join the MUC
   * @private
   * @method _converse.ChatRoom#join
   * @param { String } nick - The user's nickname
   * @param { String } [password] - Optional password, if required by the groupchat.
   *  Will fall back to the `password` value stored in the room
   *  model (if available).
   */
  join: function join(nick, password) {
    var _this3 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee3() {
      return muc_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            if (!_this3.isEntered()) {
              _context3.next = 2;
              break;
            }
            return _context3.abrupt("return", _this3);
          case 2:
            // Set this early, so we don't rejoin in onHiddenChange
            _this3.session.save('connection_status', ROOMSTATUS.CONNECTING);
            _context3.next = 5;
            return _this3.refreshDiscoInfo();
          case 5:
            _context3.next = 7;
            return _this3.getAndPersistNickname(nick);
          case 7:
            nick = _context3.sent;
            if (nick) {
              _context3.next = 14;
              break;
            }
            safeSave(_this3.session, {
              'connection_status': ROOMSTATUS.NICKNAME_REQUIRED
            });
            if (!shared_api.settings.get('muc_show_logs_before_join')) {
              _context3.next = 13;
              break;
            }
            _context3.next = 13;
            return _this3.fetchMessages();
          case 13:
            return _context3.abrupt("return", _this3);
          case 14:
            _context3.t0 = shared_api;
            _context3.next = 17;
            return _this3.constructJoinPresence(password);
          case 17:
            _context3.t1 = _context3.sent;
            _context3.t0.send.call(_context3.t0, _context3.t1);
            return _context3.abrupt("return", _this3);
          case 20:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  },
  /**
   * Clear stale cache and re-join a MUC we've been in before.
   * @private
   * @method _converse.ChatRoom#rejoin
   */
  rejoin: function rejoin() {
    this.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
    this.registerHandlers();
    this.clearOccupantsCache();
    return this.join();
  },
  constructJoinPresence: function constructJoinPresence(password) {
    var _this4 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee4() {
      var stanza;
      return muc_regeneratorRuntime().wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            stanza = (0,external_strophe_namespaceObject.$pres)({
              'id': getUniqueId(),
              'from': shared_converse.connection.jid,
              'to': _this4.getRoomJIDAndNick()
            }).c('x', {
              'xmlns': external_strophe_namespaceObject.Strophe.NS.MUC
            }).c('history', {
              'maxstanzas': _this4.features.get('mam_enabled') ? 0 : shared_api.settings.get('muc_history_max_stanzas')
            }).up();
            password = password || _this4.get('password');
            if (password) {
              stanza.cnode(external_strophe_namespaceObject.Strophe.xmlElement('password', [], password));
            }
            stanza.up(); // Go one level up, out of the `x` element.
            /**
             * *Hook* which allows plugins to update an outgoing MUC join presence stanza
             * @event _converse#constructedMUCPresence
             * @param { _converse.ChatRoom } - The MUC from which this message stanza is being sent.
             * @param { Element } stanza - The stanza which will be sent out
             */
            _context4.next = 6;
            return shared_api.hook('constructedMUCPresence', _this4, stanza);
          case 6:
            stanza = _context4.sent;
            return _context4.abrupt("return", stanza);
          case 8:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }))();
  },
  clearOccupantsCache: function clearOccupantsCache() {
    if (this.occupants.length) {
      // Remove non-members when reconnecting
      this.occupants.filter(function (o) {
        return !o.isMember();
      }).forEach(function (o) {
        return o.destroy();
      });
    } else {
      // Looks like we haven't restored occupants from cache, so we clear it.
      this.occupants.clearStore();
    }
  },
  /**
   * Given the passed in MUC message, send a XEP-0333 chat marker.
   * @param { _converse.MUCMessage } msg
   * @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
   * @param { Boolean } force - Whether a marker should be sent for the
   *  message, even if it didn't include a `markable` element.
   */
  sendMarkerForMessage: function sendMarkerForMessage(msg) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'displayed';
    var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    if (!msg || !shared_api.settings.get('send_chat_markers').includes(type) || (msg === null || msg === void 0 ? void 0 : msg.get('type')) !== 'groupchat') {
      return;
    }
    if (msg !== null && msg !== void 0 && msg.get('is_markable') || force) {
      var key = "stanza_id ".concat(this.get('jid'));
      var id = msg.get(key);
      if (!id) {
        log.error("Can't send marker for message without stanza ID: ".concat(key));
        return;
      }
      var from_jid = external_strophe_namespaceObject.Strophe.getBareJidFromJid(msg.get('from'));
      sendMarker(from_jid, id, type, msg.get('type'));
    }
  },
  /**
   * Ensures that the user is subscribed to XEP-0437 Room Activity Indicators
   * if `muc_subscribe_to_rai` is set to `true`.
   * Only affiliated users can subscribe to RAI, but this method doesn't
   * check whether the current user is affiliated because it's intended to be
   * called after the MUC has been left and we don't have that information
   * anymore.
   * @private
   * @method _converse.ChatRoom#enableRAI
   */
  enableRAI: function enableRAI() {
    if (shared_api.settings.get('muc_subscribe_to_rai')) {
      var muc_domain = external_strophe_namespaceObject.Strophe.getDomainFromJid(this.get('jid'));
      shared_api.user.presence.send(null, muc_domain, null, (0,external_strophe_namespaceObject.$build)('rai', {
        'xmlns': external_strophe_namespaceObject.Strophe.NS.RAI
      }));
    }
  },
  /**
   * Handler that gets called when the 'hidden' flag is toggled.
   * @private
   * @method _converse.ChatRoom#onHiddenChange
   */
  onHiddenChange: function onHiddenChange() {
    var _this5 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee5() {
      var roomstatus, conn_status;
      return muc_regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            roomstatus = ROOMSTATUS;
            conn_status = _this5.session.get('connection_status');
            if (!_this5.get('hidden')) {
              _context5.next = 10;
              break;
            }
            if (!(conn_status === roomstatus.ENTERED && _this5.isRAICandidate())) {
              _context5.next = 8;
              break;
            }
            _this5.sendMarkerForLastMessage('received', true);
            _context5.next = 7;
            return _this5.leave();
          case 7:
            _this5.enableRAI();
          case 8:
            _context5.next = 12;
            break;
          case 10:
            if (conn_status === roomstatus.DISCONNECTED) {
              _this5.rejoin();
            }
            _this5.clearUnreadMsgCounter();
          case 12:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    }))();
  },
  onOccupantAdded: function onOccupantAdded(occupant) {
    if (shared_converse.isInfoVisible(public_converse.MUC_TRAFFIC_STATES.ENTERED) && this.session.get('connection_status') === ROOMSTATUS.ENTERED && occupant.get('show') === 'online') {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_TRAFFIC_STATES.ENTERED);
    }
  },
  onOccupantRemoved: function onOccupantRemoved(occupant) {
    if (shared_converse.isInfoVisible(public_converse.MUC_TRAFFIC_STATES.EXITED) && this.isEntered() && occupant.get('show') === 'online') {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_TRAFFIC_STATES.EXITED);
    }
  },
  onOccupantShowChanged: function onOccupantShowChanged(occupant) {
    if (occupant.get('states').includes('303')) {
      return;
    }
    if (occupant.get('show') === 'offline' && shared_converse.isInfoVisible(public_converse.MUC_TRAFFIC_STATES.EXITED)) {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_TRAFFIC_STATES.EXITED);
    } else if (occupant.get('show') === 'online' && shared_converse.isInfoVisible(public_converse.MUC_TRAFFIC_STATES.ENTERED)) {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_TRAFFIC_STATES.ENTERED);
    }
  },
  onRoomEntered: function onRoomEntered() {
    var _this6 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee6() {
      return muc_regeneratorRuntime().wrap(function _callee6$(_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            _context6.next = 2;
            return _this6.occupants.fetchMembers();
          case 2:
            if (!shared_api.settings.get('clear_messages_on_reconnection')) {
              _context6.next = 7;
              break;
            }
            _context6.next = 5;
            return _this6.clearMessages();
          case 5:
            _context6.next = 9;
            break;
          case 7:
            _context6.next = 9;
            return _this6.fetchMessages();
          case 9:
            /**
             * Triggered when the user has entered a new MUC
             * @event _converse#enteredNewRoom
             * @type { _converse.ChatRoom}
             * @example _converse.api.listen.on('enteredNewRoom', model => { ... });
             */
            shared_api.trigger('enteredNewRoom', _this6);
            _context6.t0 = shared_api.settings.get('auto_register_muc_nickname');
            if (!_context6.t0) {
              _context6.next = 15;
              break;
            }
            _context6.next = 14;
            return shared_api.disco.supports(external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER, _this6.get('jid'));
          case 14:
            _context6.t0 = _context6.sent;
          case 15:
            if (!_context6.t0) {
              _context6.next = 17;
              break;
            }
            _this6.registerNickname();
          case 17:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    }))();
  },
  onConnectionStatusChanged: function onConnectionStatusChanged() {
    var _this7 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee7() {
      return muc_regeneratorRuntime().wrap(function _callee7$(_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            if (!_this7.isEntered()) {
              _context7.next = 15;
              break;
            }
            if (!_this7.isRAICandidate()) {
              _context7.next = 13;
              break;
            }
            _context7.prev = 2;
            _context7.next = 5;
            return _this7.leave();
          case 5:
            _context7.next = 10;
            break;
          case 7:
            _context7.prev = 7;
            _context7.t0 = _context7["catch"](2);
            log.error(_context7.t0);
          case 10:
            _this7.enableRAI();
            _context7.next = 15;
            break;
          case 13:
            _context7.next = 15;
            return _this7.onRoomEntered();
          case 15:
          case "end":
            return _context7.stop();
        }
      }, _callee7, null, [[2, 7]]);
    }))();
  },
  onReconnection: function onReconnection() {
    var _this8 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee8() {
      return muc_regeneratorRuntime().wrap(function _callee8$(_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            _context8.next = 2;
            return _this8.rejoin();
          case 2:
            _this8.announceReconnection();
          case 3:
          case "end":
            return _context8.stop();
        }
      }, _callee8);
    }))();
  },
  getMessagesCollection: function getMessagesCollection() {
    return new shared_converse.ChatRoomMessages();
  },
  restoreSession: function restoreSession() {
    var _this9 = this;
    var id = "muc.session-".concat(shared_converse.bare_jid, "-").concat(this.get('jid'));
    this.session = new MUCSession({
      id: id
    });
    initStorage(this.session, id, 'session');
    return new Promise(function (r) {
      return _this9.session.fetch({
        'success': r,
        'error': r
      });
    });
  },
  initDiscoModels: function initDiscoModels() {
    var _this10 = this;
    var id = "converse.muc-features-".concat(shared_converse.bare_jid, "-").concat(this.get('jid'));
    this.features = new Model(Object.assign({
      id: id
    }, public_converse.ROOM_FEATURES.reduce(function (acc, feature) {
      acc[feature] = false;
      return acc;
    }, {})));
    this.features.browserStorage = shared_converse.createStore(id, 'session');
    this.features.listenTo(shared_converse, 'beforeLogout', function () {
      return _this10.features.browserStorage.flush();
    });
    id = "converse.muc-config-".concat(shared_converse.bare_jid, "-").concat(this.get('jid'));
    this.config = new Model({
      id: id
    });
    this.config.browserStorage = shared_converse.createStore(id, 'session');
    this.config.listenTo(shared_converse, 'beforeLogout', function () {
      return _this10.config.browserStorage.flush();
    });
  },
  initOccupants: function initOccupants() {
    var _this11 = this;
    this.occupants = new shared_converse.ChatRoomOccupants();
    var id = "converse.occupants-".concat(shared_converse.bare_jid).concat(this.get('jid'));
    this.occupants.browserStorage = shared_converse.createStore(id, 'session');
    this.occupants.chatroom = this;
    this.occupants.listenTo(shared_converse, 'beforeLogout', function () {
      return _this11.occupants.browserStorage.flush();
    });
  },
  fetchOccupants: function fetchOccupants() {
    var _this12 = this;
    this.occupants.fetched = new Promise(function (resolve) {
      _this12.occupants.fetch({
        'add': true,
        'silent': true,
        'success': resolve,
        'error': resolve
      });
    });
    return this.occupants.fetched;
  },
  handleAffiliationChangedMessage: function handleAffiliationChangedMessage(stanza) {
    var item = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MUC_USER, "\"] item"), stanza).pop();
    if (item) {
      var from = stanza.getAttribute('from');
      var type = stanza.getAttribute('type');
      var affiliation = item.getAttribute('affiliation');
      var jid = item.getAttribute('jid');
      var data = {
        from: from,
        type: type,
        affiliation: affiliation,
        'states': [],
        'show': type == 'unavailable' ? 'offline' : 'online',
        'role': item.getAttribute('role'),
        'jid': external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid),
        'resource': external_strophe_namespaceObject.Strophe.getResourceFromJid(jid)
      };
      var occupant = this.occupants.findOccupant({
        'jid': data.jid
      });
      if (occupant) {
        occupant.save(data);
      } else {
        this.occupants.create(data);
      }
    }
  },
  handleErrorMessageStanza: function handleErrorMessageStanza(stanza) {
    var _this13 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee9() {
      var __, attrs, message, new_attrs;
      return muc_regeneratorRuntime().wrap(function _callee9$(_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            __ = shared_converse.__;
            _context9.next = 3;
            return parseMUCMessage(stanza, _this13);
          case 3:
            attrs = _context9.sent;
            _context9.next = 6;
            return _this13.shouldShowErrorMessage(attrs);
          case 6:
            if (_context9.sent) {
              _context9.next = 8;
              break;
            }
            return _context9.abrupt("return");
          case 8:
            message = _this13.getMessageReferencedByError(attrs);
            if (message) {
              new_attrs = {
                'error': attrs.error,
                'error_condition': attrs.error_condition,
                'error_text': attrs.error_text,
                'error_type': attrs.error_type,
                'editable': false
              };
              if (attrs.msgid === message.get('retraction_id')) {
                // The error message refers to a retraction
                new_attrs.retracted = undefined;
                new_attrs.retraction_id = undefined;
                new_attrs.retracted_id = undefined;
                if (!attrs.error) {
                  if (attrs.error_condition === 'forbidden') {
                    new_attrs.error = __("You're not allowed to retract your message.");
                  } else if (attrs.error_condition === 'not-acceptable') {
                    new_attrs.error = __("Your retraction was not delivered because you're not present in the groupchat.");
                  } else {
                    new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
                  }
                }
              } else if (!attrs.error) {
                if (attrs.error_condition === 'forbidden') {
                  new_attrs.error = __("Your message was not delivered because you weren't allowed to send it.");
                } else if (attrs.error_condition === 'not-acceptable') {
                  new_attrs.error = __("Your message was not delivered because you're not present in the groupchat.");
                } else {
                  new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
                }
              }
              message.save(new_attrs);
            } else {
              _this13.createMessage(attrs);
            }
          case 10:
          case "end":
            return _context9.stop();
        }
      }, _callee9);
    }))();
  },
  /**
   * Handles incoming message stanzas from the service that hosts this MUC
   * @private
   * @method _converse.ChatRoom#handleMessageFromMUCHost
   * @param { Element } stanza
   */
  handleMessageFromMUCHost: function handleMessageFromMUCHost(stanza) {
    if (this.isEntered()) {
      // We're not interested in activity indicators when already joined to the room
      return;
    }
    var rai = external_sizzle_default()("rai[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.RAI, "\"]"), stanza).pop();
    var active_mucs = Array.from((rai === null || rai === void 0 ? void 0 : rai.querySelectorAll('activity')) || []).map(function (m) {
      return m.textContent;
    });
    if (active_mucs.includes(this.get('jid'))) {
      this.save({
        'has_activity': true,
        'num_unread_general': 0 // Either/or between activity and unreads
      });
    }
  },

  /**
   * Handles XEP-0452 MUC Mention Notification messages
   * @private
   * @method _converse.ChatRoom#handleForwardedMentions
   * @param { Element } stanza
   */
  handleForwardedMentions: function handleForwardedMentions(stanza) {
    var _this14 = this;
    if (this.isEntered()) {
      // Avoid counting mentions twice
      return;
    }
    var msgs = external_sizzle_default()("mentions[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MENTIONS, "\"] forwarded[xmlns=\"").concat(external_strophe_namespaceObject.Strophe.NS.FORWARD, "\"] message[type=\"groupchat\"]"), stanza);
    var muc_jid = this.get('jid');
    var mentions = msgs.filter(function (m) {
      return external_strophe_namespaceObject.Strophe.getBareJidFromJid(m.getAttribute('from')) === muc_jid;
    });
    if (mentions.length) {
      this.save({
        'has_activity': true,
        'num_unread': this.get('num_unread') + mentions.length
      });
      mentions.forEach( /*#__PURE__*/function () {
        var _ref = muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee10(stanza) {
          var attrs, data;
          return muc_regeneratorRuntime().wrap(function _callee10$(_context10) {
            while (1) switch (_context10.prev = _context10.next) {
              case 0:
                _context10.next = 2;
                return parseMUCMessage(stanza, _this14);
              case 2:
                attrs = _context10.sent;
                data = {
                  stanza: stanza,
                  attrs: attrs,
                  'chatbox': _this14
                };
                shared_api.trigger('message', data);
              case 5:
              case "end":
                return _context10.stop();
            }
          }, _callee10);
        }));
        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
    }
  },
  /**
   * Parses an incoming message stanza and queues it for processing.
   * @private
   * @method _converse.ChatRoom#handleMessageStanza
   * @param { Element } stanza
   */
  handleMessageStanza: function handleMessageStanza(stanza) {
    var _this15 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee11() {
      var _stanza$tree, _stanza$tree2, _stanza;
      var type, attrs, data;
      return muc_regeneratorRuntime().wrap(function _callee11$(_context11) {
        while (1) switch (_context11.prev = _context11.next) {
          case 0:
            stanza = (_stanza$tree = (_stanza$tree2 = (_stanza = stanza).tree) === null || _stanza$tree2 === void 0 ? void 0 : _stanza$tree2.call(_stanza)) !== null && _stanza$tree !== void 0 ? _stanza$tree : stanza;
            type = stanza.getAttribute('type');
            if (!(type === 'error')) {
              _context11.next = 4;
              break;
            }
            return _context11.abrupt("return", _this15.handleErrorMessageStanza(stanza));
          case 4:
            if (!(type === 'groupchat')) {
              _context11.next = 11;
              break;
            }
            if (!isArchived(stanza)) {
              _context11.next = 7;
              break;
            }
            return _context11.abrupt("return", log.warn("Received a MAM message with type \"groupchat\""));
          case 7:
            _this15.createInfoMessages(stanza);
            _this15.fetchFeaturesIfConfigurationChanged(stanza);
            _context11.next = 13;
            break;
          case 11:
            if (type) {
              _context11.next = 13;
              break;
            }
            return _context11.abrupt("return", _this15.handleForwardedMentions(stanza));
          case 13:
            _context11.prev = 13;
            _context11.next = 16;
            return parseMUCMessage(stanza, _this15);
          case 16:
            attrs = _context11.sent;
            _context11.next = 22;
            break;
          case 19:
            _context11.prev = 19;
            _context11.t0 = _context11["catch"](13);
            return _context11.abrupt("return", log.error(_context11.t0));
          case 22:
            data = {
              stanza: stanza,
              attrs: attrs,
              'chatbox': _this15
            };
            /**
             * Triggered when a groupchat message stanza has been received and parsed.
             * @event _converse#message
             * @type { object }
             * @property { module:converse-muc~MUCMessageData } data
             */
            shared_api.trigger('message', data);
            return _context11.abrupt("return", attrs && _this15.queueMessage(attrs));
          case 25:
          case "end":
            return _context11.stop();
        }
      }, _callee11, null, [[13, 19]]);
    }))();
  },
  /**
   * Register presence and message handlers relevant to this groupchat
   * @private
   * @method _converse.ChatRoom#registerHandlers
   */
  registerHandlers: function registerHandlers() {
    var _this16 = this;
    var muc_jid = this.get('jid');
    var muc_domain = external_strophe_namespaceObject.Strophe.getDomainFromJid(muc_jid);
    this.removeHandlers();
    this.presence_handler = shared_converse.connection.addHandler(function (stanza) {
      return _this16.onPresence(stanza) || true;
    }, null, 'presence', null, null, muc_jid, {
      'ignoreNamespaceFragment': true,
      'matchBareFromJid': true
    });
    this.domain_presence_handler = shared_converse.connection.addHandler(function (stanza) {
      return _this16.onPresenceFromMUCHost(stanza) || true;
    }, null, 'presence', null, null, muc_domain);
    this.message_handler = shared_converse.connection.addHandler(function (stanza) {
      return !!_this16.handleMessageStanza(stanza) || true;
    }, null, 'message', null, null, muc_jid, {
      'matchBareFromJid': true
    });
    this.domain_message_handler = shared_converse.connection.addHandler(function (stanza) {
      return _this16.handleMessageFromMUCHost(stanza) || true;
    }, null, 'message', null, null, muc_domain);
    this.affiliation_message_handler = shared_converse.connection.addHandler(function (stanza) {
      return _this16.handleAffiliationChangedMessage(stanza) || true;
    }, external_strophe_namespaceObject.Strophe.NS.MUC_USER, 'message', null, null, muc_jid);
  },
  removeHandlers: function removeHandlers() {
    // Remove the presence and message handlers that were
    // registered for this groupchat.
    if (this.message_handler) {
      shared_converse.connection && shared_converse.connection.deleteHandler(this.message_handler);
      delete this.message_handler;
    }
    if (this.domain_message_handler) {
      shared_converse.connection && shared_converse.connection.deleteHandler(this.domain_message_handler);
      delete this.domain_message_handler;
    }
    if (this.presence_handler) {
      shared_converse.connection && shared_converse.connection.deleteHandler(this.presence_handler);
      delete this.presence_handler;
    }
    if (this.domain_presence_handler) {
      shared_converse.connection && shared_converse.connection.deleteHandler(this.domain_presence_handler);
      delete this.domain_presence_handler;
    }
    if (this.affiliation_message_handler) {
      shared_converse.connection && shared_converse.connection.deleteHandler(this.affiliation_message_handler);
      delete this.affiliation_message_handler;
    }
    return this;
  },
  invitesAllowed: function invitesAllowed() {
    return shared_api.settings.get('allow_muc_invitations') && (this.features.get('open') || this.getOwnAffiliation() === 'owner');
  },
  getDisplayName: function getDisplayName() {
    var name = this.get('name');
    if (name) {
      return name;
    } else if (shared_api.settings.get('locked_muc_domain') === 'hidden') {
      return external_strophe_namespaceObject.Strophe.getNodeFromJid(this.get('jid'));
    } else {
      return this.get('jid');
    }
  },
  /**
   * Sends a message stanza to the XMPP server and expects a reflection
   * or error message within a specific timeout period.
   * @private
   * @method _converse.ChatRoom#sendTimedMessage
   * @param { _converse.Message|Element } message
   * @returns { Promise<Element>|Promise<TimeoutError> } Returns a promise
   *  which resolves with the reflected message stanza or with an error stanza or {@link TimeoutError}.
   */
  sendTimedMessage: function sendTimedMessage(el) {
    if (typeof el.tree === 'function') {
      el = el.tree();
    }
    var id = el.getAttribute('id');
    if (!id) {
      // inject id if not found
      id = this.getUniqueId('sendIQ');
      el.setAttribute('id', id);
    }
    var promise = getOpenPromise();
    var timeout = shared_api.settings.get('stanza_timeout');
    var timeoutHandler = shared_converse.connection.addTimedHandler(timeout, function () {
      shared_converse.connection.deleteHandler(handler);
      var err = new TimeoutError('Timeout Error: No response from server');
      promise.resolve(err);
      return false;
    });
    var handler = shared_converse.connection.addHandler(function (stanza) {
      timeoutHandler && shared_converse.connection.deleteTimedHandler(timeoutHandler);
      promise.resolve(stanza);
    }, null, 'message', ['error', 'groupchat'], id);
    shared_api.send(el);
    return promise;
  },
  /**
   * Retract one of your messages in this groupchat
   * @private
   * @method _converse.ChatRoom#retractOwnMessage
   * @param { _converse.Message } message - The message which we're retracting.
   */
  retractOwnMessage: function retractOwnMessage(message) {
    var _this17 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee12() {
      var __, origin_id, editable, stanza, result;
      return muc_regeneratorRuntime().wrap(function _callee12$(_context12) {
        while (1) switch (_context12.prev = _context12.next) {
          case 0:
            __ = shared_converse.__;
            origin_id = message.get('origin_id');
            if (origin_id) {
              _context12.next = 4;
              break;
            }
            throw new Error("Can't retract message without a XEP-0359 Origin ID");
          case 4:
            editable = message.get('editable');
            stanza = (0,external_strophe_namespaceObject.$msg)({
              'id': getUniqueId(),
              'to': _this17.get('jid'),
              'type': 'groupchat'
            }).c('store', {
              xmlns: external_strophe_namespaceObject.Strophe.NS.HINTS
            }).up().c('apply-to', {
              'id': origin_id,
              'xmlns': external_strophe_namespaceObject.Strophe.NS.FASTEN
            }).c('retract', {
              xmlns: external_strophe_namespaceObject.Strophe.NS.RETRACT
            }); // Optimistic save
            message.set({
              'retracted': new Date().toISOString(),
              'retracted_id': origin_id,
              'retraction_id': stanza.tree().getAttribute('id'),
              'editable': false
            });
            _context12.next = 9;
            return _this17.sendTimedMessage(stanza);
          case 9:
            result = _context12.sent;
            if (muc_u.isErrorStanza(result)) {
              log.error(result);
            } else if (result instanceof TimeoutError) {
              log.error(result);
              message.save({
                editable: editable,
                'error_type': 'timeout',
                'error': __('A timeout happened while while trying to retract your message.'),
                'retracted': undefined,
                'retracted_id': undefined,
                'retraction_id': undefined
              });
            }
          case 11:
          case "end":
            return _context12.stop();
        }
      }, _callee12);
    }))();
  },
  /**
   * Retract someone else's message in this groupchat.
   * @private
   * @method _converse.ChatRoom#retractOtherMessage
   * @param { _converse.ChatRoomMessage } message - The message which we're retracting.
   * @param { string } [reason] - The reason for retracting the message.
   * @example
   *  const room = await api.rooms.get(jid);
   *  const message = room.messages.findWhere({'body': 'Get rich quick!'});
   *  room.retractOtherMessage(message, 'spam');
   */
  retractOtherMessage: function retractOtherMessage(message, reason) {
    var _this18 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee13() {
      var editable, result;
      return muc_regeneratorRuntime().wrap(function _callee13$(_context13) {
        while (1) switch (_context13.prev = _context13.next) {
          case 0:
            editable = message.get('editable'); // Optimistic save
            message.save({
              'moderated': 'retracted',
              'moderated_by': shared_converse.bare_jid,
              'moderated_id': message.get('msgid'),
              'moderation_reason': reason,
              'editable': false
            });
            _context13.next = 4;
            return _this18.sendRetractionIQ(message, reason);
          case 4:
            result = _context13.sent;
            if (result === null || muc_u.isErrorStanza(result)) {
              // Undo the save if something went wrong
              message.save({
                editable: editable,
                'moderated': undefined,
                'moderated_by': undefined,
                'moderated_id': undefined,
                'moderation_reason': undefined
              });
            }
            return _context13.abrupt("return", result);
          case 7:
          case "end":
            return _context13.stop();
        }
      }, _callee13);
    }))();
  },
  /**
   * Sends an IQ stanza to the XMPP server to retract a message in this groupchat.
   * @private
   * @method _converse.ChatRoom#sendRetractionIQ
   * @param { _converse.ChatRoomMessage } message - The message which we're retracting.
   * @param { string } [reason] - The reason for retracting the message.
   */
  sendRetractionIQ: function sendRetractionIQ(message, reason) {
    var iq = (0,external_strophe_namespaceObject.$iq)({
      'to': this.get('jid'),
      'type': 'set'
    }).c('apply-to', {
      'id': message.get("stanza_id ".concat(this.get('jid'))),
      'xmlns': external_strophe_namespaceObject.Strophe.NS.FASTEN
    }).c('moderate', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.MODERATE
    }).c('retract', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.RETRACT
    }).up().c('reason').t(reason || '');
    return shared_api.sendIQ(iq, null, false);
  },
  /**
   * Sends an IQ stanza to the XMPP server to destroy this groupchat. Not
   * to be confused with the {@link _converse.ChatRoom#destroy}
   * method, which simply removes the room from the local browser storage cache.
   * @private
   * @method _converse.ChatRoom#sendDestroyIQ
   * @param { string } [reason] - The reason for destroying the groupchat.
   * @param { string } [new_jid] - The JID of the new groupchat which replaces this one.
   */
  sendDestroyIQ: function sendDestroyIQ(reason, new_jid) {
    var destroy = (0,external_strophe_namespaceObject.$build)('destroy');
    if (new_jid) {
      destroy.attrs({
        'jid': new_jid
      });
    }
    var iq = (0,external_strophe_namespaceObject.$iq)({
      'to': this.get('jid'),
      'type': 'set'
    }).c('query', {
      'xmlns': external_strophe_namespaceObject.Strophe.NS.MUC_OWNER
    }).cnode(destroy.node);
    if (reason && reason.length > 0) {
      iq.c('reason', reason);
    }
    return shared_api.sendIQ(iq);
  },
  /**
   * Leave the groupchat.
   * @private
   * @method _converse.ChatRoom#leave
   * @param { string } [exit_msg] - Message to indicate your reason for leaving
   */
  leave: function leave(exit_msg) {
    var _this19 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee14() {
      var _converse$disco_entit;
      var disco_entity;
      return muc_regeneratorRuntime().wrap(function _callee14$(_context14) {
        while (1) switch (_context14.prev = _context14.next) {
          case 0:
            shared_api.connection.connected() && shared_api.user.presence.send('unavailable', _this19.getRoomJIDAndNick(), exit_msg);

            // Delete the features model
            if (!_this19.features) {
              _context14.next = 4;
              break;
            }
            _context14.next = 4;
            return new Promise(function (resolve) {
              return _this19.features.destroy({
                'success': resolve,
                'error': function error(_, e) {
                  log.error(e);
                  resolve();
                }
              });
            });
          case 4:
            // Delete disco entity
            disco_entity = (_converse$disco_entit = shared_converse.disco_entities) === null || _converse$disco_entit === void 0 ? void 0 : _converse$disco_entit.get(_this19.get('jid'));
            if (!disco_entity) {
              _context14.next = 8;
              break;
            }
            _context14.next = 8;
            return new Promise(function (resolve) {
              return disco_entity.destroy({
                'success': resolve,
                'error': function error(_, e) {
                  log.error(e);
                  resolve();
                }
              });
            });
          case 8:
            safeSave(_this19.session, {
              'connection_status': ROOMSTATUS.DISCONNECTED
            });
          case 9:
          case "end":
            return _context14.stop();
        }
      }, _callee14);
    }))();
  },
  close: function close(ev) {
    var _this20 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee15() {
      var ENTERED, CLOSING, was_entered;
      return muc_regeneratorRuntime().wrap(function _callee15$(_context15) {
        while (1) switch (_context15.prev = _context15.next) {
          case 0:
            ENTERED = ROOMSTATUS.ENTERED, CLOSING = ROOMSTATUS.CLOSING;
            was_entered = _this20.session.get('connection_status') === ENTERED;
            safeSave(_this20.session, {
              'connection_status': CLOSING
            });
            was_entered && _this20.sendMarkerForLastMessage('received', true);
            _context15.next = 6;
            return _this20.unregisterNickname();
          case 6:
            _context15.next = 8;
            return _this20.leave();
          case 8:
            _this20.occupants.clearStore();
            if ((ev === null || ev === void 0 ? void 0 : ev.name) !== 'closeAllChatBoxes' && shared_api.settings.get('muc_clear_messages_on_leave')) {
              _this20.clearMessages();
            }

            // Delete the session model
            _context15.next = 12;
            return new Promise(function (resolve) {
              return _this20.session.destroy({
                'success': resolve,
                'error': function error(_, e) {
                  log.error(e);
                  resolve();
                }
              });
            });
          case 12:
            return _context15.abrupt("return", shared_converse.ChatBox.prototype.close.call(_this20));
          case 13:
          case "end":
            return _context15.stop();
        }
      }, _callee15);
    }))();
  },
  canModerateMessages: function canModerateMessages() {
    var self = this.getOwnOccupant();
    return self && self.isModerator() && shared_api.disco.supports(external_strophe_namespaceObject.Strophe.NS.MODERATE, this.get('jid'));
  },
  /**
   * Return an array of unique nicknames based on all occupants and messages in this MUC.
   * @private
   * @method _converse.ChatRoom#getAllKnownNicknames
   * @returns { String[] }
   */
  getAllKnownNicknames: function getAllKnownNicknames() {
    return muc_toConsumableArray(new Set([].concat(muc_toConsumableArray(this.occupants.map(function (o) {
      return o.get('nick');
    })), muc_toConsumableArray(this.messages.map(function (m) {
      return m.get('nick');
    }))))).filter(function (n) {
      return n;
    });
  },
  getAllKnownNicknamesRegex: function getAllKnownNicknamesRegex() {
    var longNickString = this.getAllKnownNicknames().map(function (n) {
      return parse_helpers.escapeRegexString(n);
    }).join('|');
    return RegExp("(?:\\p{P}|\\p{Z}|^)@(".concat(longNickString, ")(?![\\w@-])"), 'uig');
  },
  getOccupantByJID: function getOccupantByJID(jid) {
    return this.occupants.findOccupant({
      jid: jid
    });
  },
  getOccupantByNickname: function getOccupantByNickname(nick) {
    return this.occupants.findOccupant({
      nick: nick
    });
  },
  getReferenceURIFromNickname: function getReferenceURIFromNickname(nickname) {
    var muc_jid = this.get('jid');
    var occupant = this.getOccupant(nickname);
    var uri = this.features.get('nonanonymous') && (occupant === null || occupant === void 0 ? void 0 : occupant.get('jid')) || "".concat(muc_jid, "/").concat(nickname);
    return encodeURI("xmpp:".concat(uri));
  },
  /**
   * Given a text message, look for `@` mentions and turn them into
   * XEP-0372 references
   * @param { String } text
   */
  parseTextForReferences: function parseTextForReferences(text) {
    var _this21 = this;
    var mentions_regex = /((?:[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F])|[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|^)(@[\x2D0-9A-Z_a-z\u017F\u212A]+(?:\.[0-9A-Z_a-z\u017F\u212A]+)*)/gi;
    if (!text || !mentions_regex.test(text)) {
      return [text, []];
    }
    var getMatchingNickname = parse_helpers.findFirstMatchInArray(this.getAllKnownNicknames());
    var matchToReference = function matchToReference(match) {
      var at_sign_index = match[0].indexOf('@');
      if (match[0][at_sign_index + 1] === '@') {
        // edge-case
        at_sign_index += 1;
      }
      var begin = match.index + at_sign_index;
      var end = begin + match[0].length - at_sign_index;
      var value = getMatchingNickname(match[1]);
      var type = 'mention';
      var uri = _this21.getReferenceURIFromNickname(value);
      return {
        begin: begin,
        end: end,
        value: value,
        type: type,
        uri: uri
      };
    };
    var regex = this.getAllKnownNicknamesRegex();
    var mentions = muc_toConsumableArray(text.matchAll(regex)).filter(function (m) {
      return !m[0].startsWith('/');
    });
    var references = mentions.map(matchToReference);
    var _p$reduceTextFromRefe = parse_helpers.reduceTextFromReferences(text, references),
      _p$reduceTextFromRefe2 = muc_slicedToArray(_p$reduceTextFromRefe, 2),
      updated_message = _p$reduceTextFromRefe2[0],
      updated_references = _p$reduceTextFromRefe2[1];
    return [updated_message, updated_references];
  },
  getOutgoingMessageAttributes: function getOutgoingMessageAttributes(attrs) {
    var _this22 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee16() {
      var _attrs;
      var is_spoiler, text, references, _this22$parseTextForR, _this22$parseTextForR2, origin_id, body;
      return muc_regeneratorRuntime().wrap(function _callee16$(_context16) {
        while (1) switch (_context16.prev = _context16.next) {
          case 0:
            _context16.next = 2;
            return shared_api.emojis.initialize();
          case 2:
            is_spoiler = _this22.get('composing_spoiler');
            text = '';
            if ((_attrs = attrs) !== null && _attrs !== void 0 && _attrs.body) {
              _this22$parseTextForR = _this22.parseTextForReferences(attrs.body);
              _this22$parseTextForR2 = muc_slicedToArray(_this22$parseTextForR, 2);
              text = _this22$parseTextForR2[0];
              references = _this22$parseTextForR2[1];
            }
            origin_id = getUniqueId();
            body = text ? muc_u.shortnamesToUnicode(text) : undefined;
            attrs = Object.assign({}, attrs, {
              body: body,
              is_spoiler: is_spoiler,
              origin_id: origin_id,
              references: references,
              'id': origin_id,
              'msgid': origin_id,
              'from': "".concat(_this22.get('jid'), "/").concat(_this22.get('nick')),
              'fullname': _this22.get('nick'),
              'is_only_emojis': text ? muc_u.isOnlyEmojis(text) : false,
              'message': body,
              'nick': _this22.get('nick'),
              'sender': 'me',
              'type': 'groupchat'
            }, getMediaURLsMetadata(text));

            /**
             * *Hook* which allows plugins to update the attributes of an outgoing
             * message.
             * @event _converse#getOutgoingMessageAttributes
             */
            _context16.next = 10;
            return shared_api.hook('getOutgoingMessageAttributes', _this22, attrs);
          case 10:
            attrs = _context16.sent;
            return _context16.abrupt("return", attrs);
          case 12:
          case "end":
            return _context16.stop();
        }
      }, _callee16);
    }))();
  },
  /**
   * Utility method to construct the JID for the current user as occupant of the groupchat.
   * @private
   * @method _converse.ChatRoom#getRoomJIDAndNick
   * @returns {string} - The groupchat JID with the user's nickname added at the end.
   * @example groupchat@conference.example.org/nickname
   */
  getRoomJIDAndNick: function getRoomJIDAndNick() {
    var nick = this.get('nick');
    var jid = external_strophe_namespaceObject.Strophe.getBareJidFromJid(this.get('jid'));
    return jid + (nick !== null ? "/".concat(nick) : '');
  },
  /**
   * Sends a message with the current XEP-0085 chat state of the user
   * as taken from the `chat_state` attribute of the {@link _converse.ChatRoom}.
   * @private
   * @method _converse.ChatRoom#sendChatState
   */
  sendChatState: function sendChatState() {
    if (!shared_api.settings.get('send_chat_state_notifications') || !this.get('chat_state') || !this.isEntered() || this.features.get('moderated') && this.getOwnRole() === 'visitor') {
      return;
    }
    var allowed = shared_api.settings.get('send_chat_state_notifications');
    if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
      return;
    }
    var chat_state = this.get('chat_state');
    if (chat_state === shared_converse.GONE) {
      // <gone/> is not applicable within MUC context
      return;
    }
    shared_api.send((0,external_strophe_namespaceObject.$msg)({
      'to': this.get('jid'),
      'type': 'groupchat'
    }).c(chat_state, {
      'xmlns': external_strophe_namespaceObject.Strophe.NS.CHATSTATES
    }).up().c('no-store', {
      'xmlns': external_strophe_namespaceObject.Strophe.NS.HINTS
    }).up().c('no-permanent-store', {
      'xmlns': external_strophe_namespaceObject.Strophe.NS.HINTS
    }));
  },
  /**
   * Send a direct invitation as per XEP-0249
   * @private
   * @method _converse.ChatRoom#directInvite
   * @param { String } recipient - JID of the person being invited
   * @param { String } [reason] - Reason for the invitation
   */
  directInvite: function directInvite(recipient, reason) {
    if (this.features.get('membersonly')) {
      // When inviting to a members-only groupchat, we first add
      // the person to the member list by giving them an
      // affiliation of 'member' otherwise they won't be able to join.
      this.updateMemberLists([{
        'jid': recipient,
        'affiliation': 'member',
        'reason': reason
      }]);
    }
    var attrs = {
      'xmlns': 'jabber:x:conference',
      'jid': this.get('jid')
    };
    if (reason !== null) {
      attrs.reason = reason;
    }
    if (this.get('password')) {
      attrs.password = this.get('password');
    }
    var invitation = (0,external_strophe_namespaceObject.$msg)({
      'from': shared_converse.connection.jid,
      'to': recipient,
      'id': getUniqueId()
    }).c('x', attrs);
    shared_api.send(invitation);
    /**
     * After the user has sent out a direct invitation (as per XEP-0249),
     * to a roster contact, asking them to join a room.
     * @event _converse#chatBoxMaximized
     * @type {object}
     * @property {_converse.ChatRoom} room
     * @property {string} recipient - The JID of the person being invited
     * @property {string} reason - The original reason for the invitation
     * @example _converse.api.listen.on('chatBoxMaximized', view => { ... });
     */
    shared_api.trigger('roomInviteSent', {
      'room': this,
      'recipient': recipient,
      'reason': reason
    });
  },
  /**
   * Refresh the disco identity, features and fields for this {@link _converse.ChatRoom}.
   * *features* are stored on the features {@link Model} attribute on this {@link _converse.ChatRoom}.
   * *fields* are stored on the config {@link Model} attribute on this {@link _converse.ChatRoom}.
   * @private
   * @returns {Promise}
   */
  refreshDiscoInfo: function refreshDiscoInfo() {
    var _this23 = this;
    return shared_api.disco.refresh(this.get('jid')).then(function () {
      return _this23.getDiscoInfo();
    }).catch(function (e) {
      return log.error(e);
    });
  },
  /**
   * Fetch the *extended* MUC info from the server and cache it locally
   * https://xmpp.org/extensions/xep-0045.html#disco-roominfo
   * @private
   * @method _converse.ChatRoom#getDiscoInfo
   * @returns {Promise}
   */
  getDiscoInfo: function getDiscoInfo() {
    var _this24 = this;
    return shared_api.disco.getIdentity('conference', 'text', this.get('jid')).then(function (identity) {
      return _this24.save({
        'name': identity === null || identity === void 0 ? void 0 : identity.get('name')
      });
    }).then(function () {
      return _this24.getDiscoInfoFields();
    }).then(function () {
      return _this24.getDiscoInfoFeatures();
    }).catch(function (e) {
      return log.error(e);
    });
  },
  /**
   * Fetch the *extended* MUC info fields from the server and store them locally
   * in the `config` {@link Model} attribute.
   * See: https://xmpp.org/extensions/xep-0045.html#disco-roominfo
   * @private
   * @method _converse.ChatRoom#getDiscoInfoFields
   * @returns {Promise}
   */
  getDiscoInfoFields: function getDiscoInfoFields() {
    var _this25 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee17() {
      var fields, config;
      return muc_regeneratorRuntime().wrap(function _callee17$(_context17) {
        while (1) switch (_context17.prev = _context17.next) {
          case 0:
            _context17.next = 2;
            return shared_api.disco.getFields(_this25.get('jid'));
          case 2:
            fields = _context17.sent;
            config = fields.reduce(function (config, f) {
              var name = f.get('var');
              if (name !== null && name !== void 0 && name.startsWith('muc#roominfo_')) {
                config[name.replace('muc#roominfo_', '')] = f.get('value');
              }
              return config;
            }, {});
            _this25.config.save(config);
          case 5:
          case "end":
            return _context17.stop();
        }
      }, _callee17);
    }))();
  },
  /**
   * Use converse-disco to populate the features {@link Model} which
   * is stored as an attibute on this {@link _converse.ChatRoom}.
   * The results may be cached. If you want to force fetching the features from the
   * server, call {@link _converse.ChatRoom#refreshDiscoInfo} instead.
   * @private
   * @returns {Promise}
   */
  getDiscoInfoFeatures: function getDiscoInfoFeatures() {
    var _this26 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee18() {
      var features, attrs;
      return muc_regeneratorRuntime().wrap(function _callee18$(_context18) {
        while (1) switch (_context18.prev = _context18.next) {
          case 0:
            _context18.next = 2;
            return shared_api.disco.getFeatures(_this26.get('jid'));
          case 2:
            features = _context18.sent;
            attrs = public_converse.ROOM_FEATURES.reduce(function (acc, feature) {
              acc[feature] = false;
              return acc;
            }, {
              'fetched': new Date().toISOString()
            });
            features.each(function (feature) {
              var fieldname = feature.get('var');
              if (!fieldname.startsWith('muc_')) {
                if (fieldname === external_strophe_namespaceObject.Strophe.NS.MAM) {
                  attrs.mam_enabled = true;
                } else {
                  attrs[fieldname] = true;
                }
                return;
              }
              attrs[fieldname.replace('muc_', '')] = true;
            });
            _this26.features.save(attrs);
          case 6:
          case "end":
            return _context18.stop();
        }
      }, _callee18);
    }))();
  },
  /**
   * Given a <field> element, return a copy with a <value> child if
   * we can find a value for it in this rooms config.
   * @private
   * @method _converse.ChatRoom#addFieldValue
   * @returns { Element }
   */
  addFieldValue: function addFieldValue(field) {
    var type = field.getAttribute('type');
    if (type === 'fixed') {
      return field;
    }
    var fieldname = field.getAttribute('var').replace('muc#roomconfig_', '');
    var config = this.get('roomconfig');
    if (fieldname in config) {
      var values;
      switch (type) {
        case 'boolean':
          values = [config[fieldname] ? 1 : 0];
          break;
        case 'list-multi':
          values = config[fieldname];
          break;
        default:
          values = [config[fieldname]];
      }
      field.innerHTML = values.map(function (v) {
        return (0,external_strophe_namespaceObject.$build)('value').t(v);
      }).join('');
    }
    return field;
  },
  /**
   * Automatically configure the groupchat based on this model's
   * 'roomconfig' data.
   * @private
   * @method _converse.ChatRoom#autoConfigureChatRoom
   * @returns { Promise<Element> }
   * Returns a promise which resolves once a response IQ has
   * been received.
   */
  autoConfigureChatRoom: function autoConfigureChatRoom() {
    var _this27 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee19() {
      var stanza, fields, configArray;
      return muc_regeneratorRuntime().wrap(function _callee19$(_context19) {
        while (1) switch (_context19.prev = _context19.next) {
          case 0:
            _context19.next = 2;
            return _this27.fetchRoomConfiguration();
          case 2:
            stanza = _context19.sent;
            fields = external_sizzle_default()('field', stanza);
            configArray = fields.map(function (f) {
              return _this27.addFieldValue(f);
            });
            if (!configArray.length) {
              _context19.next = 7;
              break;
            }
            return _context19.abrupt("return", _this27.sendConfiguration(configArray));
          case 7:
          case "end":
            return _context19.stop();
        }
      }, _callee19);
    }))();
  },
  /**
   * Send an IQ stanza to fetch the groupchat configuration data.
   * Returns a promise which resolves once the response IQ
   * has been received.
   * @private
   * @method _converse.ChatRoom#fetchRoomConfiguration
   * @returns { Promise<Element> }
   */
  fetchRoomConfiguration: function fetchRoomConfiguration() {
    return shared_api.sendIQ((0,external_strophe_namespaceObject.$iq)({
      'to': this.get('jid'),
      'type': 'get'
    }).c('query', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.MUC_OWNER
    }));
  },
  /**
   * Sends an IQ stanza with the groupchat configuration.
   * @private
   * @method _converse.ChatRoom#sendConfiguration
   * @param { Array } config - The groupchat configuration
   * @returns { Promise<Element> } - A promise which resolves with
   * the `result` stanza received from the XMPP server.
   */
  sendConfiguration: function sendConfiguration() {
    var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var iq = (0,external_strophe_namespaceObject.$iq)({
      to: this.get('jid'),
      type: 'set'
    }).c('query', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.MUC_OWNER
    }).c('x', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.XFORM,
      type: 'submit'
    });
    config.forEach(function (node) {
      return iq.cnode(node).up();
    });
    return shared_api.sendIQ(iq);
  },
  onCommandError: function onCommandError(err) {
    var __ = shared_converse.__;
    log.fatal(err);
    var message = __('Sorry, an error happened while running the command.') + ' ' + __("Check your browser's developer console for details.");
    this.createMessage({
      message: message,
      'type': 'error'
    });
  },
  getNickOrJIDFromCommandArgs: function getNickOrJIDFromCommandArgs(args) {
    var __ = shared_converse.__;
    if (muc_u.isValidJID(args.trim())) {
      return args.trim();
    }
    if (!args.startsWith('@')) {
      args = '@' + args;
    }
    var _this$parseTextForRef = this.parseTextForReferences(args),
      _this$parseTextForRef2 = muc_slicedToArray(_this$parseTextForRef, 2),
      _text = _this$parseTextForRef2[0],
      references = _this$parseTextForRef2[1]; // eslint-disable-line no-unused-vars
    if (!references.length) {
      var message = __("Error: couldn't find a groupchat participant based on your arguments");
      this.createMessage({
        message: message,
        'type': 'error'
      });
      return;
    }
    if (references.length > 1) {
      var _message = __('Error: found multiple groupchat participant based on your arguments');
      this.createMessage({
        message: _message,
        'type': 'error'
      });
      return;
    }
    var nick_or_jid = references.pop().value;
    var reason = args.split(nick_or_jid, 2)[1];
    if (reason && !reason.startsWith(' ')) {
      var _message2 = __("Error: couldn't find a groupchat participant based on your arguments");
      this.createMessage({
        message: _message2,
        'type': 'error'
      });
      return;
    }
    return nick_or_jid;
  },
  validateRoleOrAffiliationChangeArgs: function validateRoleOrAffiliationChangeArgs(command, args) {
    var __ = shared_converse.__;
    if (!args) {
      var message = __('Error: the "%1$s" command takes two arguments, the user\'s nickname and optionally a reason.', command);
      this.createMessage({
        message: message,
        'type': 'error'
      });
      return false;
    }
    return true;
  },
  getAllowedCommands: function getAllowedCommands() {
    var allowed_commands = ['clear', 'help', 'me', 'nick', 'register'];
    if (this.config.get('changesubject') || ['owner', 'admin'].includes(this.getOwnAffiliation())) {
      allowed_commands = [].concat(muc_toConsumableArray(allowed_commands), ['subject', 'topic']);
    }
    var occupant = this.occupants.findWhere({
      'jid': shared_converse.bare_jid
    });
    if (this.verifyAffiliations(['owner'], occupant, false)) {
      allowed_commands = allowed_commands.concat(OWNER_COMMANDS).concat(ADMIN_COMMANDS);
    } else if (this.verifyAffiliations(['admin'], occupant, false)) {
      allowed_commands = allowed_commands.concat(ADMIN_COMMANDS);
    }
    if (this.verifyRoles(['moderator'], occupant, false)) {
      allowed_commands = allowed_commands.concat(MODERATOR_COMMANDS).concat(VISITOR_COMMANDS);
    } else if (!this.verifyRoles(['visitor', 'participant', 'moderator'], occupant, false)) {
      allowed_commands = allowed_commands.concat(VISITOR_COMMANDS);
    }
    allowed_commands.sort();
    if (Array.isArray(shared_api.settings.get('muc_disable_slash_commands'))) {
      return allowed_commands.filter(function (c) {
        return !shared_api.settings.get('muc_disable_slash_commands').includes(c);
      });
    } else {
      return allowed_commands;
    }
  },
  verifyAffiliations: function verifyAffiliations(affiliations, occupant) {
    var show_error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
    var __ = shared_converse.__;
    if (!Array.isArray(affiliations)) {
      throw new TypeError('affiliations must be an Array');
    }
    if (!affiliations.length) {
      return true;
    }
    occupant = occupant || this.occupants.findWhere({
      'jid': shared_converse.bare_jid
    });
    if (occupant) {
      var a = occupant.get('affiliation');
      if (affiliations.includes(a)) {
        return true;
      }
    }
    if (show_error) {
      var message = __('Forbidden: you do not have the necessary affiliation in order to do that.');
      this.createMessage({
        message: message,
        'type': 'error'
      });
    }
    return false;
  },
  verifyRoles: function verifyRoles(roles, occupant) {
    var show_error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
    var __ = shared_converse.__;
    if (!Array.isArray(roles)) {
      throw new TypeError('roles must be an Array');
    }
    if (!roles.length) {
      return true;
    }
    occupant = occupant || this.occupants.findWhere({
      'jid': shared_converse.bare_jid
    });
    if (occupant) {
      var role = occupant.get('role');
      if (roles.includes(role)) {
        return true;
      }
    }
    if (show_error) {
      var message = __('Forbidden: you do not have the necessary role in order to do that.');
      this.createMessage({
        message: message,
        'type': 'error',
        'is_ephemeral': 20000
      });
    }
    return false;
  },
  /**
   * Returns the `role` which the current user has in this MUC
   * @private
   * @method _converse.ChatRoom#getOwnRole
   * @returns { ('none'|'visitor'|'participant'|'moderator') }
   */
  getOwnRole: function getOwnRole() {
    var _this$getOwnOccupant, _this$getOwnOccupant$;
    return (_this$getOwnOccupant = this.getOwnOccupant()) === null || _this$getOwnOccupant === void 0 ? void 0 : (_this$getOwnOccupant$ = _this$getOwnOccupant.attributes) === null || _this$getOwnOccupant$ === void 0 ? void 0 : _this$getOwnOccupant$.role;
  },
  /**
   * Returns the `affiliation` which the current user has in this MUC
   * @private
   * @method _converse.ChatRoom#getOwnAffiliation
   * @returns { ('none'|'outcast'|'member'|'admin'|'owner') }
   */
  getOwnAffiliation: function getOwnAffiliation() {
    var _this$getOwnOccupant2, _this$getOwnOccupant3;
    return ((_this$getOwnOccupant2 = this.getOwnOccupant()) === null || _this$getOwnOccupant2 === void 0 ? void 0 : (_this$getOwnOccupant3 = _this$getOwnOccupant2.attributes) === null || _this$getOwnOccupant3 === void 0 ? void 0 : _this$getOwnOccupant3.affiliation) || 'none';
  },
  /**
   * Get the {@link _converse.ChatRoomOccupant} instance which
   * represents the current user.
   * @method _converse.ChatRoom#getOwnOccupant
   * @returns { _converse.ChatRoomOccupant }
   */
  getOwnOccupant: function getOwnOccupant() {
    return this.occupants.getOwnOccupant();
  },
  /**
   * Send a presence stanza to update the user's nickname in this MUC.
   * @param { String } nick
   */
  setNickname: function setNickname(nick) {
    var _this28 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee20() {
      var old_nick, __, message, jid;
      return muc_regeneratorRuntime().wrap(function _callee20$(_context20) {
        while (1) switch (_context20.prev = _context20.next) {
          case 0:
            _context20.t0 = shared_api.settings.get('auto_register_muc_nickname');
            if (!_context20.t0) {
              _context20.next = 5;
              break;
            }
            _context20.next = 4;
            return shared_api.disco.supports(external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER, _this28.get('jid'));
          case 4:
            _context20.t0 = _context20.sent;
          case 5:
            if (!_context20.t0) {
              _context20.next = 21;
              break;
            }
            old_nick = _this28.get('nick');
            _this28.set({
              nick: nick
            });
            _context20.prev = 8;
            _context20.next = 11;
            return _this28.registerNickname();
          case 11:
            _context20.next = 21;
            break;
          case 13:
            _context20.prev = 13;
            _context20.t1 = _context20["catch"](8);
            __ = shared_converse.__;
            log.error(_context20.t1);
            message = __("Error: couldn't register new nickname in members only room");
            _this28.createMessage({
              message: message,
              'type': 'error',
              'is_ephemeral': true
            });
            _this28.set({
              'nick': old_nick
            });
            return _context20.abrupt("return");
          case 21:
            jid = external_strophe_namespaceObject.Strophe.getBareJidFromJid(_this28.get('jid'));
            shared_api.send((0,external_strophe_namespaceObject.$pres)({
              'from': shared_converse.connection.jid,
              'to': "".concat(jid, "/").concat(nick),
              'id': getUniqueId()
            }).tree());
          case 23:
          case "end":
            return _context20.stop();
        }
      }, _callee20, null, [[8, 13]]);
    }))();
  },
  /**
   * Send an IQ stanza to modify an occupant's role
   * @private
   * @method _converse.ChatRoom#setRole
   * @param { _converse.ChatRoomOccupant } occupant
   * @param { String } role
   * @param { String } reason
   * @param { function } onSuccess - callback for a succesful response
   * @param { function } onError - callback for an error response
   */
  setRole: function setRole(occupant, role, reason, onSuccess, onError) {
    var item = (0,external_strophe_namespaceObject.$build)('item', {
      'nick': occupant.get('nick'),
      role: role
    });
    var iq = (0,external_strophe_namespaceObject.$iq)({
      'to': this.get('jid'),
      'type': 'set'
    }).c('query', {
      xmlns: external_strophe_namespaceObject.Strophe.NS.MUC_ADMIN
    }).cnode(item.node);
    if (reason !== null) {
      iq.c('reason', reason);
    }
    return shared_api.sendIQ(iq).then(onSuccess).catch(onError);
  },
  /**
   * @private
   * @method _converse.ChatRoom#getOccupant
   * @param { String } nickname_or_jid - The nickname or JID of the occupant to be returned
   * @returns { _converse.ChatRoomOccupant }
   */
  getOccupant: function getOccupant(nickname_or_jid) {
    return muc_u.isValidJID(nickname_or_jid) ? this.getOccupantByJID(nickname_or_jid) : this.getOccupantByNickname(nickname_or_jid);
  },
  /**
   * Return an array of occupant models that have the required role
   * @private
   * @method _converse.ChatRoom#getOccupantsWithRole
   * @param { String } role
   * @returns { _converse.ChatRoomOccupant[] }
   */
  getOccupantsWithRole: function getOccupantsWithRole(role) {
    return this.getOccupantsSortedBy('nick').filter(function (o) {
      return o.get('role') === role;
    }).map(function (item) {
      return {
        'jid': item.get('jid'),
        'nick': item.get('nick'),
        'role': item.get('role')
      };
    });
  },
  /**
   * Return an array of occupant models that have the required affiliation
   * @private
   * @method _converse.ChatRoom#getOccupantsWithAffiliation
   * @param { String } affiliation
   * @returns { _converse.ChatRoomOccupant[] }
   */
  getOccupantsWithAffiliation: function getOccupantsWithAffiliation(affiliation) {
    return this.getOccupantsSortedBy('nick').filter(function (o) {
      return o.get('affiliation') === affiliation;
    }).map(function (item) {
      return {
        'jid': item.get('jid'),
        'nick': item.get('nick'),
        'affiliation': item.get('affiliation')
      };
    });
  },
  /**
   * Return an array of occupant models, sorted according to the passed-in attribute.
   * @private
   * @method _converse.ChatRoom#getOccupantsSortedBy
   * @param { String } attr - The attribute to sort the returned array by
   * @returns { _converse.ChatRoomOccupant[] }
   */
  getOccupantsSortedBy: function getOccupantsSortedBy(attr) {
    return Array.from(this.occupants.models).sort(function (a, b) {
      return a.get(attr) < b.get(attr) ? -1 : a.get(attr) > b.get(attr) ? 1 : 0;
    });
  },
  /**
   * Fetch the lists of users with the given affiliations.
   * Then compute the delta between those users and
   * the passed in members, and if it exists, send the delta
   * to the XMPP server to update the member list.
   * @private
   * @method _converse.ChatRoom#updateMemberLists
   * @param { object } members - Map of member jids and affiliations.
   * @returns { Promise }
   *  A promise which is resolved once the list has been
   *  updated or once it's been established there's no need
   *  to update the list.
   */
  updateMemberLists: function updateMemberLists(members) {
    var _this29 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee21() {
      var muc_jid, all_affiliations, aff_lists, old_members;
      return muc_regeneratorRuntime().wrap(function _callee21$(_context21) {
        while (1) switch (_context21.prev = _context21.next) {
          case 0:
            muc_jid = _this29.get('jid');
            all_affiliations = ['member', 'admin', 'owner'];
            _context21.next = 4;
            return Promise.all(all_affiliations.map(function (a) {
              return getAffiliationList(a, muc_jid);
            }));
          case 4:
            aff_lists = _context21.sent;
            old_members = aff_lists.reduce(function (acc, val) {
              return muc_u.isErrorObject(val) ? acc : [].concat(muc_toConsumableArray(val), muc_toConsumableArray(acc));
            }, []);
            _context21.next = 8;
            return setAffiliations(muc_jid, computeAffiliationsDelta(true, false, members, old_members));
          case 8:
            _context21.next = 10;
            return _this29.occupants.fetchMembers();
          case 10:
          case "end":
            return _context21.stop();
        }
      }, _callee21);
    }))();
  },
  /**
   * Given a nick name, save it to the model state, otherwise, look
   * for a server-side reserved nickname or default configured
   * nickname and if found, persist that to the model state.
   * @private
   * @method _converse.ChatRoom#getAndPersistNickname
   * @returns { Promise<string> } A promise which resolves with the nickname
   */
  getAndPersistNickname: function getAndPersistNickname(nick) {
    var _this30 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee22() {
      return muc_regeneratorRuntime().wrap(function _callee22$(_context22) {
        while (1) switch (_context22.prev = _context22.next) {
          case 0:
            _context22.t1 = nick || _this30.get('nick');
            if (_context22.t1) {
              _context22.next = 5;
              break;
            }
            _context22.next = 4;
            return _this30.getReservedNick();
          case 4:
            _context22.t1 = _context22.sent;
          case 5:
            _context22.t0 = _context22.t1;
            if (_context22.t0) {
              _context22.next = 8;
              break;
            }
            _context22.t0 = shared_converse.getDefaultMUCNickname();
          case 8:
            nick = _context22.t0;
            if (nick) safeSave(_this30, {
              nick: nick
            }, {
              'silent': true
            });
            return _context22.abrupt("return", nick);
          case 11:
          case "end":
            return _context22.stop();
        }
      }, _callee22);
    }))();
  },
  /**
   * Use service-discovery to ask the XMPP server whether
   * this user has a reserved nickname for this groupchat.
   * If so, we'll use that, otherwise we render the nickname form.
   * @private
   * @method _converse.ChatRoom#getReservedNick
   * @returns { Promise<string> } A promise which resolves with the reserved nick or null
   */
  getReservedNick: function getReservedNick() {
    var _this31 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee23() {
      var stanza, result, identity_el;
      return muc_regeneratorRuntime().wrap(function _callee23$(_context23) {
        while (1) switch (_context23.prev = _context23.next) {
          case 0:
            stanza = (0,external_strophe_namespaceObject.$iq)({
              'to': _this31.get('jid'),
              'from': shared_converse.connection.jid,
              'type': 'get'
            }).c('query', {
              'xmlns': external_strophe_namespaceObject.Strophe.NS.DISCO_INFO,
              'node': 'x-roomuser-item'
            });
            _context23.next = 3;
            return shared_api.sendIQ(stanza, null, false);
          case 3:
            result = _context23.sent;
            if (!muc_u.isErrorObject(result)) {
              _context23.next = 6;
              break;
            }
            throw result;
          case 6:
            // Result might be undefined due to a timeout
            identity_el = result === null || result === void 0 ? void 0 : result.querySelector('query[node="x-roomuser-item"] identity');
            return _context23.abrupt("return", identity_el ? identity_el.getAttribute('name') : null);
          case 8:
          case "end":
            return _context23.stop();
        }
      }, _callee23);
    }))();
  },
  /**
   * Send an IQ stanza to the MUC to register this user's nickname.
   * This sets the user's affiliation to 'member' (if they weren't affiliated
   * before) and reserves the nickname for this user, thereby preventing other
   * users from using it in this MUC.
   * See https://xmpp.org/extensions/xep-0045.html#register
   * @private
   * @method _converse.ChatRoom#registerNickname
   */
  registerNickname: function registerNickname() {
    var _this32 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee24() {
      var __, nick, jid, iq, err_msg, required_fields;
      return muc_regeneratorRuntime().wrap(function _callee24$(_context24) {
        while (1) switch (_context24.prev = _context24.next) {
          case 0:
            __ = shared_converse.__;
            nick = _this32.get('nick');
            jid = _this32.get('jid');
            _context24.prev = 3;
            _context24.next = 6;
            return shared_api.sendIQ((0,external_strophe_namespaceObject.$iq)({
              'to': jid,
              'type': 'get'
            }).c('query', {
              'xmlns': external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER
            }));
          case 6:
            iq = _context24.sent;
            _context24.next = 14;
            break;
          case 9:
            _context24.prev = 9;
            _context24.t0 = _context24["catch"](3);
            if (external_sizzle_default()("not-allowed[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), _context24.t0).length) {
              err_msg = __("You're not allowed to register yourself in this groupchat.");
            } else if (external_sizzle_default()("registration-required[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), _context24.t0).length) {
              err_msg = __("You're not allowed to register in this groupchat because it's members-only.");
            }
            log.error(_context24.t0);
            return _context24.abrupt("return", err_msg);
          case 14:
            required_fields = external_sizzle_default()('field required', iq).map(function (f) {
              return f.parentElement;
            });
            if (!(required_fields.length > 1 && required_fields[0].getAttribute('var') !== 'muc#register_roomnick')) {
              _context24.next = 17;
              break;
            }
            return _context24.abrupt("return", log.error("Can't register the user register in the groupchat ".concat(jid, " due to the required fields")));
          case 17:
            _context24.prev = 17;
            _context24.next = 20;
            return shared_api.sendIQ((0,external_strophe_namespaceObject.$iq)({
              'to': jid,
              'type': 'set'
            }).c('query', {
              'xmlns': external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER
            }).c('x', {
              'xmlns': external_strophe_namespaceObject.Strophe.NS.XFORM,
              'type': 'submit'
            }).c('field', {
              'var': 'FORM_TYPE'
            }).c('value').t('http://jabber.org/protocol/muc#register').up().up().c('field', {
              'var': 'muc#register_roomnick'
            }).c('value').t(nick));
          case 20:
            _context24.next = 28;
            break;
          case 22:
            _context24.prev = 22;
            _context24.t1 = _context24["catch"](17);
            if (external_sizzle_default()("service-unavailable[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), _context24.t1).length) {
              err_msg = __("Can't register your nickname in this groupchat, it doesn't support registration.");
            } else if (external_sizzle_default()("bad-request[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), _context24.t1).length) {
              err_msg = __("Can't register your nickname in this groupchat, invalid data form supplied.");
            }
            log.error(err_msg);
            log.error(_context24.t1);
            return _context24.abrupt("return", err_msg);
          case 28:
          case "end":
            return _context24.stop();
        }
      }, _callee24, null, [[3, 9], [17, 22]]);
    }))();
  },
  /**
   * Check whether we should unregister the user from this MUC, and if so,
   * call { @link _converse.ChatRoom#sendUnregistrationIQ }
   * @method _converse.ChatRoom#unregisterNickname
   */
  unregisterNickname: function unregisterNickname() {
    var _this33 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee25() {
      return muc_regeneratorRuntime().wrap(function _callee25$(_context25) {
        while (1) switch (_context25.prev = _context25.next) {
          case 0:
            if (!(shared_api.settings.get('auto_register_muc_nickname') === 'unregister')) {
              _context25.next = 12;
              break;
            }
            _context25.prev = 1;
            _context25.next = 4;
            return shared_api.disco.supports(external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER, _this33.get('jid'));
          case 4:
            if (!_context25.sent) {
              _context25.next = 7;
              break;
            }
            _context25.next = 7;
            return _this33.sendUnregistrationIQ();
          case 7:
            _context25.next = 12;
            break;
          case 9:
            _context25.prev = 9;
            _context25.t0 = _context25["catch"](1);
            log.error(_context25.t0);
          case 12:
          case "end":
            return _context25.stop();
        }
      }, _callee25, null, [[1, 9]]);
    }))();
  },
  /**
   * Send an IQ stanza to the MUC to unregister this user's nickname.
   * If the user had a 'member' affiliation, it'll be removed and their
   * nickname will no longer be reserved and can instead be used (and
   * registered) by other users.
   * @method _converse.ChatRoom#sendUnregistrationIQ
   */
  sendUnregistrationIQ: function sendUnregistrationIQ() {
    var iq = (0,external_strophe_namespaceObject.$iq)({
      'to': this.get('jid'),
      'type': 'set'
    }).c('query', {
      'xmlns': external_strophe_namespaceObject.Strophe.NS.MUC_REGISTER
    }).c('remove');
    return shared_api.sendIQ(iq).catch(function (e) {
      return log.error(e);
    });
  },
  /**
   * Given a presence stanza, update the occupant model based on its contents.
   * @private
   * @method _converse.ChatRoom#updateOccupantsOnPresence
   * @param { Element } pres - The presence stanza
   */
  updateOccupantsOnPresence: function updateOccupantsOnPresence(pres) {
    var _occupant$attributes, _occupant$attributes2;
    var data = parseMUCPresence(pres, this);
    if (data.type === 'error' || !data.jid && !data.nick && !data.occupant_id) {
      return true;
    }
    var occupant = this.occupants.findOccupant(data);
    // Destroy an unavailable occupant if this isn't a nick change operation and if they're not affiliated
    if (data.type === 'unavailable' && occupant && !data.states.includes(public_converse.MUC_NICK_CHANGED_CODE) && !['admin', 'owner', 'member'].includes(data['affiliation'])) {
      // Before destroying we set the new data, so that we can show the disconnection message
      occupant.set(data);
      occupant.destroy();
      return;
    }
    var jid = data.jid || '';
    var attributes = muc_objectSpread(muc_objectSpread({}, data), {}, {
      'jid': external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid) || (occupant === null || occupant === void 0 ? void 0 : (_occupant$attributes = occupant.attributes) === null || _occupant$attributes === void 0 ? void 0 : _occupant$attributes.jid),
      'resource': external_strophe_namespaceObject.Strophe.getResourceFromJid(jid) || (occupant === null || occupant === void 0 ? void 0 : (_occupant$attributes2 = occupant.attributes) === null || _occupant$attributes2 === void 0 ? void 0 : _occupant$attributes2.resource)
    });
    if (data.is_me) {
      var modified = false;
      if (data.states.includes(public_converse.MUC_NICK_CHANGED_CODE)) {
        modified = true;
        this.set('nick', data.nick);
      }
      if (this.features.get(external_strophe_namespaceObject.Strophe.NS.OCCUPANTID) && this.get('occupant-id') !== data.occupant_id) {
        modified = true;
        this.set('occupant_id', data.occupant_id);
      }
      modified && this.save();
    }
    if (occupant) {
      occupant.save(attributes);
    } else {
      this.occupants.create(attributes);
    }
  },
  fetchFeaturesIfConfigurationChanged: function fetchFeaturesIfConfigurationChanged(stanza) {
    // 104: configuration change
    // 170: logging enabled
    // 171: logging disabled
    // 172: room no longer anonymous
    // 173: room now semi-anonymous
    // 174: room now fully anonymous
    var codes = ['104', '170', '171', '172', '173', '174'];
    if (external_sizzle_default()('status', stanza).filter(function (e) {
      return codes.includes(e.getAttribute('status'));
    }).length) {
      this.refreshDiscoInfo();
    }
  },
  /**
   * Given two JIDs, which can be either user JIDs or MUC occupant JIDs,
   * determine whether they belong to the same user.
   * @private
   * @method _converse.ChatRoom#isSameUser
   * @param { String } jid1
   * @param { String } jid2
   * @returns { Boolean }
   */
  isSameUser: function isSameUser(jid1, jid2) {
    var bare_jid1 = external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid1);
    var bare_jid2 = external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid2);
    var resource1 = external_strophe_namespaceObject.Strophe.getResourceFromJid(jid1);
    var resource2 = external_strophe_namespaceObject.Strophe.getResourceFromJid(jid2);
    if (muc_u.isSameBareJID(jid1, jid2)) {
      if (bare_jid1 === this.get('jid')) {
        // MUC JIDs
        return resource1 === resource2;
      } else {
        return true;
      }
    } else {
      var occupant1 = bare_jid1 === this.get('jid') ? this.occupants.findOccupant({
        'nick': resource1
      }) : this.occupants.findOccupant({
        'jid': bare_jid1
      });
      var occupant2 = bare_jid2 === this.get('jid') ? this.occupants.findOccupant({
        'nick': resource2
      }) : this.occupants.findOccupant({
        'jid': bare_jid2
      });
      return occupant1 === occupant2;
    }
  },
  isSubjectHidden: function isSubjectHidden() {
    var _this34 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee26() {
      var jids;
      return muc_regeneratorRuntime().wrap(function _callee26$(_context26) {
        while (1) switch (_context26.prev = _context26.next) {
          case 0:
            _context26.next = 2;
            return shared_api.user.settings.get('mucs_with_hidden_subject', []);
          case 2:
            jids = _context26.sent;
            return _context26.abrupt("return", jids.includes(_this34.get('jid')));
          case 4:
          case "end":
            return _context26.stop();
        }
      }, _callee26);
    }))();
  },
  toggleSubjectHiddenState: function toggleSubjectHiddenState() {
    var _this35 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee27() {
      var muc_jid, jids;
      return muc_regeneratorRuntime().wrap(function _callee27$(_context27) {
        while (1) switch (_context27.prev = _context27.next) {
          case 0:
            muc_jid = _this35.get('jid');
            _context27.next = 3;
            return shared_api.user.settings.get('mucs_with_hidden_subject', []);
          case 3:
            jids = _context27.sent;
            if (jids.includes(_this35.get('jid'))) {
              shared_api.user.settings.set('mucs_with_hidden_subject', jids.filter(function (jid) {
                return jid !== muc_jid;
              }));
            } else {
              shared_api.user.settings.set('mucs_with_hidden_subject', [].concat(muc_toConsumableArray(jids), [muc_jid]));
            }
          case 5:
          case "end":
            return _context27.stop();
        }
      }, _callee27);
    }))();
  },
  /**
   * Handle a possible subject change and return `true` if so.
   * @private
   * @method _converse.ChatRoom#handleSubjectChange
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMUCMessage}
   */
  handleSubjectChange: function handleSubjectChange(attrs) {
    var _this36 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee28() {
      var __, subject, author, message, prev_msg;
      return muc_regeneratorRuntime().wrap(function _callee28$(_context28) {
        while (1) switch (_context28.prev = _context28.next) {
          case 0:
            __ = shared_converse.__;
            if (!(typeof attrs.subject === 'string' && !attrs.thread && !attrs.message)) {
              _context28.next = 14;
              break;
            }
            // https://xmpp.org/extensions/xep-0045.html#subject-mod
            // -----------------------------------------------------
            // The subject is changed by sending a message of type "groupchat" to the <room@service>,
            // where the <message/> MUST contain a <subject/> element that specifies the new subject but
            // MUST NOT contain a <body/> element (or a <thread/> element).
            subject = attrs.subject;
            author = attrs.nick;
            safeSave(_this36, {
              'subject': {
                author: author,
                'text': attrs.subject || ''
              }
            });
            if (!(!attrs.is_delayed && author)) {
              _context28.next = 13;
              break;
            }
            message = subject ? __('Topic set by %1$s', author) : __('Topic cleared by %1$s', author);
            prev_msg = _this36.messages.last();
            if ((prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('nick')) !== attrs.nick || (prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('type')) !== 'info' || (prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('message')) !== message) {
              _this36.createMessage({
                message: message,
                'nick': attrs.nick,
                'type': 'info',
                'is_ephemeral': true
              });
            }
            _context28.next = 11;
            return _this36.isSubjectHidden();
          case 11:
            if (!_context28.sent) {
              _context28.next = 13;
              break;
            }
            _this36.toggleSubjectHiddenState();
          case 13:
            return _context28.abrupt("return", true);
          case 14:
            return _context28.abrupt("return", false);
          case 15:
          case "end":
            return _context28.stop();
        }
      }, _callee28);
    }))();
  },
  /**
   * Set the subject for this {@link _converse.ChatRoom}
   * @private
   * @method _converse.ChatRoom#setSubject
   * @param { String } value
   */
  setSubject: function setSubject() {
    var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    shared_api.send((0,external_strophe_namespaceObject.$msg)({
      to: this.get('jid'),
      from: shared_converse.connection.jid,
      type: 'groupchat'
    }).c('subject', {
      xmlns: 'jabber:client'
    }).t(value).tree());
  },
  /**
   * Is this a chat state notification that can be ignored,
   * because it's old or because it's from us.
   * @private
   * @method _converse.ChatRoom#ignorableCSN
   * @param { Object } attrs - The message attributes
   */
  ignorableCSN: function ignorableCSN(attrs) {
    return attrs.chat_state && !attrs.body && (attrs.is_delayed || this.isOwnMessage(attrs));
  },
  /**
   * Determines whether the message is from ourselves by checking
   * the `from` attribute. Doesn't check the `type` attribute.
   * @private
   * @method _converse.ChatRoom#isOwnMessage
   * @param { Object|Element|_converse.Message } msg
   * @returns { boolean }
   */
  isOwnMessage: function isOwnMessage(msg) {
    var from;
    if (lodash_es_isElement(msg)) {
      from = msg.getAttribute('from');
    } else if (msg instanceof shared_converse.Message) {
      from = msg.get('from');
    } else {
      from = msg.from;
    }
    return external_strophe_namespaceObject.Strophe.getResourceFromJid(from) == this.get('nick');
  },
  getUpdatedMessageAttributes: function getUpdatedMessageAttributes(message, attrs) {
    var new_attrs = muc_objectSpread(muc_objectSpread({}, shared_converse.ChatBox.prototype.getUpdatedMessageAttributes.call(this, message, attrs)), lodash_es_pick(attrs, ['from_muc', 'occupant_id']));
    if (this.isOwnMessage(attrs)) {
      var stanza_id_keys = Object.keys(attrs).filter(function (k) {
        return k.startsWith('stanza_id');
      });
      Object.assign(new_attrs, lodash_es_pick(attrs, stanza_id_keys));
      if (!message.get('received')) {
        new_attrs.received = new Date().toISOString();
      }
    }
    return new_attrs;
  },
  /**
   * Send a MUC-0410 MUC Self-Ping stanza to room to determine
   * whether we're still joined.
   * @async
   * @private
   * @method _converse.ChatRoom#isJoined
   * @returns {Promise<boolean>}
   */
  isJoined: function isJoined() {
    var _this37 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee29() {
      return muc_regeneratorRuntime().wrap(function _callee29$(_context29) {
        while (1) switch (_context29.prev = _context29.next) {
          case 0:
            if (_this37.isEntered()) {
              _context29.next = 3;
              break;
            }
            log.info("isJoined: not pinging MUC ".concat(_this37.get('jid'), " since we're not entered"));
            return _context29.abrupt("return", false);
          case 3:
            if (shared_api.connection.connected()) {
              _context29.next = 6;
              break;
            }
            _context29.next = 6;
            return new Promise(function (resolve) {
              return shared_api.listen.once('reconnected', resolve);
            });
          case 6:
            return _context29.abrupt("return", shared_api.ping("".concat(_this37.get('jid'), "/").concat(_this37.get('nick'))));
          case 7:
          case "end":
            return _context29.stop();
        }
      }, _callee29);
    }))();
  },
  /**
   * Sends a status update presence (i.e. based on the `<show>` element)
   * @method _converse.ChatRoom#sendStatusPresence
   * @param { String } type
   * @param { String } [status] - An optional status message
   * @param { Element[]|Strophe.Builder[]|Element|Strophe.Builder } [child_nodes]
   *  Nodes(s) to be added as child nodes of the `presence` XML element.
   */
  sendStatusPresence: function sendStatusPresence(type, status, child_nodes) {
    var _this38 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee30() {
      var presence;
      return muc_regeneratorRuntime().wrap(function _callee30$(_context30) {
        while (1) switch (_context30.prev = _context30.next) {
          case 0:
            if (!(_this38.session.get('connection_status') === ROOMSTATUS.ENTERED)) {
              _context30.next = 6;
              break;
            }
            _context30.next = 3;
            return shared_converse.xmppstatus.constructPresence(type, _this38.getRoomJIDAndNick(), status);
          case 3:
            presence = _context30.sent;
            child_nodes === null || child_nodes === void 0 ? void 0 : child_nodes.map(function (c) {
              var _c$tree;
              return (_c$tree = c === null || c === void 0 ? void 0 : c.tree()) !== null && _c$tree !== void 0 ? _c$tree : c;
            }).forEach(function (c) {
              return presence.cnode(c).up();
            });
            shared_api.send(presence);
          case 6:
          case "end":
            return _context30.stop();
        }
      }, _callee30);
    }))();
  },
  /**
   * Check whether we're still joined and re-join if not
   * @method _converse.ChatRoom#rejoinIfNecessary
   */
  rejoinIfNecessary: function rejoinIfNecessary() {
    var _this39 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee31() {
      return muc_regeneratorRuntime().wrap(function _callee31$(_context31) {
        while (1) switch (_context31.prev = _context31.next) {
          case 0:
            if (!_this39.isRAICandidate()) {
              _context31.next = 3;
              break;
            }
            log.debug("rejoinIfNecessary: not rejoining hidden MUC \"".concat(_this39.get('jid'), "\" since we're using RAI"));
            return _context31.abrupt("return", true);
          case 3:
            _context31.next = 5;
            return _this39.isJoined();
          case 5:
            if (_context31.sent) {
              _context31.next = 8;
              break;
            }
            _this39.rejoin();
            return _context31.abrupt("return", true);
          case 8:
          case "end":
            return _context31.stop();
        }
      }, _callee31);
    }))();
  },
  /**
   * @private
   * @method _converse.ChatRoom#shouldShowErrorMessage
   * @returns {Promise<boolean>}
   */
  shouldShowErrorMessage: function shouldShowErrorMessage(attrs) {
    var _this40 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee32() {
      return muc_regeneratorRuntime().wrap(function _callee32$(_context32) {
        while (1) switch (_context32.prev = _context32.next) {
          case 0:
            if (!(attrs.error_type === 'Decryption')) {
              _context32.next = 9;
              break;
            }
            if (!(attrs.error_message === "Message key not found. The counter was repeated or the key was not filled.")) {
              _context32.next = 5;
              break;
            }
            return _context32.abrupt("return", false);
          case 5:
            if (!(attrs.error_condition === 'not-encrypted-for-this-device')) {
              _context32.next = 7;
              break;
            }
            return _context32.abrupt("return", false);
          case 7:
            _context32.next = 16;
            break;
          case 9:
            _context32.t0 = attrs.error_condition === 'not-acceptable';
            if (!_context32.t0) {
              _context32.next = 14;
              break;
            }
            _context32.next = 13;
            return _this40.rejoinIfNecessary();
          case 13:
            _context32.t0 = _context32.sent;
          case 14:
            if (!_context32.t0) {
              _context32.next = 16;
              break;
            }
            return _context32.abrupt("return", false);
          case 16:
            return _context32.abrupt("return", shared_converse.ChatBox.prototype.shouldShowErrorMessage.call(_this40, attrs));
          case 17:
          case "end":
            return _context32.stop();
        }
      }, _callee32);
    }))();
  },
  /**
   * Looks whether we already have a moderation message for this
   * incoming message. If so, it's considered "dangling" because
   * it probably hasn't been applied to anything yet, given that
   * the relevant message is only coming in now.
   * @private
   * @method _converse.ChatRoom#findDanglingModeration
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMUCMessage}
   * @returns { _converse.ChatRoomMessage }
   */
  findDanglingModeration: function findDanglingModeration(attrs) {
    if (!this.messages.length) {
      return null;
    }
    // Only look for dangling moderation if there are newer
    // messages than this one, since moderation come after.
    if (this.messages.last().get('time') > attrs.time) {
      // Search from latest backwards
      var messages = Array.from(this.messages.models);
      var stanza_id = attrs["stanza_id ".concat(this.get('jid'))];
      if (!stanza_id) {
        return null;
      }
      messages.reverse();
      return messages.find(function (_ref2) {
        var attributes = _ref2.attributes;
        return attributes.moderated === 'retracted' && attributes.moderated_id === stanza_id && attributes.moderated_by;
      });
    }
  },
  /**
   * Handles message moderation based on the passed in attributes.
   * @private
   * @method _converse.ChatRoom#handleModeration
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMUCMessage}
   * @returns { Boolean } Returns `true` or `false` depending on
   *  whether a message was moderated or not.
   */
  handleModeration: function handleModeration(attrs) {
    var _this41 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee33() {
      var MODERATION_ATTRIBUTES, query, key, message, _message3, moderation_attrs, new_attrs;
      return muc_regeneratorRuntime().wrap(function _callee33$(_context33) {
        while (1) switch (_context33.prev = _context33.next) {
          case 0:
            MODERATION_ATTRIBUTES = ['editable', 'moderated', 'moderated_by', 'moderated_id', 'moderation_reason'];
            if (!(attrs.moderated === 'retracted')) {
              _context33.next = 15;
              break;
            }
            query = {};
            key = "stanza_id ".concat(_this41.get('jid'));
            query[key] = attrs.moderated_id;
            message = _this41.messages.findWhere(query);
            if (message) {
              _context33.next = 11;
              break;
            }
            attrs['dangling_moderation'] = true;
            _context33.next = 10;
            return _this41.createMessage(attrs);
          case 10:
            return _context33.abrupt("return", true);
          case 11:
            message.save(lodash_es_pick(attrs, MODERATION_ATTRIBUTES));
            return _context33.abrupt("return", true);
          case 15:
            // Check if we have dangling moderation message
            _message3 = _this41.findDanglingModeration(attrs);
            if (!_message3) {
              _context33.next = 22;
              break;
            }
            moderation_attrs = lodash_es_pick(_message3.attributes, MODERATION_ATTRIBUTES);
            new_attrs = Object.assign({
              'dangling_moderation': false
            }, attrs, moderation_attrs);
            delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created
            _message3.save(new_attrs);
            return _context33.abrupt("return", true);
          case 22:
            return _context33.abrupt("return", false);
          case 23:
          case "end":
            return _context33.stop();
        }
      }, _callee33);
    }))();
  },
  getNotificationsText: function getNotificationsText() {
    var _this42 = this;
    var __ = shared_converse.__;
    var actors_per_state = this.notifications.toJSON();
    var role_changes = shared_api.settings.get('muc_show_info_messages').filter(function (role_change) {
      return public_converse.MUC_ROLE_CHANGES_LIST.includes(role_change);
    });
    var join_leave_events = shared_api.settings.get('muc_show_info_messages').filter(function (join_leave_event) {
      return public_converse.MUC_TRAFFIC_STATES_LIST.includes(join_leave_event);
    });
    var states = [].concat(muc_toConsumableArray(public_converse.CHAT_STATES), muc_toConsumableArray(join_leave_events), muc_toConsumableArray(role_changes));
    return states.reduce(function (result, state) {
      var existing_actors = actors_per_state[state];
      if (!(existing_actors !== null && existing_actors !== void 0 && existing_actors.length)) {
        return result;
      }
      var actors = existing_actors.map(function (a) {
        var _this42$getOccupant;
        return ((_this42$getOccupant = _this42.getOccupant(a)) === null || _this42$getOccupant === void 0 ? void 0 : _this42$getOccupant.getDisplayName()) || a;
      });
      if (actors.length === 1) {
        if (state === 'composing') {
          return "".concat(result).concat(__('%1$s is typing', actors[0]), "\n");
        } else if (state === 'paused') {
          return "".concat(result).concat(__('%1$s has stopped typing', actors[0]), "\n");
        } else if (state === shared_converse.GONE) {
          return "".concat(result).concat(__('%1$s has gone away', actors[0]), "\n");
        } else if (state === 'entered') {
          return "".concat(result).concat(__('%1$s has entered the groupchat', actors[0]), "\n");
        } else if (state === 'exited') {
          return "".concat(result).concat(__('%1$s has left the groupchat', actors[0]), "\n");
        } else if (state === 'op') {
          return "".concat(result).concat(__('%1$s is now a moderator', actors[0]), "\n");
        } else if (state === 'deop') {
          return "".concat(result).concat(__('%1$s is no longer a moderator', actors[0]), "\n");
        } else if (state === 'voice') {
          return "".concat(result).concat(__('%1$s has been given a voice', actors[0]), "\n");
        } else if (state === 'mute') {
          return "".concat(result).concat(__('%1$s has been muted', actors[0]), "\n");
        }
      } else if (actors.length > 1) {
        var actors_str;
        if (actors.length > 3) {
          actors_str = "".concat(Array.from(actors).slice(0, 2).join(', '), " and others");
        } else {
          var last_actor = actors.pop();
          actors_str = __('%1$s and %2$s', actors.join(', '), last_actor);
        }
        if (state === 'composing') {
          return "".concat(result).concat(__('%1$s are typing', actors_str), "\n");
        } else if (state === 'paused') {
          return "".concat(result).concat(__('%1$s have stopped typing', actors_str), "\n");
        } else if (state === shared_converse.GONE) {
          return "".concat(result).concat(__('%1$s have gone away', actors_str), "\n");
        } else if (state === 'entered') {
          return "".concat(result).concat(__('%1$s have entered the groupchat', actors_str), "\n");
        } else if (state === 'exited') {
          return "".concat(result).concat(__('%1$s have left the groupchat', actors_str), "\n");
        } else if (state === 'op') {
          return "".concat(result).concat(__('%1$s are now moderators', actors[0]), "\n");
        } else if (state === 'deop') {
          return "".concat(result).concat(__('%1$s are no longer moderators', actors[0]), "\n");
        } else if (state === 'voice') {
          return "".concat(result).concat(__('%1$s have been given voices', actors[0]), "\n");
        } else if (state === 'mute') {
          return "".concat(result).concat(__('%1$s have been muted', actors[0]), "\n");
        }
      }
      return result;
    }, '');
  },
  /**
   * @param { String } actor - The nickname of the actor that caused the notification
   * @param {String|Array<String>} states - The state or states representing the type of notificcation
   */
  removeNotification: function removeNotification(actor, states) {
    var _this43 = this;
    var actors_per_state = this.notifications.toJSON();
    states = Array.isArray(states) ? states : [states];
    states.forEach(function (state) {
      var existing_actors = Array.from(actors_per_state[state] || []);
      if (existing_actors.includes(actor)) {
        var idx = existing_actors.indexOf(actor);
        existing_actors.splice(idx, 1);
        _this43.notifications.set(state, Array.from(existing_actors));
      }
    });
  },
  /**
   * Update the notifications model by adding the passed in nickname
   * to the array of nicknames that all match a particular state.
   *
   * Removes the nickname from any other states it might be associated with.
   *
   * The state can be a XEP-0085 Chat State or a XEP-0045 join/leave
   * state.
   * @param { String } actor - The nickname of the actor that causes the notification
   * @param { String } state - The state representing the type of notificcation
   */
  updateNotifications: function updateNotifications(actor, state) {
    var _this44 = this;
    var actors_per_state = this.notifications.toJSON();
    var existing_actors = actors_per_state[state] || [];
    if (existing_actors.includes(actor)) {
      return;
    }
    var reducer = function reducer(out, s) {
      if (s === state) {
        out[s] = [].concat(muc_toConsumableArray(existing_actors), [actor]);
      } else {
        out[s] = (actors_per_state[s] || []).filter(function (a) {
          return a !== actor;
        });
      }
      return out;
    };
    var actors_per_chat_state = public_converse.CHAT_STATES.reduce(reducer, {});
    var actors_per_traffic_state = public_converse.MUC_TRAFFIC_STATES_LIST.reduce(reducer, {});
    var actors_per_role_change = public_converse.MUC_ROLE_CHANGES_LIST.reduce(reducer, {});
    this.notifications.set(Object.assign(actors_per_chat_state, actors_per_traffic_state, actors_per_role_change));
    window.setTimeout(function () {
      return _this44.removeNotification(actor, state);
    }, 10000);
  },
  handleMetadataFastening: function handleMetadataFastening(attrs) {
    if (attrs.ogp_for_id) {
      if (attrs.from !== this.get('jid')) {
        // For now we only allow metadata from the MUC itself and not
        // from individual users who are deemed less trustworthy.
        return false;
      }
      var message = this.messages.findWhere({
        'origin_id': attrs.ogp_for_id
      });
      if (message) {
        var old_list = message.get('ogp_metadata') || [];
        if (old_list.filter(function (m) {
          return m['og:url'] === attrs['og:url'];
        }).length) {
          // Don't add metadata for the same URL again
          return false;
        }
        var list = [].concat(muc_toConsumableArray(old_list), [lodash_es_pick(attrs, METADATA_ATTRIBUTES)]);
        message.save('ogp_metadata', list);
        return true;
      }
    }
    return false;
  },
  /**
   * Given {@link MessageAttributes} look for XEP-0316 Room Notifications and create info
   * messages for them.
   * @param { Element } stanza
   */
  handleMEPNotification: function handleMEPNotification(attrs) {
    var _attrs$activities,
      _this45 = this;
    if (attrs.from !== this.get('jid') || !attrs.activities) {
      return false;
    }
    (_attrs$activities = attrs.activities) === null || _attrs$activities === void 0 ? void 0 : _attrs$activities.forEach(function (activity_attrs) {
      var data = Object.assign(attrs, activity_attrs);
      _this45.createMessage(data);
      // Trigger so that notifications are shown
      shared_api.trigger('message', {
        'attrs': data,
        'chatbox': _this45
      });
    });
    return !!attrs.activities.length;
  },
  /**
   * Returns an already cached message (if it exists) based on the
   * passed in attributes map.
   * @method _converse.ChatRoom#getDuplicateMessage
   * @param { object } attrs - Attributes representing a received
   *  message, as returned by {@link parseMUCMessage}
   * @returns {Promise<_converse.Message>}
   */
  getDuplicateMessage: function getDuplicateMessage(attrs) {
    var _attrs$activities2;
    if ((_attrs$activities2 = attrs.activities) !== null && _attrs$activities2 !== void 0 && _attrs$activities2.length) {
      return this.messages.findWhere({
        'type': 'mep',
        'msgid': attrs.msgid
      });
    } else {
      return shared_converse.ChatBox.prototype.getDuplicateMessage.call(this, attrs);
    }
  },
  /**
   * Handler for all MUC messages sent to this groupchat. This method
   * shouldn't be called directly, instead {@link _converse.ChatRoom#queueMessage}
   * should be called.
   * @method _converse.ChatRoom#onMessage
   * @param { MessageAttributes } attrs - A promise which resolves to the message attributes.
   */
  onMessage: function onMessage(attrs) {
    var _this46 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee34() {
      var message, msg;
      return muc_regeneratorRuntime().wrap(function _callee34$(_context34) {
        while (1) switch (_context34.prev = _context34.next) {
          case 0:
            _context34.next = 2;
            return attrs;
          case 2:
            attrs = _context34.sent;
            if (!muc_u.isErrorObject(attrs)) {
              _context34.next = 8;
              break;
            }
            attrs.stanza && log.error(attrs.stanza);
            return _context34.abrupt("return", log.error(attrs.message));
          case 8:
            _context34.t0 = attrs.type === 'error';
            if (!_context34.t0) {
              _context34.next = 13;
              break;
            }
            _context34.next = 12;
            return _this46.shouldShowErrorMessage(attrs);
          case 12:
            _context34.t0 = !_context34.sent;
          case 13:
            if (!_context34.t0) {
              _context34.next = 15;
              break;
            }
            return _context34.abrupt("return");
          case 15:
            message = _this46.getDuplicateMessage(attrs);
            if (!message) {
              _context34.next = 21;
              break;
            }
            message.get('type') === 'groupchat' && _this46.updateMessage(message, attrs);
            return _context34.abrupt("return");
          case 21:
            if (!(attrs.receipt_id || attrs.is_marker || _this46.ignorableCSN(attrs))) {
              _context34.next = 23;
              break;
            }
            return _context34.abrupt("return");
          case 23:
            _context34.t3 = _this46.handleMetadataFastening(attrs) || _this46.handleMEPNotification(attrs);
            if (_context34.t3) {
              _context34.next = 28;
              break;
            }
            _context34.next = 27;
            return _this46.handleRetraction(attrs);
          case 27:
            _context34.t3 = _context34.sent;
          case 28:
            _context34.t2 = _context34.t3;
            if (_context34.t2) {
              _context34.next = 33;
              break;
            }
            _context34.next = 32;
            return _this46.handleModeration(attrs);
          case 32:
            _context34.t2 = _context34.sent;
          case 33:
            _context34.t1 = _context34.t2;
            if (_context34.t1) {
              _context34.next = 38;
              break;
            }
            _context34.next = 37;
            return _this46.handleSubjectChange(attrs);
          case 37:
            _context34.t1 = _context34.sent;
          case 38:
            if (!_context34.t1) {
              _context34.next = 41;
              break;
            }
            attrs.nick && _this46.removeNotification(attrs.nick, ['composing', 'paused']);
            return _context34.abrupt("return");
          case 41:
            _this46.setEditable(attrs, attrs.time);
            if (attrs['chat_state']) {
              _this46.updateNotifications(attrs.nick, attrs.chat_state);
            }
            if (!muc_u.shouldCreateGroupchatMessage(attrs)) {
              _context34.next = 54;
              break;
            }
            _context34.next = 46;
            return handleCorrection(_this46, attrs);
          case 46:
            _context34.t4 = _context34.sent;
            if (_context34.t4) {
              _context34.next = 51;
              break;
            }
            _context34.next = 50;
            return _this46.createMessage(attrs);
          case 50:
            _context34.t4 = _context34.sent;
          case 51:
            msg = _context34.t4;
            _this46.removeNotification(attrs.nick, ['composing', 'paused']);
            _this46.handleUnreadMessage(msg);
          case 54:
          case "end":
            return _context34.stop();
        }
      }, _callee34);
    }))();
  },
  handleModifyError: function handleModifyError(pres) {
    var _pres$querySelector;
    var text = (_pres$querySelector = pres.querySelector('error text')) === null || _pres$querySelector === void 0 ? void 0 : _pres$querySelector.textContent;
    if (text) {
      if (this.session.get('connection_status') === ROOMSTATUS.CONNECTING) {
        this.setDisconnectionState(text);
      } else {
        var attrs = {
          'type': 'error',
          'message': text,
          'is_ephemeral': true
        };
        this.createMessage(attrs);
      }
    }
  },
  /**
   * Handle a presence stanza that disconnects the user from the MUC
   * @param { Element } stanza
   */
  handleDisconnection: function handleDisconnection(stanza) {
    var _item$querySelector, _item$querySelector2;
    var is_self = stanza.querySelector("status[code='110']") !== null;
    var x = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MUC_USER, "\"]"), stanza).pop();
    if (!x) {
      return;
    }
    var disconnection_codes = Object.keys(shared_converse.muc.disconnect_messages);
    var codes = external_sizzle_default()('status', x).map(function (s) {
      return s.getAttribute('code');
    }).filter(function (c) {
      return disconnection_codes.includes(c);
    });
    var disconnected = is_self && codes.length > 0;
    if (!disconnected) {
      return;
    }
    // By using querySelector we assume here there is
    // one <item> per <x xmlns='http://jabber.org/protocol/muc#user'>
    // element. This appears to be a safe assumption, since
    // each <x/> element pertains to a single user.
    var item = x.querySelector('item');
    var reason = item ? (_item$querySelector = item.querySelector('reason')) === null || _item$querySelector === void 0 ? void 0 : _item$querySelector.textContent : undefined;
    var actor = item ? (_item$querySelector2 = item.querySelector('actor')) === null || _item$querySelector2 === void 0 ? void 0 : _item$querySelector2.getAttribute('nick') : undefined;
    var message = shared_converse.muc.disconnect_messages[codes[0]];
    var status = codes.includes('301') ? ROOMSTATUS.BANNED : ROOMSTATUS.DISCONNECTED;
    this.setDisconnectionState(message, reason, actor, status);
  },
  getActionInfoMessage: function getActionInfoMessage(code, nick, actor) {
    var __ = shared_converse.__;
    if (code === '301') {
      return actor ? __('%1$s has been banned by %2$s', nick, actor) : __('%1$s has been banned', nick);
    } else if (code === '303') {
      return __("%1$s's nickname has changed", nick);
    } else if (code === '307') {
      return actor ? __('%1$s has been kicked out by %2$s', nick, actor) : __('%1$s has been kicked out', nick);
    } else if (code === '321') {
      return __('%1$s has been removed because of an affiliation change', nick);
    } else if (code === '322') {
      return __('%1$s has been removed for not being a member', nick);
    }
  },
  createAffiliationChangeMessage: function createAffiliationChangeMessage(occupant) {
    var __ = shared_converse.__;
    var previous_affiliation = occupant._previousAttributes.affiliation;
    if (!previous_affiliation) {
      // If no previous affiliation was set, then we don't
      // interpret this as an affiliation change.
      // For example, if muc_send_probes is true, then occupants
      // are created based on incoming messages, in which case
      // we don't yet know the affiliation
      return;
    }
    var current_affiliation = occupant.get('affiliation');
    if (previous_affiliation === 'admin' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.EXADMIN)) {
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is no longer an admin of this groupchat', occupant.get('nick'))
      });
    } else if (previous_affiliation === 'owner' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.EXOWNER)) {
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is no longer an owner of this groupchat', occupant.get('nick'))
      });
    } else if (previous_affiliation === 'outcast' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.EXOUTCAST)) {
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is no longer banned from this groupchat', occupant.get('nick'))
      });
    }
    if (current_affiliation === 'none' && previous_affiliation === 'member' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.EXMEMBER)) {
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is no longer a member of this groupchat', occupant.get('nick'))
      });
    }
    if (current_affiliation === 'member' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.MEMBER)) {
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is now a member of this groupchat', occupant.get('nick'))
      });
    } else if (current_affiliation === 'admin' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.ADMIN) || current_affiliation == 'owner' && shared_converse.isInfoVisible(public_converse.AFFILIATION_CHANGES.OWNER)) {
      // For example: AppleJack is now an (admin|owner) of this groupchat
      this.createMessage({
        'type': 'info',
        'message': __('%1$s is now an %2$s of this groupchat', occupant.get('nick'), current_affiliation)
      });
    }
  },
  createRoleChangeMessage: function createRoleChangeMessage(occupant, changed) {
    if (changed === 'none' || occupant.changed.affiliation) {
      // We don't inform of role changes if they accompany affiliation changes.
      return;
    }
    var previous_role = occupant._previousAttributes.role;
    if (previous_role === 'moderator' && shared_converse.isInfoVisible(public_converse.MUC_ROLE_CHANGES.DEOP)) {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_ROLE_CHANGES.DEOP);
    } else if (previous_role === 'visitor' && shared_converse.isInfoVisible(public_converse.MUC_ROLE_CHANGES.VOICE)) {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_ROLE_CHANGES.VOICE);
    }
    if (occupant.get('role') === 'visitor' && shared_converse.isInfoVisible(public_converse.MUC_ROLE_CHANGES.MUTE)) {
      this.updateNotifications(occupant.get('nick'), public_converse.MUC_ROLE_CHANGES.MUTE);
    } else if (occupant.get('role') === 'moderator') {
      if (!['owner', 'admin'].includes(occupant.get('affiliation')) && shared_converse.isInfoVisible(public_converse.MUC_ROLE_CHANGES.OP)) {
        // Oly show this message if the user isn't already
        // an admin or owner, otherwise this isn't new information.
        this.updateNotifications(occupant.get('nick'), public_converse.MUC_ROLE_CHANGES.OP);
      }
    }
  },
  /**
   * Create an info message based on a received MUC status code
   * @private
   * @method _converse.ChatRoom#createInfoMessage
   * @param { string } code - The MUC status code
   * @param { Element } stanza - The original stanza that contains the code
   * @param { Boolean } is_self - Whether this stanza refers to our own presence
   */
  createInfoMessage: function createInfoMessage(code, stanza, is_self) {
    var __ = shared_converse.__;
    var data = {
      'type': 'info',
      'is_ephemeral': true
    };
    if (!shared_converse.isInfoVisible(code)) {
      return;
    }
    if (code === '110' || code === '100' && !is_self) {
      return;
    } else if (code in shared_converse.muc.info_messages) {
      data.message = shared_converse.muc.info_messages[code];
    } else if (!is_self && ACTION_INFO_CODES.includes(code)) {
      var _item$querySelector3, _item$querySelector4;
      var nick = external_strophe_namespaceObject.Strophe.getResourceFromJid(stanza.getAttribute('from'));
      var item = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MUC_USER, "\"] item"), stanza).pop();
      data.actor = item ? (_item$querySelector3 = item.querySelector('actor')) === null || _item$querySelector3 === void 0 ? void 0 : _item$querySelector3.getAttribute('nick') : undefined;
      data.reason = item ? (_item$querySelector4 = item.querySelector('reason')) === null || _item$querySelector4 === void 0 ? void 0 : _item$querySelector4.textContent : undefined;
      data.message = this.getActionInfoMessage(code, nick, data.actor);
    } else if (is_self && code in shared_converse.muc.new_nickname_messages) {
      // XXX: Side-effect of setting the nick. Should ideally be refactored out of this method
      var _nick;
      if (code === '210') {
        _nick = external_strophe_namespaceObject.Strophe.getResourceFromJid(stanza.getAttribute('from'));
      } else if (code === '303') {
        _nick = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MUC_USER, "\"] item"), stanza).pop().getAttribute('nick');
      }
      this.save('nick', _nick);
      data.message = __(shared_converse.muc.new_nickname_messages[code], _nick);
    }
    if (data.message) {
      if (code === '201' && this.messages.findWhere(data)) {
        return;
      }
      this.createMessage(data);
    }
  },
  /**
   * Create info messages based on a received presence or message stanza
   * @private
   * @method _converse.ChatRoom#createInfoMessages
   * @param { Element } stanza
   */
  createInfoMessages: function createInfoMessages(stanza) {
    var _this47 = this;
    var codes = external_sizzle_default()("x[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.MUC_USER, "\"] status"), stanza).map(function (s) {
      return s.getAttribute('code');
    });
    if (codes.includes('333') && codes.includes('307')) {
      // See: https://github.com/xsf/xeps/pull/969/files#diff-ac5113766e59219806793c1f7d967f1bR4966
      codes.splice(codes.indexOf('307'), 1);
    }
    var is_self = codes.includes('110');
    codes.forEach(function (code) {
      return _this47.createInfoMessage(code, stanza, is_self);
    });
  },
  /**
   * Set parameters regarding disconnection from this room. This helps to
   * communicate to the user why they were disconnected.
   * @param { String } message - The disconnection message, as received from (or
   *  implied by) the server.
   * @param { String } reason - The reason provided for the disconnection
   * @param { String } actor - The person (if any) responsible for this disconnection
   * @param { number } status - The status code (see `ROOMSTATUS`)
   */
  setDisconnectionState: function setDisconnectionState(message, reason, actor) {
    var status = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ROOMSTATUS.DISCONNECTED;
    this.session.save({
      'connection_status': status,
      'disconnection_actor': actor,
      'disconnection_message': message,
      'disconnection_reason': reason
    });
  },
  onNicknameClash: function onNicknameClash(presence) {
    var __ = shared_converse.__;
    if (shared_api.settings.get('muc_nickname_from_jid')) {
      var nick = presence.getAttribute('from').split('/')[1];
      if (nick === shared_converse.getDefaultMUCNickname()) {
        this.join(nick + '-2');
      } else {
        var del = nick.lastIndexOf('-');
        var num = nick.substring(del + 1, nick.length);
        this.join(nick.substring(0, del + 1) + String(Number(num) + 1));
      }
    } else {
      this.save({
        'nickname_validation_message': __('The nickname you chose is reserved or ' + 'currently in use, please choose a different one.')
      });
      this.session.save({
        'connection_status': ROOMSTATUS.NICKNAME_REQUIRED
      });
    }
  },
  /**
   * Parses a <presence> stanza with type "error" and sets the proper
   * `connection_status` value for this {@link _converse.ChatRoom} as
   * well as any additional output that can be shown to the user.
   * @private
   * @param { Element } stanza - The presence stanza
   */
  onErrorPresence: function onErrorPresence(stanza) {
    var _sizzle$pop;
    var __ = shared_converse.__;
    var error = stanza.querySelector('error');
    var error_type = error.getAttribute('type');
    var reason = (_sizzle$pop = external_sizzle_default()("text[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), error).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent;
    if (error_type === 'modify') {
      this.handleModifyError(stanza);
    } else if (error_type === 'auth') {
      if (external_sizzle_default()("not-authorized[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), error).length) {
        this.save({
          'password_validation_message': reason || __('Password incorrect')
        });
        this.session.save({
          'connection_status': ROOMSTATUS.PASSWORD_REQUIRED
        });
      }
      if (error.querySelector('registration-required')) {
        var message = __('You are not on the member list of this groupchat.');
        this.setDisconnectionState(message, reason);
      } else if (error.querySelector('forbidden')) {
        this.setDisconnectionState(shared_converse.muc.disconnect_messages[301], reason, null, ROOMSTATUS.BANNED);
      }
    } else if (error_type === 'cancel') {
      if (error.querySelector('not-allowed')) {
        var _message4 = __('You are not allowed to create new groupchats.');
        this.setDisconnectionState(_message4, reason);
      } else if (error.querySelector('not-acceptable')) {
        var _message5 = __("Your nickname doesn't conform to this groupchat's policies.");
        this.setDisconnectionState(_message5, reason);
      } else if (external_sizzle_default()("gone[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), error).length) {
        var _sizzle$pop2;
        var moved_jid = (_sizzle$pop2 = external_sizzle_default()("gone[xmlns=\"".concat(external_strophe_namespaceObject.Strophe.NS.STANZAS, "\"]"), error).pop()) === null || _sizzle$pop2 === void 0 ? void 0 : _sizzle$pop2.textContent.replace(/^xmpp:/, '').replace(/\?join$/, '');
        this.save({
          moved_jid: moved_jid,
          'destroyed_reason': reason
        });
        this.session.save({
          'connection_status': ROOMSTATUS.DESTROYED
        });
      } else if (error.querySelector('conflict')) {
        this.onNicknameClash(stanza);
      } else if (error.querySelector('item-not-found')) {
        var _message6 = __('This groupchat does not (yet) exist.');
        this.setDisconnectionState(_message6, reason);
      } else if (error.querySelector('service-unavailable')) {
        var _message7 = __('This groupchat has reached its maximum number of participants.');
        this.setDisconnectionState(_message7, reason);
      } else if (error.querySelector('remote-server-not-found')) {
        var _message8 = __('Remote server not found');
        this.setDisconnectionState(_message8, reason);
      } else if (error.querySelector('forbidden')) {
        var _message9 = __("You're not allowed to enter this groupchat");
        this.setDisconnectionState(_message9, reason);
      } else {
        var _message10 = __("An error happened while trying to enter this groupchat");
        this.setDisconnectionState(_message10, reason);
      }
    }
  },
  /**
   * Listens for incoming presence stanzas from the service that hosts this MUC
   * @private
   * @method _converse.ChatRoom#onPresenceFromMUCHost
   * @param { Element } stanza - The presence stanza
   */
  onPresenceFromMUCHost: function onPresenceFromMUCHost(stanza) {
    if (stanza.getAttribute('type') === 'error') {
      var error = stanza.querySelector('error');
      if ((error === null || error === void 0 ? void 0 : error.getAttribute('type')) === 'wait' && error !== null && error !== void 0 && error.querySelector('resource-constraint')) {
        // If we get a <resource-constraint> error, we assume it's in context of XEP-0437 RAI.
        // We remove this MUC's host from the list of enabled domains and rejoin the MUC.
        if (this.session.get('connection_status') === ROOMSTATUS.DISCONNECTED) {
          this.rejoin();
        }
      }
    }
  },
  /**
   * Handles incoming presence stanzas coming from the MUC
   * @private
   * @method _converse.ChatRoom#onPresence
   * @param { Element } stanza
   */
  onPresence: function onPresence(stanza) {
    if (stanza.getAttribute('type') === 'error') {
      return this.onErrorPresence(stanza);
    }
    this.createInfoMessages(stanza);
    if (stanza.querySelector("status[code='110']")) {
      this.onOwnPresence(stanza);
      if (this.getOwnRole() !== 'none' && this.session.get('connection_status') === ROOMSTATUS.CONNECTING) {
        this.session.save('connection_status', ROOMSTATUS.CONNECTED);
      }
    } else {
      this.updateOccupantsOnPresence(stanza);
    }
  },
  /**
   * Handles a received presence relating to the current user.
   *
   * For locked groupchats (which are by definition "new"), the
   * groupchat will either be auto-configured or created instantly
   * (with default config) or a configuration groupchat will be
   * rendered.
   *
   * If the groupchat is not locked, then the groupchat will be
   * auto-configured only if applicable and if the current
   * user is the groupchat's owner.
   * @private
   * @method _converse.ChatRoom#onOwnPresence
   * @param { Element } pres - The stanza
   */
  onOwnPresence: function onOwnPresence(stanza) {
    var _this48 = this;
    return muc_asyncToGenerator( /*#__PURE__*/muc_regeneratorRuntime().mark(function _callee35() {
      var old_status, locked_room;
      return muc_regeneratorRuntime().wrap(function _callee35$(_context35) {
        while (1) switch (_context35.prev = _context35.next) {
          case 0:
            _context35.next = 2;
            return _this48.occupants.fetched;
          case 2:
            if (!(stanza.getAttribute('type') === 'unavailable')) {
              _context35.next = 5;
              break;
            }
            _this48.handleDisconnection(stanza);
            return _context35.abrupt("return");
          case 5:
            old_status = _this48.session.get('connection_status');
            if (old_status !== ROOMSTATUS.ENTERED && old_status !== ROOMSTATUS.CLOSING) {
              // Set connection_status before creating the occupant, but
              // only trigger afterwards, so that plugins can access the
              // occupant in their event handlers.
              _this48.session.save('connection_status', ROOMSTATUS.ENTERED, {
                'silent': true
              });
              _this48.updateOccupantsOnPresence(stanza);
              _this48.session.trigger('change:connection_status', _this48.session, old_status);
            } else {
              _this48.updateOccupantsOnPresence(stanza);
            }
            locked_room = stanza.querySelector("status[code='201']");
            if (!locked_room) {
              _context35.next = 20;
              break;
            }
            if (!_this48.get('auto_configure')) {
              _context35.next = 14;
              break;
            }
            _context35.next = 12;
            return _this48.autoConfigureChatRoom().then(function () {
              return _this48.refreshDiscoInfo();
            });
          case 12:
            _context35.next = 20;
            break;
          case 14:
            if (!shared_api.settings.get('muc_instant_rooms')) {
              _context35.next = 19;
              break;
            }
            _context35.next = 17;
            return _this48.sendConfiguration().then(function () {
              return _this48.refreshDiscoInfo();
            });
          case 17:
            _context35.next = 20;
            break;
          case 19:
            _this48.session.save({
              'view': public_converse.MUC.VIEWS.CONFIG
            });
          case 20:
          case "end":
            return _context35.stop();
        }
      }, _callee35);
    }))();
  },
  /**
   * Returns a boolean to indicate whether the current user
   * was mentioned in a message.
   * @private
   * @method _converse.ChatRoom#isUserMentioned
   * @param { String } - The text message
   */
  isUserMentioned: function isUserMentioned(message) {
    var nick = this.get('nick');
    if (message.get('references').length) {
      var mentions = message.get('references').filter(function (ref) {
        return ref.type === 'mention';
      }).map(function (ref) {
        return ref.value;
      });
      return mentions.includes(nick);
    } else {
      return new RegExp("\\b".concat(nick, "\\b")).test(message.get('body'));
    }
  },
  incrementUnreadMsgsCounter: function incrementUnreadMsgsCounter(message) {
    var settings = {
      'num_unread_general': this.get('num_unread_general') + 1
    };
    if (this.get('num_unread_general') === 0) {
      settings['first_unread_id'] = message.get('id');
    }
    if (this.isUserMentioned(message)) {
      settings.num_unread = this.get('num_unread') + 1;
    }
    this.save(settings);
  },
  clearUnreadMsgCounter: function clearUnreadMsgCounter() {
    if (this.get('num_unread_general') > 0 || this.get('num_unread') > 0 || this.get('has_activity')) {
      this.sendMarkerForMessage(this.messages.last());
    }
    safeSave(this, {
      'has_activity': false,
      'num_unread': 0,
      'num_unread_general': 0
    });
  }
};
/* harmony default export */ const muc = (ChatRoomMixin);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/occupant.js
function occupant_typeof(obj) {
  "@babel/helpers - typeof";

  return occupant_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;
  }, occupant_typeof(obj);
}
function occupant_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function occupant_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, occupant_toPropertyKey(descriptor.key), descriptor);
  }
}
function occupant_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) occupant_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) occupant_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function occupant_toPropertyKey(arg) {
  var key = occupant_toPrimitive(arg, "string");
  return occupant_typeof(key) === "symbol" ? key : String(key);
}
function occupant_toPrimitive(input, hint) {
  if (occupant_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (occupant_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function occupant_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    occupant_get = Reflect.get.bind();
  } else {
    occupant_get = function _get(target, property, receiver) {
      var base = occupant_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return occupant_get.apply(this, arguments);
}
function occupant_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = occupant_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function occupant_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) occupant_setPrototypeOf(subClass, superClass);
}
function occupant_setPrototypeOf(o, p) {
  occupant_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return occupant_setPrototypeOf(o, p);
}
function occupant_createSuper(Derived) {
  var hasNativeReflectConstruct = occupant_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = occupant_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = occupant_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return occupant_possibleConstructorReturn(this, result);
  };
}
function occupant_possibleConstructorReturn(self, call) {
  if (call && (occupant_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 occupant_assertThisInitialized(self);
}
function occupant_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function occupant_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 occupant_getPrototypeOf(o) {
  occupant_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return occupant_getPrototypeOf(o);
}


/**
 * Represents a participant in a MUC
 * @class
 * @namespace _converse.ChatRoomOccupant
 * @memberOf _converse
 */
var ChatRoomOccupant = /*#__PURE__*/function (_Model) {
  occupant_inherits(ChatRoomOccupant, _Model);
  var _super = occupant_createSuper(ChatRoomOccupant);
  function ChatRoomOccupant() {
    occupant_classCallCheck(this, ChatRoomOccupant);
    return _super.apply(this, arguments);
  }
  occupant_createClass(ChatRoomOccupant, [{
    key: "defaults",
    value: function defaults() {
      // eslint-disable-line class-methods-use-this
      return {
        hats: [],
        show: 'offline',
        states: []
      };
    }
  }, {
    key: "save",
    value: function save(key, val, options) {
      var attrs;
      if (key == null) {
        // eslint-disable-line no-eq-null
        return occupant_get(occupant_getPrototypeOf(ChatRoomOccupant.prototype), "save", this).call(this, key, val, options);
      } else if (occupant_typeof(key) === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }
      if (attrs.occupant_id) {
        attrs.id = attrs.occupant_id;
      }
      return occupant_get(occupant_getPrototypeOf(ChatRoomOccupant.prototype), "save", this).call(this, attrs, options);
    }
  }, {
    key: "getDisplayName",
    value: function getDisplayName() {
      return this.get('nick') || this.get('jid');
    }
  }, {
    key: "isMember",
    value: function isMember() {
      return ['admin', 'owner', 'member'].includes(this.get('affiliation'));
    }
  }, {
    key: "isModerator",
    value: function isModerator() {
      return ['admin', 'owner'].includes(this.get('affiliation')) || this.get('role') === 'moderator';
    }
  }, {
    key: "isSelf",
    value: function isSelf() {
      return this.get('states').includes('110');
    }
  }]);
  return ChatRoomOccupant;
}(Model);
/* harmony default export */ const occupant = (ChatRoomOccupant);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/utils.js
function muc_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_utils_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;
  }, muc_utils_typeof(obj);
}
function utils_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 utils_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? utils_ownKeys(Object(source), !0).forEach(function (key) {
      utils_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : utils_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function utils_defineProperty(obj, key, value) {
  key = utils_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 utils_toPropertyKey(arg) {
  var key = utils_toPrimitive(arg, "string");
  return muc_utils_typeof(key) === "symbol" ? key : String(key);
}
function utils_toPrimitive(input, hint) {
  if (muc_utils_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_utils_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_utils_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" == muc_utils_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 muc_utils_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 muc_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var muc_utils_converse$env = public_converse.env,
  muc_utils_Strophe = muc_utils_converse$env.Strophe,
  utils_sizzle = muc_utils_converse$env.sizzle,
  muc_utils_u = muc_utils_converse$env.u;
function getAutoFetchedAffiliationLists() {
  var affs = shared_api.settings.get('muc_fetch_members');
  return Array.isArray(affs) ? affs : affs ? ['member', 'admin', 'owner'] : [];
}

/**
 * Given an occupant model, see which roles may be assigned to that user.
 * @param { Model } occupant
 * @returns { Array<('moderator'|'participant'|'visitor')> } - An array of assignable roles
 */
function getAssignableRoles(occupant) {
  var disabled = shared_api.settings.get('modtools_disable_assign');
  if (!Array.isArray(disabled)) {
    disabled = disabled ? ROLES : [];
  }
  if (occupant.get('role') === 'moderator') {
    return ROLES.filter(function (r) {
      return !disabled.includes(r);
    });
  } else {
    return [];
  }
}
function registerDirectInvitationHandler() {
  shared_converse.connection.addHandler(function (message) {
    shared_converse.onDirectMUCInvitation(message);
    return true;
  }, 'jabber:x:conference', 'message');
}
function disconnectChatRooms() {
  /* When disconnecting, mark all groupchats as
   * disconnected, so that they will be properly entered again
   * when fetched from session storage.
   */
  return shared_converse.chatboxes.filter(function (m) {
    return m.get('type') === shared_converse.CHATROOMS_TYPE;
  }).forEach(function (m) {
    return m.session.save({
      'connection_status': public_converse.ROOMSTATUS.DISCONNECTED
    });
  });
}
function onWindowStateChanged(_x) {
  return _onWindowStateChanged.apply(this, arguments);
}
function _onWindowStateChanged() {
  _onWindowStateChanged = muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee2(data) {
    var rooms;
    return muc_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(data.state === 'visible' && shared_api.connection.connected())) {
            _context2.next = 5;
            break;
          }
          _context2.next = 3;
          return shared_api.rooms.get();
        case 3:
          rooms = _context2.sent;
          rooms.forEach(function (room) {
            return room.rejoinIfNecessary();
          });
        case 5:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _onWindowStateChanged.apply(this, arguments);
}
function routeToRoom(_x2) {
  return _routeToRoom.apply(this, arguments);
}

/* Opens a groupchat, making sure that certain attributes
 * are correct, for example that the "type" is set to
 * "chatroom".
 */
function _routeToRoom() {
  _routeToRoom = muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee3(jid) {
    return muc_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (muc_utils_u.isValidMUCJID(jid)) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return", log.warn("invalid jid \"".concat(jid, "\" provided in url fragment")));
        case 2:
          _context3.next = 4;
          return shared_api.waitUntil('roomsAutoJoined');
        case 4:
          if (!shared_api.settings.get('allow_bookmarks')) {
            _context3.next = 7;
            break;
          }
          _context3.next = 7;
          return shared_api.waitUntil('bookmarksInitialized');
        case 7:
          shared_api.rooms.open(jid);
        case 8:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _routeToRoom.apply(this, arguments);
}
function openChatRoom(_x3, _x4) {
  return _openChatRoom.apply(this, arguments);
}

/**
 * A direct MUC invitation to join a groupchat has been received
 * See XEP-0249: Direct MUC invitations.
 * @private
 * @method _converse.ChatRoom#onDirectMUCInvitation
 * @param { Element } message - The message stanza containing the invitation.
 */
function _openChatRoom() {
  _openChatRoom = muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee4(jid, settings) {
    var chatbox;
    return muc_utils_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          settings.type = shared_converse.CHATROOMS_TYPE;
          settings.id = jid;
          _context4.next = 4;
          return shared_api.rooms.get(jid, settings, true);
        case 4:
          chatbox = _context4.sent;
          chatbox.maybeShow(true);
          return _context4.abrupt("return", chatbox);
        case 7:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _openChatRoom.apply(this, arguments);
}
function onDirectMUCInvitation(_x5) {
  return _onDirectMUCInvitation.apply(this, arguments);
}
function _onDirectMUCInvitation() {
  _onDirectMUCInvitation = muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee5(message) {
    var x_el, from, room_jid, reason, result, _converse$roster$get$, _converse$roster$get, contact, chatroom;
    return muc_utils_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          x_el = utils_sizzle('x[xmlns="jabber:x:conference"]', message).pop(), from = muc_utils_Strophe.getBareJidFromJid(message.getAttribute('from')), room_jid = x_el.getAttribute('jid'), reason = x_el.getAttribute('reason');
          if (!shared_api.settings.get('auto_join_on_invite')) {
            _context5.next = 5;
            break;
          }
          result = true;
          _context5.next = 9;
          break;
        case 5:
          // Invite request might come from someone not your roster list
          contact = (_converse$roster$get$ = (_converse$roster$get = shared_converse.roster.get(from)) === null || _converse$roster$get === void 0 ? void 0 : _converse$roster$get.getDisplayName()) !== null && _converse$roster$get$ !== void 0 ? _converse$roster$get$ : from;
          /**
           * *Hook* which is used to gather confirmation whether a direct MUC
           * invitation should be accepted or not.
           *
           * It's meant for consumers of `@converse/headless` to subscribe to
           * this hook and then ask the user to confirm.
           *
           * @event _converse#confirmDirectMUCInvitation
           */
          _context5.next = 8;
          return shared_api.hook('confirmDirectMUCInvitation', {
            contact: contact,
            reason: reason,
            jid: room_jid
          }, false);
        case 8:
          result = _context5.sent;
        case 9:
          if (!result) {
            _context5.next = 14;
            break;
          }
          _context5.next = 12;
          return openChatRoom(room_jid, {
            'password': x_el.getAttribute('password')
          });
        case 12:
          chatroom = _context5.sent;
          if (chatroom.session.get('connection_status') === public_converse.ROOMSTATUS.DISCONNECTED) {
            shared_converse.chatboxes.get(room_jid).rejoin();
          }
        case 14:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
  return _onDirectMUCInvitation.apply(this, arguments);
}
function getDefaultMUCNickname() {
  // XXX: if anything changes here, update the docs for the
  // locked_muc_nickname setting.
  if (!shared_converse.xmppstatus) {
    throw new Error("Can't call _converse.getDefaultMUCNickname before the statusInitialized has been fired.");
  }
  var nick = shared_converse.xmppstatus.getNickname();
  if (nick) {
    return nick;
  } else if (shared_api.settings.get('muc_nickname_from_jid')) {
    return muc_utils_Strophe.unescapeNode(muc_utils_Strophe.getNodeFromJid(shared_converse.bare_jid));
  }
}

/**
 * Determines info message visibility based on
 * muc_show_info_messages configuration setting
 * @param {*} code
 * @memberOf _converse
 */
function isInfoVisible(code) {
  var info_messages = shared_api.settings.get('muc_show_info_messages');
  if (info_messages.includes(code)) {
    return true;
  }
  return false;
}

/**
 * Automatically join groupchats, based on the
 * "auto_join_rooms" configuration setting, which is an array
 * of strings (groupchat JIDs) or objects (with groupchat JID and other settings).
 */
function autoJoinRooms() {
  return _autoJoinRooms.apply(this, arguments);
}
function _autoJoinRooms() {
  _autoJoinRooms = muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee6() {
    return muc_utils_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          _context6.next = 2;
          return Promise.all(shared_api.settings.get('auto_join_rooms').map(function (muc) {
            if (typeof muc === 'string') {
              if (shared_converse.chatboxes.where({
                'jid': muc
              }).length) {
                return Promise.resolve();
              }
              return shared_api.rooms.open(muc);
            } else if (lodash_es_isObject(muc)) {
              return shared_api.rooms.open(muc.jid, utils_objectSpread({}, muc));
            } else {
              log.error('Invalid muc criteria specified for "auto_join_rooms"');
              return Promise.resolve();
            }
          }));
        case 2:
          /**
           * Triggered once any rooms that have been configured to be automatically joined,
           * specified via the _`auto_join_rooms` setting, have been entered.
           * @event _converse#roomsAutoJoined
           * @example _converse.api.listen.on('roomsAutoJoined', () => { ... });
           * @example _converse.api.waitUntil('roomsAutoJoined').then(() => { ... });
           */
          shared_api.trigger('roomsAutoJoined');
        case 3:
        case "end":
          return _context6.stop();
      }
    }, _callee6);
  }));
  return _autoJoinRooms.apply(this, arguments);
}
function onAddClientFeatures() {
  shared_api.disco.own.features.add(muc_utils_Strophe.NS.MUC);
  if (shared_api.settings.get('allow_muc_invitations')) {
    shared_api.disco.own.features.add('jabber:x:conference'); // Invites
  }
}

function onBeforeTearDown() {
  shared_converse.chatboxes.where({
    'type': shared_converse.CHATROOMS_TYPE
  }).forEach(function (muc) {
    return safeSave(muc.session, {
      'connection_status': public_converse.ROOMSTATUS.DISCONNECTED
    });
  });
}
function onStatusInitialized() {
  window.addEventListener(shared_converse.unloadevent, function () {
    var using_websocket = shared_api.connection.isType('websocket');
    if (using_websocket && (!shared_api.settings.get('enable_smacks') || !shared_converse.session.get('smacks_stream_id'))) {
      // For non-SMACKS websocket connections, or non-resumeable
      // connections, we disconnect all chatrooms when the page unloads.
      // See issue #1111
      disconnectChatRooms();
    }
  });
}
function onBeforeResourceBinding() {
  shared_converse.connection.addHandler(function (stanza) {
    var muc_jid = muc_utils_Strophe.getBareJidFromJid(stanza.getAttribute('from'));
    if (!shared_converse.chatboxes.get(muc_jid)) {
      shared_api.waitUntil('chatBoxesFetched').then( /*#__PURE__*/muc_utils_asyncToGenerator( /*#__PURE__*/muc_utils_regeneratorRuntime().mark(function _callee() {
        var muc;
        return muc_utils_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              muc = shared_converse.chatboxes.get(muc_jid);
              if (!muc) {
                _context.next = 5;
                break;
              }
              _context.next = 4;
              return muc.initialized;
            case 4:
              muc.message_handler.run(stanza);
            case 5:
            case "end":
              return _context.stop();
          }
        }, _callee);
      })));
    }
    return true;
  }, null, 'message', 'groupchat');
}
Object.assign(shared_converse, {
  getAssignableRoles: getAssignableRoles
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/occupants.js
function occupants_typeof(obj) {
  "@babel/helpers - typeof";

  return occupants_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;
  }, occupants_typeof(obj);
}
function occupants_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  occupants_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" == occupants_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 occupants_toConsumableArray(arr) {
  return occupants_arrayWithoutHoles(arr) || occupants_iterableToArray(arr) || occupants_unsupportedIterableToArray(arr) || occupants_nonIterableSpread();
}
function occupants_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function occupants_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return occupants_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 occupants_arrayLikeToArray(o, minLen);
}
function occupants_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function occupants_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return occupants_arrayLikeToArray(arr);
}
function occupants_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 occupants_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 occupants_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        occupants_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        occupants_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function occupants_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function occupants_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, occupants_toPropertyKey(descriptor.key), descriptor);
  }
}
function occupants_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) occupants_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) occupants_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function occupants_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    occupants_get = Reflect.get.bind();
  } else {
    occupants_get = function _get(target, property, receiver) {
      var base = occupants_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return occupants_get.apply(this, arguments);
}
function occupants_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = occupants_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function occupants_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) occupants_setPrototypeOf(subClass, superClass);
}
function occupants_setPrototypeOf(o, p) {
  occupants_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return occupants_setPrototypeOf(o, p);
}
function occupants_createSuper(Derived) {
  var hasNativeReflectConstruct = occupants_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = occupants_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = occupants_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return occupants_possibleConstructorReturn(this, result);
  };
}
function occupants_possibleConstructorReturn(self, call) {
  if (call && (occupants_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 occupants_assertThisInitialized(self);
}
function occupants_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function occupants_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 occupants_getPrototypeOf(o) {
  occupants_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return occupants_getPrototypeOf(o);
}
function occupants_defineProperty(obj, key, value) {
  key = occupants_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 occupants_toPropertyKey(arg) {
  var key = occupants_toPrimitive(arg, "string");
  return occupants_typeof(key) === "symbol" ? key : String(key);
}
function occupants_toPrimitive(input, hint) {
  if (occupants_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (occupants_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}









var occupants_u = public_converse.env.u;

/**
 * A list of {@link _converse.ChatRoomOccupant} instances, representing participants in a MUC.
 * @class
 * @namespace _converse.ChatRoomOccupants
 * @memberOf _converse
 */
var ChatRoomOccupants = /*#__PURE__*/function (_Collection) {
  occupants_inherits(ChatRoomOccupants, _Collection);
  var _super = occupants_createSuper(ChatRoomOccupants);
  function ChatRoomOccupants() {
    var _this;
    occupants_classCallCheck(this, ChatRoomOccupants);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    occupants_defineProperty(occupants_assertThisInitialized(_this), "model", occupant);
    return _this;
  }
  occupants_createClass(ChatRoomOccupants, [{
    key: "comparator",
    value: function comparator(occupant1, occupant2) {
      // eslint-disable-line class-methods-use-this
      var role1 = occupant1.get('role') || 'none';
      var role2 = occupant2.get('role') || 'none';
      if (MUC_ROLE_WEIGHTS[role1] === MUC_ROLE_WEIGHTS[role2]) {
        var nick1 = occupant1.getDisplayName().toLowerCase();
        var nick2 = occupant2.getDisplayName().toLowerCase();
        return nick1 < nick2 ? -1 : nick1 > nick2 ? 1 : 0;
      } else {
        return MUC_ROLE_WEIGHTS[role1] < MUC_ROLE_WEIGHTS[role2] ? -1 : 1;
      }
    }
  }, {
    key: "create",
    value: function create(attrs, options) {
      if (attrs.id || attrs instanceof Model) {
        return occupants_get(occupants_getPrototypeOf(ChatRoomOccupants.prototype), "create", this).call(this, attrs, options);
      }
      attrs.id = attrs.occupant_id || getUniqueId();
      return occupants_get(occupants_getPrototypeOf(ChatRoomOccupants.prototype), "create", this).call(this, attrs, options);
    }
  }, {
    key: "fetchMembers",
    value: function () {
      var _fetchMembers = occupants_asyncToGenerator( /*#__PURE__*/occupants_regeneratorRuntime().mark(function _callee() {
        var _this$getOwnOccupant,
          _this2 = this;
        var affiliations, muc_jid, aff_lists, new_members, known_affiliations, new_jids, new_nicks, removed_members;
        return occupants_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (['member', 'admin', 'owner'].includes((_this$getOwnOccupant = this.getOwnOccupant()) === null || _this$getOwnOccupant === void 0 ? void 0 : _this$getOwnOccupant.get('affiliation'))) {
                _context.next = 2;
                break;
              }
              return _context.abrupt("return");
            case 2:
              affiliations = getAutoFetchedAffiliationLists();
              if (!(affiliations.length === 0)) {
                _context.next = 5;
                break;
              }
              return _context.abrupt("return");
            case 5:
              muc_jid = this.chatroom.get('jid');
              _context.next = 8;
              return Promise.all(affiliations.map(function (a) {
                return getAffiliationList(a, muc_jid);
              }));
            case 8:
              aff_lists = _context.sent;
              new_members = aff_lists.reduce(function (acc, val) {
                return occupants_u.isErrorObject(val) ? acc : [].concat(occupants_toConsumableArray(val), occupants_toConsumableArray(acc));
              }, []);
              known_affiliations = affiliations.filter(function (a) {
                return !occupants_u.isErrorObject(aff_lists[affiliations.indexOf(a)]);
              });
              new_jids = new_members.map(function (m) {
                return m.jid;
              }).filter(function (m) {
                return m !== undefined;
              });
              new_nicks = new_members.map(function (m) {
                return !m.jid && m.nick || undefined;
              }).filter(function (m) {
                return m !== undefined;
              });
              removed_members = this.filter(function (m) {
                return known_affiliations.includes(m.get('affiliation')) && !new_nicks.includes(m.get('nick')) && !new_jids.includes(m.get('jid'));
              });
              removed_members.forEach(function (occupant) {
                if (occupant.get('jid') === shared_converse.bare_jid) {
                  return;
                } else if (occupant.get('show') === 'offline') {
                  occupant.destroy();
                } else {
                  occupant.save('affiliation', null);
                }
              });
              new_members.forEach(function (attrs) {
                var occupant = _this2.findOccupant(attrs);
                occupant ? occupant.save(attrs) : _this2.create(attrs);
              });
              /**
               * Triggered once the member lists for this MUC have been fetched and processed.
               * @event _converse#membersFetched
               * @example _converse.api.listen.on('membersFetched', () => { ... });
               */
              shared_api.trigger('membersFetched');
            case 17:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function fetchMembers() {
        return _fetchMembers.apply(this, arguments);
      }
      return fetchMembers;
    }()
    /**
     * @typedef { Object} OccupantData
     * @property { String } [jid]
     * @property { String } [nick]
     * @property { String } [occupant_id] - The XEP-0421 unique occupant id
     */
    /**
     * Try to find an existing occupant based on the provided
     * @link { OccupantData } object.
     *
     * Fetching the user by `occupant_id` is the quickest, O(1),
     * since it's a dictionary lookup.
     *
     * Fetching by jid or nick is O(n), since it requires traversing an array.
     *
     * Lookup by occupant_id is done first, then jid, and then nick.
     *
     * @method _converse.ChatRoomOccupants#findOccupant
     * @param { OccupantData } data
     */
  }, {
    key: "findOccupant",
    value: function findOccupant(data) {
      if (data.occupant_id) {
        return this.get(data.occupant_id);
      }
      var jid = data.jid && external_strophe_namespaceObject.Strophe.getBareJidFromJid(data.jid);
      return jid && this.findWhere({
        jid: jid
      }) || data.nick && this.findWhere({
        'nick': data.nick
      });
    }

    /**
     * Get the {@link _converse.ChatRoomOccupant} instance which
     * represents the current user.
     * @method _converse.ChatRoomOccupants#getOwnOccupant
     * @returns { _converse.ChatRoomOccupant }
     */
  }, {
    key: "getOwnOccupant",
    value: function getOwnOccupant() {
      return this.findOccupant({
        'jid': shared_converse.bare_jid,
        'occupant_id': this.chatroom.get('occupant_id')
      });
    }
  }]);
  return ChatRoomOccupants;
}(Collection);
/* harmony default export */ const occupants = (ChatRoomOccupants);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/affiliations/api.js

/* harmony default export */ const affiliations_api = ({
  /**
   * The "affiliations" namespace groups methods relevant to setting and
   * getting MUC affiliations.
   *
   * @namespace api.rooms.affiliations
   * @memberOf api.rooms
   */
  affiliations: {
    /**
     * Set the given affliation for the given JIDs in the specified MUCs
     *
     * @param { String|Array<String> } muc_jids - The JIDs of the MUCs in
     *  which the affiliation should be set.
     * @param { Object[] } users - An array of objects representing users
     *  for whom the affiliation is to be set.
     * @param { String } users[].jid - The JID of the user whose affiliation will change
     * @param { ('outcast'|'member'|'admin'|'owner') } users[].affiliation - The new affiliation for this user
     * @param { String } [users[].reason] - An optional reason for the affiliation change
     * @returns { Promise }
     *
     * @example
     *  api.rooms.affiliations.set(
     *      [
     *          'muc1@muc.example.org',
     *          'muc2@muc.example.org'
     *      ], [
     *          {
     *              'jid': 'user@example.org',
     *              'affiliation': 'member',
     *              'reason': "You're one of us now!"
     *          }
     *      ]
     *  )
     */
    set: function set(muc_jids, users) {
      users = !Array.isArray(users) ? [users] : users;
      muc_jids = !Array.isArray(muc_jids) ? [muc_jids] : muc_jids;
      return setAffiliations(muc_jids, users);
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/api.js
function muc_api_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_api_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;
  }, muc_api_typeof(obj);
}
function muc_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_api_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" == muc_api_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 muc_api_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 muc_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var api_u = public_converse.env.u;
/* harmony default export */ const muc_api = ({
  /**
   * The "rooms" namespace groups methods relevant to chatrooms
   * (aka groupchats).
   *
   * @namespace api.rooms
   * @memberOf api
   */
  rooms: {
    /**
     * Creates a new MUC chatroom (aka groupchat)
     *
     * Similar to {@link api.rooms.open}, but creates
     * the chatroom in the background (i.e. doesn't cause a view to open).
     *
     * @method api.rooms.create
     * @param {(string[]|string)} jid|jids The JID or array of
     *     JIDs of the chatroom(s) to create
     * @param { object } [attrs] attrs The room attributes
     * @returns {Promise} Promise which resolves with the Model representing the chat.
     */
    create: function create(jids) {
      var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      attrs = typeof attrs === 'string' ? {
        'nick': attrs
      } : attrs || {};
      if (!attrs.nick && shared_api.settings.get('muc_nickname_from_jid')) {
        attrs.nick = external_strophe_namespaceObject.Strophe.getNodeFromJid(shared_converse.bare_jid);
      }
      if (jids === undefined) {
        throw new TypeError('rooms.create: You need to provide at least one JID');
      } else if (typeof jids === 'string') {
        return shared_api.rooms.get(api_u.getJIDFromURI(jids), attrs, true);
      }
      return jids.map(function (jid) {
        return shared_api.rooms.get(api_u.getJIDFromURI(jid), attrs, true);
      });
    },
    /**
     * Opens a MUC chatroom (aka groupchat)
     *
     * Similar to {@link api.chats.open}, but for groupchats.
     *
     * @method api.rooms.open
     * @param { string } jid The room JID or JIDs (if not specified, all
     *     currently open rooms will be returned).
     * @param { string } attrs A map  containing any extra room attributes.
     * @param { string } [attrs.nick] The current user's nickname for the MUC
     * @param { boolean } [attrs.auto_configure] A boolean, indicating
     *     whether the room should be configured automatically or not.
     *     If set to `true`, then it makes sense to pass in configuration settings.
     * @param { object } [attrs.roomconfig] A map of configuration settings to be used when the room gets
     *     configured automatically. Currently it doesn't make sense to specify
     *     `roomconfig` values if `auto_configure` is set to `false`.
     *     For a list of configuration values that can be passed in, refer to these values
     *     in the [XEP-0045 MUC specification](https://xmpp.org/extensions/xep-0045.html#registrar-formtype-owner).
     *     The values should be named without the `muc#roomconfig_` prefix.
     * @param { boolean } [attrs.minimized] A boolean, indicating whether the room should be opened minimized or not.
     * @param { boolean } [attrs.bring_to_foreground] A boolean indicating whether the room should be
     *     brought to the foreground and therefore replace the currently shown chat.
     *     If there is no chat currently open, then this option is ineffective.
     * @param { Boolean } [force=false] - By default, a minimized
     *   room won't be maximized (in `overlayed` view mode) and in
     *   `fullscreen` view mode a newly opened room won't replace
     *   another chat already in the foreground.
     *   Set `force` to `true` if you want to force the room to be
     *   maximized or shown.
     * @returns {Promise} Promise which resolves with the Model representing the chat.
     *
     * @example
     * api.rooms.open('group@muc.example.com')
     *
     * @example
     * // To return an array of rooms, provide an array of room JIDs:
     * api.rooms.open(['group1@muc.example.com', 'group2@muc.example.com'])
     *
     * @example
     * // To setup a custom nickname when joining the room, provide the optional nick argument:
     * api.rooms.open('group@muc.example.com', {'nick': 'mycustomnick'})
     *
     * @example
     * // For example, opening a room with a specific default configuration:
     * api.rooms.open(
     *     'myroom@conference.example.org',
     *     { 'nick': 'coolguy69',
     *       'auto_configure': true,
     *       'roomconfig': {
     *           'changesubject': false,
     *           'membersonly': true,
     *           'persistentroom': true,
     *           'publicroom': true,
     *           'roomdesc': 'Comfy room for hanging out',
     *           'whois': 'anyone'
     *       }
     *     }
     * );
     */
    open: function open(jids) {
      var _arguments = arguments;
      return muc_api_asyncToGenerator( /*#__PURE__*/muc_api_regeneratorRuntime().mark(function _callee() {
        var attrs, force, err_msg, room, rooms;
        return muc_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              attrs = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
              force = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : false;
              _context.next = 4;
              return shared_api.waitUntil('chatBoxesFetched');
            case 4:
              if (!(jids === undefined)) {
                _context.next = 10;
                break;
              }
              err_msg = 'rooms.open: You need to provide at least one JID';
              log.error(err_msg);
              throw new TypeError(err_msg);
            case 10:
              if (!(typeof jids === 'string')) {
                _context.next = 18;
                break;
              }
              _context.next = 13;
              return shared_api.rooms.get(jids, attrs, true);
            case 13:
              room = _context.sent;
              !attrs.hidden && (room === null || room === void 0 ? void 0 : room.maybeShow(force));
              return _context.abrupt("return", room);
            case 18:
              _context.next = 20;
              return Promise.all(jids.map(function (jid) {
                return shared_api.rooms.get(jid, attrs, true);
              }));
            case 20:
              rooms = _context.sent;
              rooms.forEach(function (r) {
                return !attrs.hidden && r.maybeShow(force);
              });
              return _context.abrupt("return", rooms);
            case 23:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * Fetches the object representing a MUC chatroom (aka groupchat)
     *
     * @method api.rooms.get
     * @param { String } [jid] The room JID (if not specified, all rooms will be returned).
     * @param { Object } [attrs] A map containing any extra room attributes
     *  to be set if `create` is set to `true`
     * @param { String } [attrs.nick] Specify the nickname
     * @param { String } [attrs.password ] Specify a password if needed to enter a new room
     * @param { Boolean } create A boolean indicating whether the room should be created
     *     if not found (default: `false`)
     * @returns { Promise<_converse.ChatRoom> }
     * @example
     * api.waitUntil('roomsAutoJoined').then(() => {
     *     const create_if_not_found = true;
     *     api.rooms.get(
     *         'group@muc.example.com',
     *         {'nick': 'dread-pirate-roberts', 'password': 'secret'},
     *         create_if_not_found
     *     )
     * });
     */
    get: function get(jids) {
      var _arguments2 = arguments;
      return muc_api_asyncToGenerator( /*#__PURE__*/muc_api_regeneratorRuntime().mark(function _callee3() {
        var attrs, create, _get, _get2, chats;
        return muc_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              _get2 = function _get4() {
                _get2 = muc_api_asyncToGenerator( /*#__PURE__*/muc_api_regeneratorRuntime().mark(function _callee2(jid) {
                  var model;
                  return muc_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
                    while (1) switch (_context2.prev = _context2.next) {
                      case 0:
                        jid = api_u.getJIDFromURI(jid);
                        _context2.next = 3;
                        return shared_api.chatboxes.get(jid);
                      case 3:
                        model = _context2.sent;
                        if (!(!model && create)) {
                          _context2.next = 10;
                          break;
                        }
                        _context2.next = 7;
                        return shared_api.chatboxes.create(jid, attrs, shared_converse.ChatRoom);
                      case 7:
                        model = _context2.sent;
                        _context2.next = 12;
                        break;
                      case 10:
                        model = model && model.get('type') === shared_converse.CHATROOMS_TYPE ? model : null;
                        if (model && Object.keys(attrs).length) {
                          model.save(attrs);
                        }
                      case 12:
                        return _context2.abrupt("return", model);
                      case 13:
                      case "end":
                        return _context2.stop();
                    }
                  }, _callee2);
                }));
                return _get2.apply(this, arguments);
              };
              _get = function _get3(_x) {
                return _get2.apply(this, arguments);
              };
              attrs = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : {};
              create = _arguments2.length > 2 && _arguments2[2] !== undefined ? _arguments2[2] : false;
              _context3.next = 6;
              return shared_api.waitUntil('chatBoxesFetched');
            case 6:
              if (!(jids === undefined)) {
                _context3.next = 13;
                break;
              }
              _context3.next = 9;
              return shared_api.chatboxes.get();
            case 9:
              chats = _context3.sent;
              return _context3.abrupt("return", chats.filter(function (c) {
                return c.get('type') === shared_converse.CHATROOMS_TYPE;
              }));
            case 13:
              if (!(typeof jids === 'string')) {
                _context3.next = 15;
                break;
              }
              return _context3.abrupt("return", _get(jids));
            case 15:
              return _context3.abrupt("return", Promise.all(jids.map(function (jid) {
                return _get(jid);
              })));
            case 16:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/index.js
function plugins_muc_toConsumableArray(arr) {
  return plugins_muc_arrayWithoutHoles(arr) || plugins_muc_iterableToArray(arr) || plugins_muc_unsupportedIterableToArray(arr) || plugins_muc_nonIterableSpread();
}
function plugins_muc_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function plugins_muc_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return plugins_muc_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 plugins_muc_arrayLikeToArray(o, minLen);
}
function plugins_muc_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function plugins_muc_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return plugins_muc_arrayLikeToArray(arr);
}
function plugins_muc_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;
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Implements the non-view logic for XEP-0045 Multi-User Chat
 */














var muc_ROLES = (/* unused pure expression or super */ null && (['moderator', 'participant', 'visitor']));
var muc_AFFILIATIONS = ['owner', 'admin', 'member', 'outcast', 'none'];
public_converse.AFFILIATION_CHANGES = AFFILIATION_CHANGES;
public_converse.AFFILIATION_CHANGES_LIST = AFFILIATION_CHANGES_LIST;
public_converse.MUC_TRAFFIC_STATES = MUC_TRAFFIC_STATES;
public_converse.MUC_TRAFFIC_STATES_LIST = MUC_TRAFFIC_STATES_LIST;
public_converse.MUC_ROLE_CHANGES = MUC_ROLE_CHANGES;
public_converse.MUC_ROLE_CHANGES_LIST = MUC_ROLE_CHANGES_LIST;
public_converse.MUC = {
  INFO_CODES: INFO_CODES
};
public_converse.MUC_NICK_CHANGED_CODE = MUC_NICK_CHANGED_CODE;
public_converse.ROOM_FEATURES = ROOM_FEATURES;
public_converse.ROOMSTATUS = ROOMSTATUS;
var muc_Strophe = public_converse.env.Strophe;

// Add Strophe Namespaces
muc_Strophe.addNamespace('MUC_ADMIN', muc_Strophe.NS.MUC + '#admin');
muc_Strophe.addNamespace('MUC_OWNER', muc_Strophe.NS.MUC + '#owner');
muc_Strophe.addNamespace('MUC_REGISTER', 'jabber:iq:register');
muc_Strophe.addNamespace('MUC_ROOMCONF', muc_Strophe.NS.MUC + '#roomconfig');
muc_Strophe.addNamespace('MUC_USER', muc_Strophe.NS.MUC + '#user');
muc_Strophe.addNamespace('MUC_HATS', 'xmpp:prosody.im/protocol/hats:1');
muc_Strophe.addNamespace('CONFINFO', 'urn:ietf:params:xml:ns:conference-info');
public_converse.plugins.add('converse-muc', {
  dependencies: ['converse-chatboxes', 'converse-chat', 'converse-disco'],
  overrides: {
    ChatBoxes: {
      model: function model(attrs, options) {
        var _converse = this.__super__._converse;
        if (attrs && attrs.type == _converse.CHATROOMS_TYPE) {
          return new _converse.ChatRoom(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }
    }
  },
  initialize: function initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    var __ = shared_converse.__,
      ___ = shared_converse.___;

    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'allow_muc_invitations': true,
      'auto_join_on_invite': false,
      'auto_join_rooms': [],
      'auto_register_muc_nickname': false,
      'hide_muc_participants': false,
      'locked_muc_domain': false,
      'modtools_disable_assign': false,
      'muc_clear_messages_on_leave': true,
      'muc_domain': undefined,
      'muc_fetch_members': true,
      'muc_history_max_stanzas': undefined,
      'muc_instant_rooms': true,
      'muc_nickname_from_jid': false,
      'muc_send_probes': false,
      'muc_show_info_messages': [].concat(plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.visibility_changes), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.self), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.non_privacy_changes), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.muc_logging_changes), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.nickname_changes), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.disconnected), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.affiliation_changes), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.join_leave_events), plugins_muc_toConsumableArray(public_converse.MUC.INFO_CODES.role_changes)),
      'muc_show_logs_before_join': false,
      'muc_subscribe_to_rai': false
    });
    shared_api.promises.add(['roomsAutoJoined']);
    if (shared_api.settings.get('locked_muc_domain') && typeof shared_api.settings.get('muc_domain') !== 'string') {
      throw new Error('Config Error: it makes no sense to set locked_muc_domain ' + 'to true when muc_domain is not set');
    }

    // This is for tests (at least until we can import modules inside tests)
    public_converse.env.muc_utils = {
      computeAffiliationsDelta: computeAffiliationsDelta
    };
    Object.assign(shared_api, muc_api);
    Object.assign(shared_api.rooms, affiliations_api);

    /* https://xmpp.org/extensions/xep-0045.html
     * ----------------------------------------
     * 100 message      Entering a groupchat         Inform user that any occupant is allowed to see the user's full JID
     * 101 message (out of band)                     Affiliation change  Inform user that his or her affiliation changed while not in the groupchat
     * 102 message      Configuration change         Inform occupants that groupchat now shows unavailable members
     * 103 message      Configuration change         Inform occupants that groupchat now does not show unavailable members
     * 104 message      Configuration change         Inform occupants that a non-privacy-related groupchat configuration change has occurred
     * 110 presence     Any groupchat presence       Inform user that presence refers to one of its own groupchat occupants
     * 170 message or initial presence               Configuration change    Inform occupants that groupchat logging is now enabled
     * 171 message      Configuration change         Inform occupants that groupchat logging is now disabled
     * 172 message      Configuration change         Inform occupants that the groupchat is now non-anonymous
     * 173 message      Configuration change         Inform occupants that the groupchat is now semi-anonymous
     * 174 message      Configuration change         Inform occupants that the groupchat is now fully-anonymous
     * 201 presence     Entering a groupchat         Inform user that a new groupchat has been created
     * 210 presence     Entering a groupchat         Inform user that the service has assigned or modified the occupant's roomnick
     * 301 presence     Removal from groupchat       Inform user that he or she has been banned from the groupchat
     * 303 presence     Exiting a groupchat          Inform all occupants of new groupchat nickname
     * 307 presence     Removal from groupchat       Inform user that he or she has been kicked from the groupchat
     * 321 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because of an affiliation change
     * 322 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because the groupchat has been changed to members-only and the user is not a member
     * 332 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because of a system shutdown
     */
    shared_converse.muc = {
      info_messages: {
        100: __('This groupchat is not anonymous'),
        102: __('This groupchat now shows unavailable members'),
        103: __('This groupchat does not show unavailable members'),
        104: __('The groupchat configuration has changed'),
        170: __('Groupchat logging is now enabled'),
        171: __('Groupchat logging is now disabled'),
        172: __('This groupchat is now no longer anonymous'),
        173: __('This groupchat is now semi-anonymous'),
        174: __('This groupchat is now fully-anonymous'),
        201: __('A new groupchat has been created')
      },
      new_nickname_messages: {
        // XXX: Note the triple underscore function and not double underscore.
        210: ___('Your nickname has been automatically set to %1$s'),
        303: ___('Your nickname has been changed to %1$s')
      },
      disconnect_messages: {
        301: __('You have been banned from this groupchat'),
        333: __('You have exited this groupchat due to a technical problem'),
        307: __('You have been kicked from this groupchat'),
        321: __('You have been removed from this groupchat because of an affiliation change'),
        322: __("You have been removed from this groupchat because the groupchat has changed to members-only and you're not a member"),
        332: __('You have been removed from this groupchat because the service hosting it is being shut down')
      }
    };
    shared_converse.router.route('converse/room?jid=:jid', routeToRoom);
    shared_converse.ChatRoom = shared_converse.ChatBox.extend(muc);
    shared_converse.ChatRoomMessage = shared_converse.Message.extend(muc_message);
    shared_converse.ChatRoomOccupants = occupants;
    shared_converse.ChatRoomOccupant = occupant;

    /**
     * Collection which stores MUC messages
     * @class
     * @namespace _converse.ChatRoomMessages
     * @memberOf _converse
     */
    shared_converse.ChatRoomMessages = Collection.extend({
      model: shared_converse.ChatRoomMessage,
      comparator: 'time'
    });
    Object.assign(shared_converse, {
      getDefaultMUCNickname: getDefaultMUCNickname,
      isInfoVisible: isInfoVisible,
      onDirectMUCInvitation: onDirectMUCInvitation
    });

    /************************ BEGIN Event Handlers ************************/

    if (shared_api.settings.get('allow_muc_invitations')) {
      shared_api.listen.on('connected', registerDirectInvitationHandler);
      shared_api.listen.on('reconnected', registerDirectInvitationHandler);
    }
    shared_api.listen.on('addClientFeatures', function () {
      return shared_api.disco.own.features.add("".concat(muc_Strophe.NS.CONFINFO, "+notify"));
    });
    shared_api.listen.on('addClientFeatures', onAddClientFeatures);
    shared_api.listen.on('beforeResourceBinding', onBeforeResourceBinding);
    shared_api.listen.on('beforeTearDown', onBeforeTearDown);
    shared_api.listen.on('chatBoxesFetched', autoJoinRooms);
    shared_api.listen.on('disconnected', disconnectChatRooms);
    shared_api.listen.on('statusInitialized', onStatusInitialized);
    shared_api.listen.on('windowStateChanged', onWindowStateChanged);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/model.js


var bookmarks_model_Strophe = public_converse.env.Strophe;
var Bookmark = Model.extend({
  idAttribute: 'jid',
  getDisplayName: function getDisplayName() {
    return bookmarks_model_Strophe.xmlunescape(this.get('name'));
  }
});
/* harmony default export */ const bookmarks_model = (Bookmark);
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/collection.js
function bookmarks_collection_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmarks_collection_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;
  }, bookmarks_collection_typeof(obj);
}
function bookmarks_collection_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bookmarks_collection_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" == bookmarks_collection_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 bookmarks_collection_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 bookmarks_collection_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bookmarks_collection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bookmarks_collection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var collection_converse$env = public_converse.env,
  collection_Strophe = collection_converse$env.Strophe,
  collection_$iq = collection_converse$env.$iq,
  collection_sizzle = collection_converse$env.sizzle;
var Bookmarks = {
  model: bookmarks_model,
  comparator: function comparator(item) {
    return item.get('name').toLowerCase();
  },
  initialize: function initialize() {
    var _this = this;
    return bookmarks_collection_asyncToGenerator( /*#__PURE__*/bookmarks_collection_regeneratorRuntime().mark(function _callee() {
      var cache_key;
      return bookmarks_collection_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.on('add', function (bm) {
              return _this.openBookmarkedRoom(bm).then(function (bm) {
                return _this.markRoomAsBookmarked(bm);
              }).catch(function (e) {
                return log.fatal(e);
              });
            });
            _this.on('remove', _this.markRoomAsUnbookmarked, _this);
            _this.on('remove', _this.sendBookmarkStanza, _this);
            cache_key = "converse.room-bookmarks".concat(shared_converse.bare_jid);
            _this.fetched_flag = cache_key + 'fetched';
            initStorage(_this, cache_key);
            _context.next = 8;
            return _this.fetchBookmarks();
          case 8:
            /**
             * Triggered once the _converse.Bookmarks collection
             * has been created and cached bookmarks have been fetched.
             * @event _converse#bookmarksInitialized
             * @type { _converse.Bookmarks }
             * @example _converse.api.listen.on('bookmarksInitialized', (bookmarks) => { ... });
             */
            shared_api.trigger('bookmarksInitialized', _this);
          case 9:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  openBookmarkedRoom: function openBookmarkedRoom(bookmark) {
    return bookmarks_collection_asyncToGenerator( /*#__PURE__*/bookmarks_collection_regeneratorRuntime().mark(function _callee2() {
      var groupchat;
      return bookmarks_collection_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            if (!(shared_api.settings.get('muc_respect_autojoin') && bookmark.get('autojoin'))) {
              _context2.next = 5;
              break;
            }
            _context2.next = 3;
            return shared_api.rooms.create(bookmark.get('jid'), {
              'nick': bookmark.get('nick')
            });
          case 3:
            groupchat = _context2.sent;
            groupchat.maybeShow();
          case 5:
            return _context2.abrupt("return", bookmark);
          case 6:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  fetchBookmarks: function fetchBookmarks() {
    var deferred = getOpenPromise();
    if (window.sessionStorage.getItem(this.fetched_flag)) {
      this.fetch({
        'success': function success() {
          return deferred.resolve();
        },
        'error': function error() {
          return deferred.resolve();
        }
      });
    } else {
      this.fetchBookmarksFromServer(deferred);
    }
    return deferred;
  },
  createBookmark: function createBookmark(options) {
    var _this2 = this;
    this.create(options);
    this.sendBookmarkStanza().catch(function (iq) {
      return _this2.onBookmarkError(iq, options);
    });
  },
  sendBookmarkStanza: function sendBookmarkStanza() {
    var stanza = collection_$iq({
      'type': 'set',
      'from': shared_converse.connection.jid
    }).c('pubsub', {
      'xmlns': collection_Strophe.NS.PUBSUB
    }).c('publish', {
      'node': collection_Strophe.NS.BOOKMARKS
    }).c('item', {
      'id': 'current'
    }).c('storage', {
      'xmlns': collection_Strophe.NS.BOOKMARKS
    });
    this.forEach(function (model) {
      stanza.c('conference', {
        'name': model.get('name'),
        'autojoin': model.get('autojoin'),
        'jid': model.get('jid')
      }).c('nick').t(model.get('nick')).up().up();
    });
    stanza.up().up().up();
    stanza.c('publish-options').c('x', {
      'xmlns': collection_Strophe.NS.XFORM,
      'type': 'submit'
    }).c('field', {
      'var': 'FORM_TYPE',
      'type': 'hidden'
    }).c('value').t('http://jabber.org/protocol/pubsub#publish-options').up().up().c('field', {
      'var': 'pubsub#persist_items'
    }).c('value').t('true').up().up().c('field', {
      'var': 'pubsub#access_model'
    }).c('value').t('whitelist');
    return shared_api.sendIQ(stanza);
  },
  onBookmarkError: function onBookmarkError(iq, options) {
    var _this$get;
    var __ = shared_converse.__;
    log.error("Error while trying to add bookmark");
    log.error(iq);
    shared_api.alert('error', __('Error'), [__("Sorry, something went wrong while trying to save your bookmark.")]);
    (_this$get = this.get(options.jid)) === null || _this$get === void 0 ? void 0 : _this$get.destroy();
  },
  fetchBookmarksFromServer: function fetchBookmarksFromServer(deferred) {
    var _this3 = this;
    var stanza = collection_$iq({
      'from': shared_converse.connection.jid,
      'type': 'get'
    }).c('pubsub', {
      'xmlns': collection_Strophe.NS.PUBSUB
    }).c('items', {
      'node': collection_Strophe.NS.BOOKMARKS
    });
    shared_api.sendIQ(stanza).then(function (iq) {
      return _this3.onBookmarksReceived(deferred, iq);
    }).catch(function (iq) {
      return _this3.onBookmarksReceivedError(deferred, iq);
    });
  },
  markRoomAsBookmarked: function markRoomAsBookmarked(bookmark) {
    var groupchat = shared_converse.chatboxes.get(bookmark.get('jid'));
    groupchat === null || groupchat === void 0 ? void 0 : groupchat.save('bookmarked', true);
  },
  markRoomAsUnbookmarked: function markRoomAsUnbookmarked(bookmark) {
    var groupchat = shared_converse.chatboxes.get(bookmark.get('jid'));
    groupchat === null || groupchat === void 0 ? void 0 : groupchat.save('bookmarked', false);
  },
  createBookmarksFromStanza: function createBookmarksFromStanza(stanza) {
    var _this4 = this;
    var xmlns = collection_Strophe.NS.BOOKMARKS;
    var sel = "items[node=\"".concat(xmlns, "\"] item storage[xmlns=\"").concat(xmlns, "\"] conference");
    collection_sizzle(sel, stanza).forEach(function (el) {
      var _el$querySelector;
      var jid = el.getAttribute('jid');
      var bookmark = _this4.get(jid);
      var attrs = {
        'jid': jid,
        'name': el.getAttribute('name') || jid,
        'autojoin': el.getAttribute('autojoin') === 'true',
        'nick': ((_el$querySelector = el.querySelector('nick')) === null || _el$querySelector === void 0 ? void 0 : _el$querySelector.textContent) || ''
      };
      bookmark ? bookmark.save(attrs) : _this4.create(attrs);
    });
  },
  onBookmarksReceived: function onBookmarksReceived(deferred, iq) {
    this.createBookmarksFromStanza(iq);
    window.sessionStorage.setItem(this.fetched_flag, true);
    if (deferred !== undefined) {
      return deferred.resolve();
    }
  },
  onBookmarksReceivedError: function onBookmarksReceivedError(deferred, iq) {
    var __ = shared_converse.__;
    if (iq === null) {
      log.error('Error: timeout while fetching bookmarks');
      shared_api.alert('error', __('Timeout Error'), [__("The server did not return your bookmarks within the allowed time. " + "You can reload the page to request them again.")]);
    } else if (deferred) {
      if (iq.querySelector('error[type="cancel"] item-not-found')) {
        // Not an exception, the user simply doesn't have any bookmarks.
        window.sessionStorage.setItem(this.fetched_flag, true);
        return deferred.resolve();
      } else {
        log.error('Error while fetching bookmarks');
        log.error(iq);
        return deferred.reject(new Error("Could not fetch bookmarks"));
      }
    } else {
      log.error('Error while fetching bookmarks');
      log.error(iq);
    }
  },
  getUnopenedBookmarks: function getUnopenedBookmarks() {
    var _this5 = this;
    return bookmarks_collection_asyncToGenerator( /*#__PURE__*/bookmarks_collection_regeneratorRuntime().mark(function _callee3() {
      return bookmarks_collection_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return shared_api.waitUntil('bookmarksInitialized');
          case 2:
            _context3.next = 4;
            return shared_api.waitUntil('chatBoxesFetched');
          case 4:
            return _context3.abrupt("return", _this5.filter(function (b) {
              return !shared_converse.chatboxes.get(b.get('jid'));
            }));
          case 5:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  }
};
/* harmony default export */ const collection = (Bookmarks);
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/utils.js
function bookmarks_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmarks_utils_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;
  }, bookmarks_utils_typeof(obj);
}
function bookmarks_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bookmarks_utils_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" == bookmarks_utils_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 bookmarks_utils_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 bookmarks_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bookmarks_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bookmarks_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var bookmarks_utils_converse$env = public_converse.env,
  bookmarks_utils_Strophe = bookmarks_utils_converse$env.Strophe,
  bookmarks_utils_sizzle = bookmarks_utils_converse$env.sizzle;
function checkBookmarksSupport() {
  return _checkBookmarksSupport.apply(this, arguments);
}
function _checkBookmarksSupport() {
  _checkBookmarksSupport = bookmarks_utils_asyncToGenerator( /*#__PURE__*/bookmarks_utils_regeneratorRuntime().mark(function _callee() {
    var identity;
    return bookmarks_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return shared_api.disco.getIdentity('pubsub', 'pep', shared_converse.bare_jid);
        case 2:
          identity = _context.sent;
          if (!shared_api.settings.get('allow_public_bookmarks')) {
            _context.next = 7;
            break;
          }
          return _context.abrupt("return", !!identity);
        case 7:
          return _context.abrupt("return", shared_api.disco.supports(bookmarks_utils_Strophe.NS.PUBSUB + '#publish-options', shared_converse.bare_jid));
        case 8:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _checkBookmarksSupport.apply(this, arguments);
}
function initBookmarks() {
  return _initBookmarks.apply(this, arguments);
}
function _initBookmarks() {
  _initBookmarks = bookmarks_utils_asyncToGenerator( /*#__PURE__*/bookmarks_utils_regeneratorRuntime().mark(function _callee2() {
    return bookmarks_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (shared_api.settings.get('allow_bookmarks')) {
            _context2.next = 2;
            break;
          }
          return _context2.abrupt("return");
        case 2:
          _context2.next = 4;
          return checkBookmarksSupport();
        case 4:
          if (!_context2.sent) {
            _context2.next = 6;
            break;
          }
          shared_converse.bookmarks = new shared_converse.Bookmarks();
        case 6:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _initBookmarks.apply(this, arguments);
}
function getNicknameFromBookmark(jid) {
  var _converse$bookmarks, _converse$bookmarks$g;
  if (!shared_api.settings.get('allow_bookmarks')) {
    return null;
  }
  return (_converse$bookmarks = shared_converse.bookmarks) === null || _converse$bookmarks === void 0 ? void 0 : (_converse$bookmarks$g = _converse$bookmarks.get(jid)) === null || _converse$bookmarks$g === void 0 ? void 0 : _converse$bookmarks$g.get('nick');
}
function handleBookmarksPush(message) {
  if (bookmarks_utils_sizzle("event[xmlns=\"".concat(bookmarks_utils_Strophe.NS.PUBSUB, "#event\"] items[node=\"").concat(bookmarks_utils_Strophe.NS.BOOKMARKS, "\"]"), message).length) {
    shared_api.waitUntil('bookmarksInitialized').then(function () {
      return shared_converse.bookmarks.createBookmarksFromStanza(message);
    }).catch(function (e) {
      return log.fatal(e);
    });
  }
  return true;
}
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/index.js
function bookmarks_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmarks_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;
  }, bookmarks_typeof(obj);
}
function bookmarks_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bookmarks_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" == bookmarks_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 bookmarks_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 bookmarks_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bookmarks_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bookmarks_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @description
 * Converse.js plugin which adds views for bookmarks specified in XEP-0048.
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






var bookmarks_Strophe = public_converse.env.Strophe;
bookmarks_Strophe.addNamespace('BOOKMARKS', 'storage:bookmarks');
public_converse.plugins.add('converse-bookmarks', {
  dependencies: ["converse-chatboxes", "converse-muc"],
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    // New functions which don't exist yet can also be added.

    ChatRoom: {
      getDisplayName: function getDisplayName() {
        var _converse$bookmarks;
        var _this$__super__ = this.__super__,
          _converse = _this$__super__._converse,
          getDisplayName = _this$__super__.getDisplayName;
        var bookmark = this.get('bookmarked') ? (_converse$bookmarks = _converse.bookmarks) === null || _converse$bookmarks === void 0 ? void 0 : _converse$bookmarks.get(this.get('jid')) : null;
        return (bookmark === null || bookmark === void 0 ? void 0 : bookmark.get('name')) || getDisplayName.apply(this, arguments);
      },
      getAndPersistNickname: function getAndPersistNickname(nick) {
        nick = nick || getNicknameFromBookmark(this.get('jid'));
        return this.__super__.getAndPersistNickname.call(this, nick);
      }
    }
  },
  initialize: function initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      allow_bookmarks: true,
      allow_public_bookmarks: false,
      muc_respect_autojoin: true
    });
    shared_api.promises.add('bookmarksInitialized');
    shared_converse.Bookmark = bookmarks_model;
    shared_converse.Bookmarks = Collection.extend(collection);
    shared_api.listen.on('addClientFeatures', function () {
      if (shared_api.settings.get('allow_bookmarks')) {
        shared_api.disco.own.features.add(bookmarks_Strophe.NS.BOOKMARKS + '+notify');
      }
    });
    shared_api.listen.on('clearSession', function () {
      if (shared_converse.bookmarks) {
        shared_converse.bookmarks.clearStore({
          'silent': true
        });
        window.sessionStorage.removeItem(shared_converse.bookmarks.fetched_flag);
        delete shared_converse.bookmarks;
      }
    });
    shared_api.listen.on('connected', /*#__PURE__*/bookmarks_asyncToGenerator( /*#__PURE__*/bookmarks_regeneratorRuntime().mark(function _callee() {
      var connection;
      return bookmarks_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            // Add a handler for bookmarks pushed from other connected clients
            connection = shared_converse.connection;
            connection.addHandler(handleBookmarksPush, null, 'message', 'headline', null, shared_converse.bare_jid);
            _context.next = 4;
            return Promise.all([shared_api.waitUntil('chatBoxesFetched')]);
          case 4:
            initBookmarks();
          case 5:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/bosh.js
function bosh_typeof(obj) {
  "@babel/helpers - typeof";

  return bosh_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;
  }, bosh_typeof(obj);
}
function bosh_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bosh_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" == bosh_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 bosh_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 bosh_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bosh_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bosh_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse.js plugin which add support for XEP-0206: XMPP Over BOSH
 */





var bosh_Strophe = public_converse.env.Strophe;
var BOSH_SESSION_ID = 'converse.bosh-session';
public_converse.plugins.add('converse-bosh', {
  enabled: function enabled() {
    return !shared_converse.api.settings.get("blacklisted_plugins").includes('converse-bosh');
  },
  initialize: function initialize() {
    shared_api.settings.extend({
      bosh_service_url: undefined,
      prebind_url: null
    });
    function initBOSHSession() {
      return _initBOSHSession.apply(this, arguments);
    }
    function _initBOSHSession() {
      _initBOSHSession = bosh_asyncToGenerator( /*#__PURE__*/bosh_regeneratorRuntime().mark(function _callee3() {
        var id, jid, _jid;
        return bosh_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              id = BOSH_SESSION_ID;
              if (shared_converse.bosh_session) {
                _context3.next = 6;
                break;
              }
              shared_converse.bosh_session = new Model({
                id: id
              });
              shared_converse.bosh_session.browserStorage = shared_converse.createStore(id, "session");
              _context3.next = 6;
              return new Promise(function (resolve) {
                return shared_converse.bosh_session.fetch({
                  'success': resolve,
                  'error': resolve
                });
              });
            case 6:
              if (!shared_converse.jid) {
                _context3.next = 15;
                break;
              }
              if (!(shared_converse.bosh_session.get('jid') !== shared_converse.jid)) {
                _context3.next = 13;
                break;
              }
              _context3.next = 10;
              return setUserJID(shared_converse.jid);
            case 10:
              jid = _context3.sent;
              shared_converse.bosh_session.clear({
                'silent': true
              });
              shared_converse.bosh_session.save({
                jid: jid
              });
            case 13:
              _context3.next = 20;
              break;
            case 15:
              // Keepalive
              _jid = shared_converse.bosh_session.get('jid');
              _context3.t0 = _jid;
              if (!_context3.t0) {
                _context3.next = 20;
                break;
              }
              _context3.next = 20;
              return setUserJID(_jid);
            case 20:
              return _context3.abrupt("return", shared_converse.bosh_session);
            case 21:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return _initBOSHSession.apply(this, arguments);
    }
    shared_converse.startNewPreboundBOSHSession = function () {
      if (!shared_api.settings.get('prebind_url')) {
        throw new Error("startNewPreboundBOSHSession: If you use prebind then you MUST supply a prebind_url");
      }
      var xhr = new XMLHttpRequest();
      xhr.open('GET', shared_api.settings.get('prebind_url'), true);
      xhr.setRequestHeader('Accept', 'application/json, text/javascript');
      xhr.onload = /*#__PURE__*/bosh_asyncToGenerator( /*#__PURE__*/bosh_regeneratorRuntime().mark(function _callee() {
        var data, jid;
        return bosh_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!(xhr.status >= 200 && xhr.status < 400)) {
                _context.next = 8;
                break;
              }
              data = JSON.parse(xhr.responseText);
              _context.next = 4;
              return setUserJID(data.jid);
            case 4:
              jid = _context.sent;
              shared_converse.connection.attach(jid, data.sid, data.rid, shared_converse.connection.onConnectStatusChanged, BOSH_WAIT);
              _context.next = 9;
              break;
            case 8:
              xhr.onerror();
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      xhr.onerror = function () {
        delete shared_converse.connection;
        /**
         * Triggered when fetching prebind tokens failed
         * @event _converse#noResumeableBOSHSession
         * @type { _converse }
         * @example _converse.api.listen.on('noResumeableBOSHSession', _converse => { ... });
         */
        shared_api.trigger('noResumeableBOSHSession', shared_converse);
      };
      xhr.send();
    };
    shared_converse.restoreBOSHSession = /*#__PURE__*/bosh_asyncToGenerator( /*#__PURE__*/bosh_regeneratorRuntime().mark(function _callee2() {
      var jid;
      return bosh_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return initBOSHSession();
          case 2:
            jid = _context2.sent.get('jid');
            if (!(jid && shared_converse.connection._proto instanceof bosh_Strophe.Bosh)) {
              _context2.next = 13;
              break;
            }
            _context2.prev = 4;
            shared_converse.connection.restore(jid, shared_converse.connection.onConnectStatusChanged);
            return _context2.abrupt("return", true);
          case 9:
            _context2.prev = 9;
            _context2.t0 = _context2["catch"](4);
            !shared_converse.isTestEnv() && log.warn("Could not restore session for jid: " + jid + " Error message: " + _context2.t0.message);
            return _context2.abrupt("return", false);
          case 13:
            return _context2.abrupt("return", false);
          case 14:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[4, 9]]);
    }));

    /************************ BEGIN Event Handlers ************************/
    shared_api.listen.on('clearSession', function () {
      if (shared_converse.bosh_session === undefined) {
        // Remove manually, even if we don't have the corresponding
        // model, to avoid trying to reconnect to a stale BOSH session
        var id = BOSH_SESSION_ID;
        sessionStorage.removeItem(id);
        sessionStorage.removeItem("".concat(id, "-").concat(id));
      } else {
        shared_converse.bosh_session.destroy();
        delete shared_converse.bosh_session;
      }
    });
    shared_api.listen.on('setUserJID', function () {
      if (shared_converse.bosh_session !== undefined) {
        shared_converse.bosh_session.save({
          'jid': shared_converse.jid
        });
      }
    });
    shared_api.listen.on('addClientFeatures', function () {
      return shared_api.disco.own.features.add(bosh_Strophe.NS.BOSH);
    });

    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/
    Object.assign(shared_api, {
      /**
       * This namespace lets you access the BOSH tokens
       *
       * @namespace api.tokens
       * @memberOf api
       */
      tokens: {
        /**
         * @method api.tokens.get
         * @param { string } [id] The type of token to return ('rid' or 'sid').
         * @returns 'string' A token, either the RID or SID token depending on what's asked for.
         * @example _converse.api.tokens.get('rid');
         */
        get: function get(id) {
          if (shared_converse.connection === undefined) {
            return null;
          }
          if (id.toLowerCase() === 'rid') {
            return shared_converse.connection.rid || shared_converse.connection._proto.rid;
          } else if (id.toLowerCase() === 'sid') {
            return shared_converse.connection.sid || shared_converse.connection._proto.sid;
          }
        }
      }
    });
    /************************ end api ************************/
  }
});
;// CONCATENATED MODULE: ./src/headless/utils/arraybuffer.js

var arraybuffer_u = public_converse.env.u;
function appendArrayBuffer(buffer1, buffer2) {
  var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
  tmp.set(new Uint8Array(buffer1), 0);
  tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
  return tmp.buffer;
}
function arrayBufferToHex(ab) {
  // https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex#40031979
  return Array.prototype.map.call(new Uint8Array(ab), function (x) {
    return ('00' + x.toString(16)).slice(-2);
  }).join('');
}
function arrayBufferToString(ab) {
  return new TextDecoder("utf-8").decode(ab);
}
function stringToArrayBuffer(string) {
  var bytes = new TextEncoder("utf-8").encode(string);
  return bytes.buffer;
}
function arrayBufferToBase64(ab) {
  return btoa(new Uint8Array(ab).reduce(function (data, byte) {
    return data + String.fromCharCode(byte);
  }, ''));
}
function base64ToArrayBuffer(b64) {
  var binary_string = window.atob(b64),
    len = binary_string.length,
    bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}
function hexToArrayBuffer(hex) {
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16);
  }));
  return typedArray.buffer;
}
Object.assign(arraybuffer_u, {
  arrayBufferToHex: arrayBufferToHex,
  arrayBufferToString: arrayBufferToString,
  stringToArrayBuffer: stringToArrayBuffer,
  arrayBufferToBase64: arrayBufferToBase64,
  base64ToArrayBuffer: base64ToArrayBuffer
});
;// CONCATENATED MODULE: ./src/headless/plugins/caps/utils.js
function caps_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return caps_utils_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;
  }, caps_utils_typeof(obj);
}
function caps_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  caps_utils_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" == caps_utils_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 caps_utils_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 caps_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        caps_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        caps_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var caps_utils_converse$env = public_converse.env,
  caps_utils_Strophe = caps_utils_converse$env.Strophe,
  $build = caps_utils_converse$env.$build;
function propertySort(array, property) {
  return array.sort(function (a, b) {
    return a[property] > b[property] ? -1 : 1;
  });
}
function generateVerificationString() {
  return _generateVerificationString.apply(this, arguments);
}
function _generateVerificationString() {
  _generateVerificationString = caps_utils_asyncToGenerator( /*#__PURE__*/caps_utils_regeneratorRuntime().mark(function _callee() {
    var identities, features, S, ab;
    return caps_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          identities = shared_converse.api.disco.own.identities.get();
          features = shared_converse.api.disco.own.features.get();
          if (identities.length > 1) {
            propertySort(identities, "category");
            propertySort(identities, "type");
            propertySort(identities, "lang");
          }
          S = identities.reduce(function (result, id) {
            var _id$lang;
            return "".concat(result).concat(id.category, "/").concat(id.type, "/").concat((_id$lang = id === null || id === void 0 ? void 0 : id.lang) !== null && _id$lang !== void 0 ? _id$lang : '', "/").concat(id.name, "<");
          }, "");
          features.sort();
          S = features.reduce(function (result, feature) {
            return "".concat(result).concat(feature, "<");
          }, S);
          _context.next = 8;
          return crypto.subtle.digest('SHA-1', stringToArrayBuffer(S));
        case 8:
          ab = _context.sent;
          return _context.abrupt("return", arrayBufferToBase64(ab));
        case 10:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _generateVerificationString.apply(this, arguments);
}
function createCapsNode() {
  return _createCapsNode.apply(this, arguments);
}
/**
 * Given a stanza, adds a XEP-0115 CAPS element
 * @param { Element } stanza
 */
function _createCapsNode() {
  _createCapsNode = caps_utils_asyncToGenerator( /*#__PURE__*/caps_utils_regeneratorRuntime().mark(function _callee2() {
    return caps_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.t0 = $build;
          _context2.t1 = caps_utils_Strophe.NS.CAPS;
          _context2.next = 4;
          return generateVerificationString();
        case 4:
          _context2.t2 = _context2.sent;
          _context2.t3 = {
            'xmlns': _context2.t1,
            'hash': "sha-1",
            'node': "https://conversejs.org",
            'ver': _context2.t2
          };
          return _context2.abrupt("return", (0, _context2.t0)("c", _context2.t3).tree());
        case 7:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _createCapsNode.apply(this, arguments);
}
function addCapsNode(_x) {
  return _addCapsNode.apply(this, arguments);
}
function _addCapsNode() {
  _addCapsNode = caps_utils_asyncToGenerator( /*#__PURE__*/caps_utils_regeneratorRuntime().mark(function _callee3(stanza) {
    var caps_el;
    return caps_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return createCapsNode();
        case 2:
          caps_el = _context3.sent;
          stanza.root().cnode(caps_el).up();
          return _context3.abrupt("return", stanza);
        case 5:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _addCapsNode.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/caps/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


var caps_Strophe = public_converse.env.Strophe;
caps_Strophe.addNamespace('CAPS', "http://jabber.org/protocol/caps");
public_converse.plugins.add('converse-caps', {
  dependencies: ['converse-status'],
  initialize: function initialize() {
    shared_api.listen.on('constructedPresence', function (_, p) {
      return addCapsNode(p);
    });
    shared_api.listen.on('constructedMUCPresence', function (_, p) {
      return addCapsNode(p);
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/chatboxes.js



var ChatBoxes = Collection.extend({
  comparator: 'time_opened',
  model: function model(attrs, options) {
    return new shared_converse.ChatBox(attrs, options);
  },
  onChatBoxesFetched: function onChatBoxesFetched(collection) {
    collection.filter(function (c) {
      return !c.isValid();
    }).forEach(function (c) {
      return c.destroy();
    });
    /**
     * Triggered once all chat boxes have been recreated from the browser cache
     * @event _converse#chatBoxesFetched
     * @type { object }
     * @property { _converse.ChatBox | _converse.ChatRoom } chatbox
     * @property { Element } stanza
     * @example _converse.api.listen.on('chatBoxesFetched', obj => { ... });
     * @example _converse.api.waitUntil('chatBoxesFetched').then(() => { ... });
     */
    shared_api.trigger('chatBoxesFetched');
  },
  onConnected: function onConnected(reconnecting) {
    var _this = this;
    if (reconnecting) {
      return;
    }
    initStorage(this, "converse.chatboxes-".concat(shared_converse.bare_jid));
    this.fetch({
      'add': true,
      'success': function success(c) {
        return _this.onChatBoxesFetched(c);
      }
    });
  }
});
/* harmony default export */ const chatboxes = (ChatBoxes);
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/utils.js
function chatboxes_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return chatboxes_utils_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;
  }, chatboxes_utils_typeof(obj);
}
function chatboxes_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chatboxes_utils_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" == chatboxes_utils_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 chatboxes_utils_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 chatboxes_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chatboxes_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chatboxes_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var chatboxes_utils_Strophe = public_converse.env.Strophe;
function createChatBox(_x, _x2, _x3) {
  return _createChatBox.apply(this, arguments);
}
function _createChatBox() {
  _createChatBox = chatboxes_utils_asyncToGenerator( /*#__PURE__*/chatboxes_utils_regeneratorRuntime().mark(function _callee(jid, attrs, Model) {
    var chatbox;
    return chatboxes_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          jid = chatboxes_utils_Strophe.getBareJidFromJid(jid.toLowerCase());
          Object.assign(attrs, {
            'jid': jid,
            'id': jid
          });
          _context.prev = 2;
          chatbox = new Model(attrs, {
            'collection': shared_converse.chatboxes
          });
          _context.next = 10;
          break;
        case 6:
          _context.prev = 6;
          _context.t0 = _context["catch"](2);
          log.error(_context.t0);
          return _context.abrupt("return", null);
        case 10:
          _context.next = 12;
          return chatbox.initialized;
        case 12:
          if (chatbox.isValid()) {
            _context.next = 15;
            break;
          }
          chatbox.destroy();
          return _context.abrupt("return", null);
        case 15:
          shared_converse.chatboxes.add(chatbox);
          return _context.abrupt("return", chatbox);
        case 17:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[2, 6]]);
  }));
  return _createChatBox.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/api.js
function chatboxes_api_typeof(obj) {
  "@babel/helpers - typeof";

  return chatboxes_api_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;
  }, chatboxes_api_typeof(obj);
}
function chatboxes_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chatboxes_api_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" == chatboxes_api_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 chatboxes_api_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 chatboxes_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chatboxes_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chatboxes_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



/**
 * The "chatboxes" namespace.
 *
 * @namespace api.chatboxes
 * @memberOf api
 */
/* harmony default export */ const chatboxes_api = ({
  /**
   * @method api.chats.create
   * @param { String|String[] } jids - A JID or array of JIDs
   * @param { Object } [attrs] An object containing configuration attributes
   * @param { Model } model - The type of chatbox that should be created
   */
  create: function create() {
    var _arguments = arguments;
    return chatboxes_api_asyncToGenerator( /*#__PURE__*/chatboxes_api_regeneratorRuntime().mark(function _callee() {
      var jids, attrs, model;
      return chatboxes_api_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            jids = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : [];
            attrs = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
            model = _arguments.length > 2 ? _arguments[2] : undefined;
            _context.next = 5;
            return shared_api.waitUntil('chatBoxesFetched');
          case 5:
            if (!(typeof jids === 'string')) {
              _context.next = 9;
              break;
            }
            return _context.abrupt("return", createChatBox(jids, attrs, model));
          case 9:
            return _context.abrupt("return", Promise.all(jids.map(function (jid) {
              return createChatBox(jid, attrs, model);
            })));
          case 10:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * @method api.chats.get
   * @param { String|String[] } jids - A JID or array of JIDs
   */
  get: function get(jids) {
    return chatboxes_api_asyncToGenerator( /*#__PURE__*/chatboxes_api_regeneratorRuntime().mark(function _callee2() {
      return chatboxes_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return shared_api.waitUntil('chatBoxesFetched');
          case 2:
            if (!(jids === undefined)) {
              _context2.next = 6;
              break;
            }
            return _context2.abrupt("return", shared_converse.chatboxes.models);
          case 6:
            if (!(typeof jids === 'string')) {
              _context2.next = 10;
              break;
            }
            return _context2.abrupt("return", shared_converse.chatboxes.get(jids.toLowerCase()));
          case 10:
            jids = jids.map(function (j) {
              return j.toLowerCase();
            });
            return _context2.abrupt("return", shared_converse.chatboxes.models.filter(function (m) {
              return jids.includes(m.get('jid'));
            }));
          case 12:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




var chatboxes_Strophe = public_converse.env.Strophe;
public_converse.plugins.add('converse-chatboxes', {
  dependencies: ["converse-emoji", "converse-roster", "converse-vcard"],
  initialize: function initialize() {
    shared_api.promises.add(['chatBoxesFetched', 'chatBoxesInitialized', 'privateChatsAutoJoined']);
    Object.assign(shared_api, {
      'chatboxes': chatboxes_api
    });
    shared_converse.ChatBoxes = chatboxes;
    shared_api.listen.on('addClientFeatures', function () {
      shared_api.disco.own.features.add(chatboxes_Strophe.NS.MESSAGE_CORRECT);
      shared_api.disco.own.features.add(chatboxes_Strophe.NS.HTTPUPLOAD);
      shared_api.disco.own.features.add(chatboxes_Strophe.NS.OUTOFBAND);
    });
    shared_api.listen.on('pluginsInitialized', function () {
      shared_converse.chatboxes = new shared_converse.ChatBoxes();
      /**
       * Triggered once the _converse.ChatBoxes collection has been initialized.
       * @event _converse#chatBoxesInitialized
       * @example _converse.api.listen.on('chatBoxesInitialized', () => { ... });
       * @example _converse.api.waitUntil('chatBoxesInitialized').then(() => { ... });
       */
      shared_api.trigger('chatBoxesInitialized');
    });
    shared_api.listen.on('presencesInitialized', function (reconnecting) {
      return shared_converse.chatboxes.onConnected(reconnecting);
    });
    shared_api.listen.on('reconnected', function () {
      return shared_converse.chatboxes.forEach(function (m) {
        return m.onReconnection();
      });
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/utils.js



var adhoc_utils_converse$env = public_converse.env,
  adhoc_utils_Strophe = adhoc_utils_converse$env.Strophe,
  adhoc_utils_u = adhoc_utils_converse$env.u;
function parseForCommands(stanza) {
  var items = external_sizzle_default()("query[xmlns=\"".concat(adhoc_utils_Strophe.NS.DISCO_ITEMS, "\"][node=\"").concat(adhoc_utils_Strophe.NS.ADHOC, "\"] item"), stanza);
  return items.map(getAttributes);
}
function getCommandFields(iq, jid) {
  var _sizzle$pop, _Array$from$map, _cmd_el$querySelector;
  var cmd_el = external_sizzle_default()("command[xmlns=\"".concat(adhoc_utils_Strophe.NS.ADHOC, "\"]"), iq).pop();
  var data = {
    sessionid: cmd_el.getAttribute('sessionid'),
    instructions: (_sizzle$pop = external_sizzle_default()('x[type="form"][xmlns="jabber:x:data"] instructions', cmd_el).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent,
    fields: external_sizzle_default()('x[type="form"][xmlns="jabber:x:data"] field', cmd_el).map(function (f) {
      return adhoc_utils_u.xForm2TemplateResult(f, cmd_el, {
        domain: jid
      });
    }),
    actions: (_Array$from$map = Array.from((_cmd_el$querySelector = cmd_el.querySelector('actions')) === null || _cmd_el$querySelector === void 0 ? void 0 : _cmd_el$querySelector.children).map(function (a) {
      return a.nodeName.toLowerCase();
    })) !== null && _Array$from$map !== void 0 ? _Array$from$map : []
  };
  return data;
}
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/api.js
function adhoc_api_typeof(obj) {
  "@babel/helpers - typeof";

  return adhoc_api_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;
  }, adhoc_api_typeof(obj);
}
var _templateObject, _templateObject2;
function adhoc_api_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 adhoc_api_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? adhoc_api_ownKeys(Object(source), !0).forEach(function (key) {
      adhoc_api_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : adhoc_api_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function adhoc_api_defineProperty(obj, key, value) {
  key = adhoc_api_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 adhoc_api_toPropertyKey(arg) {
  var key = adhoc_api_toPrimitive(arg, "string");
  return adhoc_api_typeof(key) === "symbol" ? key : String(key);
}
function adhoc_api_toPrimitive(input, hint) {
  if (adhoc_api_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (adhoc_api_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function adhoc_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  adhoc_api_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" == adhoc_api_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 adhoc_api_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 adhoc_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        adhoc_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        adhoc_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var adhoc_api_converse$env = public_converse.env,
  adhoc_api_Strophe = adhoc_api_converse$env.Strophe,
  adhoc_api_$iq = adhoc_api_converse$env.$iq,
  adhoc_api_u = adhoc_api_converse$env.u,
  api_stx = adhoc_api_converse$env.stx;
/* harmony default export */ const adhoc_api = ({
  /**
   * The XEP-0050 Ad-Hoc Commands API
   *
   * This API lets you discover ad-hoc commands available for an entity in the XMPP network.
   *
   * @namespace api.adhoc
   * @memberOf api
   */
  adhoc: {
    /**
     * @method api.adhoc.getCommands
     * @param { String } to_jid
     */
    getCommands: function getCommands(to_jid) {
      return adhoc_api_asyncToGenerator( /*#__PURE__*/adhoc_api_regeneratorRuntime().mark(function _callee() {
        return adhoc_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.t0 = parseForCommands;
              _context.next = 4;
              return shared_api.disco.items(to_jid, adhoc_api_Strophe.NS.ADHOC);
            case 4:
              _context.t1 = _context.sent;
              return _context.abrupt("return", (0, _context.t0)(_context.t1));
            case 8:
              _context.prev = 8;
              _context.t2 = _context["catch"](0);
              if (_context.t2 === null) {
                log.error("Error: timeout while fetching ad-hoc commands for ".concat(to_jid));
              } else {
                log.error("Error while fetching ad-hoc commands for ".concat(to_jid));
                log.error(_context.t2);
              }
              return _context.abrupt("return", []);
            case 12:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[0, 8]]);
      }))();
    },
    /**
     * @method api.adhoc.fetchCommandForm
     */
    fetchCommandForm: function fetchCommandForm(command) {
      return adhoc_api_asyncToGenerator( /*#__PURE__*/adhoc_api_regeneratorRuntime().mark(function _callee2() {
        var node, jid, stanza, __;
        return adhoc_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              node = command.node;
              jid = command.jid;
              stanza = adhoc_api_$iq({
                'type': 'set',
                'to': jid
              }).c('command', {
                'xmlns': adhoc_api_Strophe.NS.ADHOC,
                'node': node,
                'action': 'execute'
              });
              _context2.prev = 3;
              _context2.t0 = getCommandFields;
              _context2.next = 7;
              return shared_api.sendIQ(stanza);
            case 7:
              _context2.t1 = _context2.sent;
              _context2.t2 = jid;
              return _context2.abrupt("return", (0, _context2.t0)(_context2.t1, _context2.t2));
            case 12:
              _context2.prev = 12;
              _context2.t3 = _context2["catch"](3);
              if (_context2.t3 === null) {
                log.error("Error: timeout while trying to execute command for ".concat(jid));
              } else {
                log.error("Error while trying to execute command for ".concat(jid));
                log.error(_context2.t3);
              }
              __ = shared_converse.__;
              return _context2.abrupt("return", {
                instructions: __('An error occurred while trying to fetch the command form'),
                fields: []
              });
            case 17:
            case "end":
              return _context2.stop();
          }
        }, _callee2, null, [[3, 12]]);
      }))();
    },
    /**
     * @method api.adhoc.runCommand
     * @param { String } jid
     * @param { String } sessionid
     * @param { 'execute' | 'cancel' | 'prev' | 'next' | 'complete' } action
     * @param { String } node
     * @param { Array<{ string: string }> } inputs
     */
    runCommand: function runCommand(jid, sessionid, node, action, inputs) {
      return adhoc_api_asyncToGenerator( /*#__PURE__*/adhoc_api_regeneratorRuntime().mark(function _callee3() {
        var _result$querySelector;
        var iq, result, __, command, status;
        return adhoc_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              iq = api_stx(_templateObject || (_templateObject = _taggedTemplateLiteral(["<iq type=\"set\" to=\"", "\" xmlns=\"jabber:client\">\n                    <command sessionid=\"", "\" node=\"", "\" action=\"", "\" xmlns=\"", "\">\n                        ", "\n                    </command>\n                </iq>"])), jid, sessionid, node, action, adhoc_api_Strophe.NS.ADHOC, !['cancel', 'prev'].includes(action) ? api_stx(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n                            <x xmlns=\"", "\" type=\"submit\">\n                                ", "\n                            </x>"])), adhoc_api_Strophe.NS.XFORM, inputs.reduce(function (out, _ref) {
                var name = _ref.name,
                  value = _ref.value;
                return out + "<field var=\"".concat(name, "\"><value>").concat(value, "</value></field>");
              }, '')) : '');
              _context3.next = 3;
              return shared_api.sendIQ(iq, null, false);
            case 3:
              result = _context3.sent;
              if (!(result === null)) {
                _context3.next = 10;
                break;
              }
              log.warn("A timeout occurred while trying to run an ad-hoc command");
              __ = shared_converse.__;
              return _context3.abrupt("return", {
                status: 'error',
                note: __('A timeout occurred')
              });
            case 10:
              if (adhoc_api_u.isErrorStanza(result)) {
                log.error('Error while trying to execute an ad-hoc command');
                log.error(result);
              }
            case 11:
              command = result.querySelector('command');
              status = command === null || command === void 0 ? void 0 : command.getAttribute('status');
              return _context3.abrupt("return", adhoc_api_objectSpread(adhoc_api_objectSpread({
                status: status
              }, status === 'executing' ? getCommandFields(result) : {}), {}, {
                note: (_result$querySelector = result.querySelector('note')) === null || _result$querySelector === void 0 ? void 0 : _result$querySelector.textContent
              }));
            case 14:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/index.js


var adhoc_Strophe = public_converse.env.Strophe;
adhoc_Strophe.addNamespace('ADHOC', 'http://jabber.org/protocol/commands');
public_converse.plugins.add('converse-adhoc', {
  dependencies: ["converse-disco"],
  initialize: function initialize() {
    Object.assign(this._converse.api, adhoc_api);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/feed.js
function feed_typeof(obj) {
  "@babel/helpers - typeof";

  return feed_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;
  }, feed_typeof(obj);
}
function feed_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  feed_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" == feed_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 feed_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 feed_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        feed_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        feed_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function feed_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function feed_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, feed_toPropertyKey(descriptor.key), descriptor);
  }
}
function feed_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) feed_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) feed_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function feed_toPropertyKey(arg) {
  var key = feed_toPrimitive(arg, "string");
  return feed_typeof(key) === "symbol" ? key : String(key);
}
function feed_toPrimitive(input, hint) {
  if (feed_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (feed_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function feed_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) feed_setPrototypeOf(subClass, superClass);
}
function feed_setPrototypeOf(o, p) {
  feed_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return feed_setPrototypeOf(o, p);
}
function feed_createSuper(Derived) {
  var hasNativeReflectConstruct = feed_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = feed_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = feed_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return feed_possibleConstructorReturn(this, result);
  };
}
function feed_possibleConstructorReturn(self, call) {
  if (call && (feed_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 feed_assertThisInitialized(self);
}
function feed_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function feed_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 feed_getPrototypeOf(o) {
  feed_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return feed_getPrototypeOf(o);
}


var HeadlinesFeed = /*#__PURE__*/function (_ChatBox) {
  feed_inherits(HeadlinesFeed, _ChatBox);
  var _super = feed_createSuper(HeadlinesFeed);
  function HeadlinesFeed() {
    feed_classCallCheck(this, HeadlinesFeed);
    return _super.apply(this, arguments);
  }
  feed_createClass(HeadlinesFeed, [{
    key: "defaults",
    value: function defaults() {
      return {
        'bookmarked': false,
        'hidden': ['mobile', 'fullscreen'].includes(shared_api.settings.get("view_mode")),
        'message_type': 'headline',
        'num_unread': 0,
        'time_opened': this.get('time_opened') || new Date().getTime(),
        'type': shared_converse.HEADLINES_TYPE
      };
    }
  }, {
    key: "initialize",
    value: function () {
      var _initialize = feed_asyncToGenerator( /*#__PURE__*/feed_regeneratorRuntime().mark(function _callee() {
        return feed_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.set({
                'box_id': "box-".concat(this.get('jid'))
              });
              this.initUI();
              this.initMessages();
              _context.next = 5;
              return this.fetchMessages();
            case 5:
              /**
               * Triggered once a { @link _converse.HeadlinesFeed } has been created and initialized.
               * @event _converse#headlinesFeedInitialized
               * @type { _converse.HeadlinesFeed }
               * @example _converse.api.listen.on('headlinesFeedInitialized', model => { ... });
               */
              shared_api.trigger('headlinesFeedInitialized', this);
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }]);
  return HeadlinesFeed;
}(model);

;// CONCATENATED MODULE: ./src/headless/plugins/headlines/api.js
function headlines_api_typeof(obj) {
  "@babel/helpers - typeof";

  return headlines_api_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;
  }, headlines_api_typeof(obj);
}
function headlines_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  headlines_api_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" == headlines_api_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 headlines_api_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 headlines_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        headlines_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        headlines_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

/* harmony default export */ const headlines_api = ({
  /**
   * The "headlines" namespace, which is used for headline-channels
   * which are read-only channels containing messages of type
   * "headline".
   *
   * @namespace api.headlines
   * @memberOf api
   */
  headlines: {
    /**
     * Retrieves a headline-channel or all headline-channels.
     *
     * @method api.headlines.get
     * @param {String|String[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
     * @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
     * @param { Boolean } [create=false] - Whether the chat should be created if it's not found.
     * @returns { Promise<_converse.HeadlinesFeed> }
     */
    get: function get(jids) {
      var _arguments = arguments;
      return headlines_api_asyncToGenerator( /*#__PURE__*/headlines_api_regeneratorRuntime().mark(function _callee2() {
        var attrs, create, _get, _get2, chats;
        return headlines_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _get2 = function _get4() {
                _get2 = headlines_api_asyncToGenerator( /*#__PURE__*/headlines_api_regeneratorRuntime().mark(function _callee(jid) {
                  var model;
                  return headlines_api_regeneratorRuntime().wrap(function _callee$(_context) {
                    while (1) switch (_context.prev = _context.next) {
                      case 0:
                        _context.next = 2;
                        return shared_api.chatboxes.get(jid);
                      case 2:
                        model = _context.sent;
                        if (!(!model && create)) {
                          _context.next = 9;
                          break;
                        }
                        _context.next = 6;
                        return shared_api.chatboxes.create(jid, attrs, shared_converse.HeadlinesFeed);
                      case 6:
                        model = _context.sent;
                        _context.next = 11;
                        break;
                      case 9:
                        model = model && model.get('type') === shared_converse.HEADLINES_TYPE ? model : null;
                        if (model && Object.keys(attrs).length) {
                          model.save(attrs);
                        }
                      case 11:
                        return _context.abrupt("return", model);
                      case 12:
                      case "end":
                        return _context.stop();
                    }
                  }, _callee);
                }));
                return _get2.apply(this, arguments);
              };
              _get = function _get3(_x) {
                return _get2.apply(this, arguments);
              };
              attrs = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
              create = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : false;
              if (!(jids === undefined)) {
                _context2.next = 11;
                break;
              }
              _context2.next = 7;
              return shared_api.chatboxes.get();
            case 7:
              chats = _context2.sent;
              return _context2.abrupt("return", chats.filter(function (c) {
                return c.get('type') === shared_converse.HEADLINES_TYPE;
              }));
            case 11:
              if (!(typeof jids === 'string')) {
                _context2.next = 13;
                break;
              }
              return _context2.abrupt("return", _get(jids));
            case 13:
              return _context2.abrupt("return", Promise.all(jids.map(function (jid) {
                return _get(jid);
              })));
            case 14:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/utils.js
function headlines_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return headlines_utils_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;
  }, headlines_utils_typeof(obj);
}
function headlines_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  headlines_utils_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" == headlines_utils_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 headlines_utils_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 headlines_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        headlines_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        headlines_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}




/**
 * Handler method for all incoming messages of type "headline".
 * @param { Element } stanza
 */
function onHeadlineMessage(_x) {
  return _onHeadlineMessage.apply(this, arguments);
}
function _onHeadlineMessage() {
  _onHeadlineMessage = headlines_utils_asyncToGenerator( /*#__PURE__*/headlines_utils_regeneratorRuntime().mark(function _callee(stanza) {
    var from_jid, chatbox, attrs;
    return headlines_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!(isHeadline(stanza) || isServerMessage(stanza))) {
            _context.next = 15;
            break;
          }
          from_jid = stanza.getAttribute('from');
          _context.next = 4;
          return shared_api.waitUntil('rosterInitialized');
        case 4:
          if (!(from_jid.includes('@') && !shared_converse.roster.get(from_jid) && !shared_api.settings.get("allow_non_roster_messaging"))) {
            _context.next = 6;
            break;
          }
          return _context.abrupt("return");
        case 6:
          if (!(stanza.querySelector('body') === null)) {
            _context.next = 8;
            break;
          }
          return _context.abrupt("return");
        case 8:
          chatbox = shared_converse.chatboxes.create({
            'id': from_jid,
            'jid': from_jid,
            'type': shared_converse.HEADLINES_TYPE,
            'from': from_jid
          });
          _context.next = 11;
          return parseMessage(stanza, shared_converse);
        case 11:
          attrs = _context.sent;
          _context.next = 14;
          return chatbox.createMessage(attrs);
        case 14:
          shared_api.trigger('message', {
            chatbox: chatbox,
            stanza: stanza,
            attrs: attrs
          });
        case 15:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _onHeadlineMessage.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/index.js
/**
 * @module converse-headlines
 * @copyright 2022, the Converse.js contributors
 */




public_converse.plugins.add('converse-headlines', {
  dependencies: ["converse-chat"],
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.

    ChatBoxes: {
      model: function model(attrs, options) {
        var _converse = this.__super__._converse;
        if (attrs.type == _converse.HEADLINES_TYPE) {
          return new _converse.HeadlinesFeed(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }
    }
  },
  initialize: function initialize() {
    /**
     * Shows headline messages
     * @class
     * @namespace _converse.HeadlinesFeed
     * @memberOf _converse
     */
    shared_converse.HeadlinesFeed = HeadlinesFeed;
    function registerHeadlineHandler() {
      shared_converse.connection.addHandler(function (m) {
        return onHeadlineMessage(m) || true;
      }, null, 'message');
    }
    shared_api.listen.on('connected', registerHeadlineHandler);
    shared_api.listen.on('reconnected', registerHeadlineHandler);
    Object.assign(shared_api, headlines_api);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/mam/placeholder.js
function placeholder_typeof(obj) {
  "@babel/helpers - typeof";

  return placeholder_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;
  }, placeholder_typeof(obj);
}
function placeholder_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function placeholder_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, placeholder_toPropertyKey(descriptor.key), descriptor);
  }
}
function placeholder_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) placeholder_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) placeholder_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function placeholder_toPropertyKey(arg) {
  var key = placeholder_toPrimitive(arg, "string");
  return placeholder_typeof(key) === "symbol" ? key : String(key);
}
function placeholder_toPrimitive(input, hint) {
  if (placeholder_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (placeholder_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function placeholder_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) placeholder_setPrototypeOf(subClass, superClass);
}
function placeholder_setPrototypeOf(o, p) {
  placeholder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return placeholder_setPrototypeOf(o, p);
}
function placeholder_createSuper(Derived) {
  var hasNativeReflectConstruct = placeholder_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = placeholder_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = placeholder_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return placeholder_possibleConstructorReturn(this, result);
  };
}
function placeholder_possibleConstructorReturn(self, call) {
  if (call && (placeholder_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 placeholder_assertThisInitialized(self);
}
function placeholder_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function placeholder_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 placeholder_getPrototypeOf(o) {
  placeholder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return placeholder_getPrototypeOf(o);
}


var placeholder_u = public_converse.env.utils;
var MAMPlaceholderMessage = /*#__PURE__*/function (_Model) {
  placeholder_inherits(MAMPlaceholderMessage, _Model);
  var _super = placeholder_createSuper(MAMPlaceholderMessage);
  function MAMPlaceholderMessage() {
    placeholder_classCallCheck(this, MAMPlaceholderMessage);
    return _super.apply(this, arguments);
  }
  placeholder_createClass(MAMPlaceholderMessage, [{
    key: "defaults",
    value: function defaults() {
      // eslint-disable-line class-methods-use-this
      return {
        'msgid': placeholder_u.getUniqueId(),
        'is_ephemeral': false
      };
    }
  }]);
  return MAMPlaceholderMessage;
}(Model);

;// CONCATENATED MODULE: ./src/headless/shared/rsm.js
function rsm_typeof(obj) {
  "@babel/helpers - typeof";

  return rsm_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;
  }, rsm_typeof(obj);
}
function rsm_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function rsm_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, rsm_toPropertyKey(descriptor.key), descriptor);
  }
}
function rsm_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) rsm_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) rsm_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function rsm_toPropertyKey(arg) {
  var key = rsm_toPrimitive(arg, "string");
  return rsm_typeof(key) === "symbol" ? key : String(key);
}
function rsm_toPrimitive(input, hint) {
  if (rsm_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (rsm_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/**
 * @module converse-rsm
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description XEP-0059 Result Set Management
 *   Some code taken from the Strophe RSM plugin, licensed under the MIT License
 *   Copyright 2006-2017 Strophe (https://github.com/strophe/strophejs)
 */


var rsm_converse$env = public_converse.env,
  rsm_Strophe = rsm_converse$env.Strophe,
  rsm_$build = rsm_converse$env.$build;
rsm_Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');

/**
 * @typedef { Object } RSMQueryParameters
 * [XEP-0059 RSM](https://xmpp.org/extensions/xep-0059.html) Attributes that can be used to filter query results
 * @property { String } [after] - The XEP-0359 stanza ID of a message after which messages should be returned. Implies forward paging.
 * @property { String } [before] - The XEP-0359 stanza ID of a message before which messages should be returned. Implies backward paging.
 * @property { number } [index=0] - The index of the results page to return.
 * @property { number } [max] - The maximum number of items to return.
 */

var RSM_QUERY_PARAMETERS = ['after', 'before', 'index', 'max'];
var rsm_toNumber = function toNumber(v) {
  return Number(v);
};
var rsm_toString = function toString(v) {
  return v.toString();
};
var RSM_TYPES = {
  'after': rsm_toString,
  'before': rsm_toString,
  'count': rsm_toNumber,
  'first': rsm_toString,
  'index': rsm_toNumber,
  'last': rsm_toString,
  'max': rsm_toNumber
};
var isUndefined = function isUndefined(x) {
  return typeof x === 'undefined';
};

// This array contains both query attributes and response attributes
var RSM_ATTRIBUTES = Object.keys(RSM_TYPES);

/**
 * Instances of this class are used to page through query results according to XEP-0059 Result Set Management
 * @class RSM
 */
var RSM = /*#__PURE__*/function () {
  /**
   * Create a new RSM instance
   * @param { Object } options - Configuration options
   * @constructor
   */
  function RSM() {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    rsm_classCallCheck(this, RSM);
    this.query = RSM.getQueryParameters(options);
    this.result = options.xml ? RSM.parseXMLResult(options.xml) : {};
  }

  /**
   * Returns a `<set>` XML element that confirms to XEP-0059 Result Set Management.
   * The element is constructed based on the {@link module:converse-rsm~RSMQueryParameters}
   * that are set on this RSM instance.
   * @returns { Element }
   */
  rsm_createClass(RSM, [{
    key: "toXML",
    value: function toXML() {
      var _this = this;
      var xml = rsm_$build('set', {
        xmlns: rsm_Strophe.NS.RSM
      });
      var reducer = function reducer(xml, a) {
        return !isUndefined(_this.query[a]) ? xml.c(a).t((_this.query[a] || '').toString()).up() : xml;
      };
      return RSM_QUERY_PARAMETERS.reduce(reducer, xml).tree();
    }
  }, {
    key: "next",
    value: function next(max, before) {
      var options = Object.assign({}, this.query, {
        after: this.result.last,
        before: before,
        max: max
      });
      return new RSM(options);
    }
  }, {
    key: "previous",
    value: function previous(max, after) {
      var options = Object.assign({}, this.query, {
        after: after,
        before: this.result.first,
        max: max
      });
      return new RSM(options);
    }
  }], [{
    key: "getQueryParameters",
    value: function getQueryParameters() {
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return lodash_es_pick(options, RSM_QUERY_PARAMETERS);
    }
  }, {
    key: "parseXMLResult",
    value: function parseXMLResult(set) {
      var result = {};
      for (var i = 0; i < RSM_ATTRIBUTES.length; i++) {
        var attr = RSM_ATTRIBUTES[i];
        var elem = set.getElementsByTagName(attr)[0];
        if (!isUndefined(elem) && elem !== null) {
          result[attr] = RSM_TYPES[attr](rsm_Strophe.getText(elem));
          if (attr == 'first') {
            result.index = RSM_TYPES['index'](elem.getAttribute('index'));
          }
        }
      }
      return result;
    }
  }]);
  return RSM;
}();
shared_converse.RSM_ATTRIBUTES = RSM_ATTRIBUTES;
shared_converse.RSM = RSM;
;// CONCATENATED MODULE: ./src/headless/plugins/mam/api.js
function mam_api_typeof(obj) {
  "@babel/helpers - typeof";

  return mam_api_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;
  }, mam_api_typeof(obj);
}
function mam_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  mam_api_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" == mam_api_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 mam_api_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 mam_api_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? mam_api_ownKeys(Object(source), !0).forEach(function (key) {
      mam_api_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : mam_api_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function mam_api_defineProperty(obj, key, value) {
  key = mam_api_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 mam_api_toPropertyKey(arg) {
  var key = mam_api_toPrimitive(arg, "string");
  return mam_api_typeof(key) === "symbol" ? key : String(key);
}
function mam_api_toPrimitive(input, hint) {
  if (mam_api_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (mam_api_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function mam_api_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 mam_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        mam_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        mam_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var mam_api_converse$env = public_converse.env,
  mam_api_Strophe = mam_api_converse$env.Strophe,
  mam_api_$iq = mam_api_converse$env.$iq,
  dayjs = mam_api_converse$env.dayjs;
var api_NS = mam_api_Strophe.NS;
var mam_api_u = public_converse.env.utils;
/* harmony default export */ const mam_api = ({
  /**
   * The [XEP-0313](https://xmpp.org/extensions/xep-0313.html) Message Archive Management API
   *
   * Enables you to query an XMPP server for archived messages.
   *
   * See also the [message-archiving](/docs/html/configuration.html#message-archiving)
   * option in the configuration settings section, which you'll
   * usually want to use in conjunction with this API.
   *
   * @namespace _converse.api.archive
   * @memberOf _converse.api
   */
  archive: {
    /**
     * @typedef { module:converse-rsm~RSMQueryParameters } MAMFilterParameters
     * Filter parameters which can be used to filter a MAM XEP-0313 archive
     * @property { String } [end] - A date string in ISO-8601 format, before which messages should be returned. Implies backward paging.
     * @property { String } [start] - A date string in ISO-8601 format, after which messages should be returned. Implies forward paging.
     * @property { String } [with] - A JID against which to match messages, according to either their `to` or `from` attributes.
     *     An item in a MUC archive matches if the publisher of the item matches the JID.
     *     If `with` is omitted, all messages that match the rest of the query will be returned, regardless of to/from
     *     addresses of each message.
     */
    /**
     * The options that can be passed in to the {@link _converse.api.archive.query } method
     * @typedef { module:converse-mam~MAMFilterParameters } ArchiveQueryOptions
     * @property { Boolean } [groupchat=false] - Whether the MAM archive is for a groupchat.
     */
    /**
     * Query for archived messages.
     *
     * The options parameter can also be an instance of
     * RSM to enable easy querying between results pages.
     *
     * @method _converse.api.archive.query
     * @param { module:converse-mam~ArchiveQueryOptions } options - An object containing query parameters
     * @throws {Error} An error is thrown if the XMPP server responds with an error.
     * @returns { Promise<module:converse-mam~MAMQueryResult> } A promise which resolves
     *     to a {@link module:converse-mam~MAMQueryResult } object.
     *
     * @example
     * // Requesting all archived messages
     * // ================================
     * //
     * // The simplest query that can be made is to simply not pass in any parameters.
     * // Such a query will return all archived messages for the current user.
     *
     * let result;
     * try {
     *     result = await api.archive.query();
     * } catch (e) {
     *     // The query was not successful, perhaps inform the user?
     *     // The IQ stanza returned by the XMPP server is passed in, so that you
     *     // may inspect it and determine what the problem was.
     * }
     * // Do something with the messages, like showing them in your webpage.
     * result.messages.forEach(m => this.showMessage(m));
     *
     * @example
     * // Requesting all archived messages for a particular contact or room
     * // =================================================================
     * //
     * // To query for messages sent between the current user and another user or room,
     * // the query options need to contain the the JID (Jabber ID) of the user or
     * // room under the  `with` key.
     *
     * // For a particular user
     * let result;
     * try {
     *    result = await api.archive.query({'with': 'john@doe.net'});
     * } catch (e) {
     *     // The query was not successful
     * }
     *
     * // For a particular room
     * let result;
     * try {
     *    result = await api.archive.query({'with': 'discuss@conference.doglovers.net', 'groupchat': true});
     * } catch (e) {
     *     // The query was not successful
     * }
     *
     * @example
     * // Requesting all archived messages before or after a certain date
     * // ===============================================================
     * //
     * // The `start` and `end` parameters are used to query for messages
     * // within a certain timeframe. The passed in date values may either be ISO8601
     * // formatted date strings, or JavaScript Date objects.
     *
     *  const options = {
     *      'with': 'john@doe.net',
     *      'start': '2010-06-07T00:00:00Z',
     *      'end': '2010-07-07T13:23:54Z'
     *  };
     * let result;
     * try {
     *    result = await api.archive.query(options);
     * } catch (e) {
     *     // The query was not successful
     * }
     *
     * @example
     * // Limiting the amount of messages returned
     * // ========================================
     * //
     * // The amount of returned messages may be limited with the `max` parameter.
     * // By default, the messages are returned from oldest to newest.
     *
     * // Return maximum 10 archived messages
     * let result;
     * try {
     *     result = await api.archive.query({'with': 'john@doe.net', 'max':10});
     * } catch (e) {
     *     // The query was not successful
     * }
     *
     * @example
     * // Paging forwards through a set of archived messages
     * // ==================================================
     * //
     * // When limiting the amount of messages returned per query, you might want to
     * // repeatedly make a further query to fetch the next batch of messages.
     * //
     * // To simplify this usecase for you, the callback method receives not only an array
     * // with the returned archived messages, but also a special RSM (*Result Set Management*)
     * // object which contains the query parameters you passed in, as well
     * // as two utility methods `next`, and `previous`.
     * //
     * // When you call one of these utility methods on the returned RSM object, and then
     * // pass the result into a new query, you'll receive the next or previous batch of
     * // archived messages. Please note, when calling these methods, pass in an integer
     * // to limit your results.
     *
     * const options = {'with': 'john@doe.net', 'max':10};
     * let result;
     * try {
     *     result = await api.archive.query(options);
     * } catch (e) {
     *     // The query was not successful
     * }
     * // Do something with the messages, like showing them in your webpage.
     * result.messages.forEach(m => this.showMessage(m));
     *
     * while (!result.complete) {
     *     try {
     *         result = await api.archive.query(Object.assign(options, rsm.next(10).query));
     *     } catch (e) {
     *         // The query was not successful
     *     }
     *     // Do something with the messages, like showing them in your webpage.
     *     result.messages.forEach(m => this.showMessage(m));
     * }
     *
     * @example
     * // Paging backwards through a set of archived messages
     * // ===================================================
     * //
     * // To page backwards through the archive, you need to know the UID of the message
     * // which you'd like to page backwards from and then pass that as value for the
     * // `before` parameter. If you simply want to page backwards from the most recent
     * // message, pass in the `before` parameter with an empty string value `''`.
     *
     * let result;
     * const options = {'before': '', 'max':5};
     * try {
     *     result = await api.archive.query(options);
     * } catch (e) {
     *     // The query was not successful
     * }
     * // Do something with the messages, like showing them in your webpage.
     * result.messages.forEach(m => this.showMessage(m));
     *
     * // Now we query again, to get the previous batch.
     * try {
     *      result = await api.archive.query(Object.assign(options, rsm.previous(5).query));
     * } catch (e) {
     *     // The query was not successful
     * }
     * // Do something with the messages, like showing them in your webpage.
     * result.messages.forEach(m => this.showMessage(m));
     *
     */
    query: function query(options) {
      return mam_api_asyncToGenerator( /*#__PURE__*/mam_api_regeneratorRuntime().mark(function _callee() {
        var attrs, jid, supported, queryid, stanza, _rsm, messages, message_handler, error, timeout, iq_result, __, err_msg, _, _err_msg, rsm, fin, complete, set;
        return mam_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (shared_api.connection.connected()) {
                _context.next = 2;
                break;
              }
              throw new Error('Can\'t call `api.archive.query` before having established an XMPP session');
            case 2:
              attrs = {
                'type': 'set'
              };
              if (!(options && options.groupchat)) {
                _context.next = 7;
                break;
              }
              if (options['with']) {
                _context.next = 6;
                break;
              }
              throw new Error('You need to specify a "with" value containing ' + 'the chat room JID, when querying groupchat messages.');
            case 6:
              attrs.to = options['with'];
            case 7:
              jid = attrs.to || shared_converse.bare_jid;
              _context.next = 10;
              return shared_api.disco.supports(api_NS.MAM, jid);
            case 10:
              supported = _context.sent;
              if (supported) {
                _context.next = 14;
                break;
              }
              log.warn("Did not fetch MAM archive for ".concat(jid, " because it doesn't support ").concat(api_NS.MAM));
              return _context.abrupt("return", {
                'messages': []
              });
            case 14:
              queryid = mam_api_u.getUniqueId();
              stanza = mam_api_$iq(attrs).c('query', {
                'xmlns': api_NS.MAM,
                'queryid': queryid
              });
              if (options) {
                stanza.c('x', {
                  'xmlns': api_NS.XFORM,
                  'type': 'submit'
                }).c('field', {
                  'var': 'FORM_TYPE',
                  'type': 'hidden'
                }).c('value').t(api_NS.MAM).up().up();
                if (options['with'] && !options.groupchat) {
                  stanza.c('field', {
                    'var': 'with'
                  }).c('value').t(options['with']).up().up();
                }
                ['start', 'end'].forEach(function (t) {
                  if (options[t]) {
                    var date = dayjs(options[t]);
                    if (date.isValid()) {
                      stanza.c('field', {
                        'var': t
                      }).c('value').t(date.toISOString()).up().up();
                    } else {
                      throw new TypeError("archive.query: invalid date provided for: ".concat(t));
                    }
                  }
                });
                stanza.up();
                _rsm = new RSM(options);
                if (Object.keys(_rsm.query).length) {
                  stanza.cnode(_rsm.toXML());
                }
              }
              messages = [];
              message_handler = shared_converse.connection.addHandler(function (stanza) {
                var result = external_sizzle_default()("message > result[xmlns=\"".concat(api_NS.MAM, "\"]"), stanza).pop();
                if (result === undefined || result.getAttribute('queryid') !== queryid) {
                  return true;
                }
                var from = stanza.getAttribute('from') || shared_converse.bare_jid;
                if (options.groupchat) {
                  if (from !== options['with']) {
                    log.warn("Ignoring alleged groupchat MAM message from ".concat(stanza.getAttribute('from')));
                    return true;
                  }
                } else if (from !== shared_converse.bare_jid) {
                  log.warn("Ignoring alleged MAM message from ".concat(stanza.getAttribute('from')));
                  return true;
                }
                messages.push(stanza);
                return true;
              }, api_NS.MAM);
              timeout = shared_api.settings.get('message_archiving_timeout');
              _context.next = 22;
              return shared_api.sendIQ(stanza, timeout, false);
            case 22:
              iq_result = _context.sent;
              if (!(iq_result === null)) {
                _context.next = 31;
                break;
              }
              __ = shared_converse.__;
              err_msg = __("Timeout while trying to fetch archived messages.");
              log.error(err_msg);
              error = new TimeoutError(err_msg);
              return _context.abrupt("return", {
                messages: messages,
                error: error
              });
            case 31:
              if (!mam_api_u.isErrorStanza(iq_result)) {
                _context.next = 38;
                break;
              }
              _ = shared_converse.__;
              _err_msg = _('An error occurred while querying for archived messages.');
              log.error(_err_msg);
              log.error(iq_result);
              error = new Error(_err_msg);
              return _context.abrupt("return", {
                messages: messages,
                error: error
              });
            case 38:
              shared_converse.connection.deleteHandler(message_handler);
              fin = iq_result && external_sizzle_default()("fin[xmlns=\"".concat(api_NS.MAM, "\"]"), iq_result).pop();
              complete = (fin === null || fin === void 0 ? void 0 : fin.getAttribute('complete')) === 'true';
              set = external_sizzle_default()("set[xmlns=\"".concat(api_NS.RSM, "\"]"), fin).pop();
              if (set) {
                rsm = new RSM(mam_api_objectSpread(mam_api_objectSpread({}, options), {}, {
                  'xml': set
                }));
              }
              /**
               * @typedef { Object } MAMQueryResult
               * @property { Array } messages
               * @property { RSM } [rsm] - An instance of {@link RSM}.
               *  You can call `next()` or `previous()` on this instance,
               *  to get the RSM query parameters for the next or previous
               *  page in the result set.
               * @property { Boolean } complete
               * @property { Error } [error]
               */
              return _context.abrupt("return", {
                messages: messages,
                rsm: rsm,
                complete: complete
              });
            case 44:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/mam/utils.js
function mam_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return mam_utils_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;
  }, mam_utils_typeof(obj);
}
function mam_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  mam_utils_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" == mam_utils_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 mam_utils_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 mam_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        mam_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        mam_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var mam_utils_converse$env = public_converse.env,
  mam_utils_Strophe = mam_utils_converse$env.Strophe,
  mam_utils_$iq = mam_utils_converse$env.$iq;
var utils_NS = mam_utils_Strophe.NS;
var mam_utils_u = public_converse.env.utils;
function onMAMError(iq) {
  if (iq !== null && iq !== void 0 && iq.querySelectorAll('feature-not-implemented').length) {
    log.warn("Message Archive Management (XEP-0313) not supported by ".concat(iq.getAttribute('from')));
  } else {
    log.error("Error while trying to set archiving preferences for ".concat(iq.getAttribute('from'), "."));
    log.error(iq);
  }
}

/**
 * Handle returned IQ stanza containing Message Archive
 * Management (XEP-0313) preferences.
 *
 * XXX: For now we only handle the global default preference.
 * The XEP also provides for per-JID preferences, which is
 * currently not supported in converse.js.
 *
 * Per JID preferences will be set in chat boxes, so it'll
 * probbaly be handled elsewhere in any case.
 */
function onMAMPreferences(iq, feature) {
  var preference = external_sizzle_default()("prefs[xmlns=\"".concat(utils_NS.MAM, "\"]"), iq).pop();
  var default_pref = preference.getAttribute('default');
  if (default_pref !== shared_api.settings.get('message_archiving')) {
    var stanza = mam_utils_$iq({
      'type': 'set'
    }).c('prefs', {
      'xmlns': utils_NS.MAM,
      'default': shared_api.settings.get('message_archiving')
    });
    Array.from(preference.children).forEach(function (child) {
      return stanza.cnode(child).up();
    });

    // XXX: Strictly speaking, the server should respond with the updated prefs
    // (see example 18: https://xmpp.org/extensions/xep-0313.html#config)
    // but Prosody doesn't do this, so we don't rely on it.
    shared_api.sendIQ(stanza).then(function () {
      return feature.save({
        'preferences': {
          'default': shared_api.settings.get('message_archiving')
        }
      });
    }).catch(shared_converse.onMAMError);
  } else {
    feature.save({
      'preferences': {
        'default': shared_api.settings.get('message_archiving')
      }
    });
  }
}
function getMAMPrefsFromFeature(feature) {
  var prefs = feature.get('preferences') || {};
  if (feature.get('var') !== utils_NS.MAM || shared_api.settings.get('message_archiving') === undefined) {
    return;
  }
  if (prefs['default'] !== shared_api.settings.get('message_archiving')) {
    shared_api.sendIQ(mam_utils_$iq({
      'type': 'get'
    }).c('prefs', {
      'xmlns': utils_NS.MAM
    })).then(function (iq) {
      return shared_converse.onMAMPreferences(iq, feature);
    }).catch(shared_converse.onMAMError);
  }
}
function preMUCJoinMAMFetch(muc) {
  if (!shared_api.settings.get('muc_show_logs_before_join') || !muc.features.get('mam_enabled') || muc.get('prejoin_mam_fetched')) {
    return;
  }
  fetchNewestMessages(muc);
  muc.save({
    'prejoin_mam_fetched': true
  });
}
function handleMAMResult(_x, _x2, _x3, _x4, _x5) {
  return _handleMAMResult.apply(this, arguments);
}

/**
 * @typedef { Object } MAMOptions
 * A map of MAM related options that may be passed to fetchArchivedMessages
 * @param { number } [options.max] - The maximum number of items to return.
 *  Defaults to "archived_messages_page_size"
 * @param { string } [options.after] - The XEP-0359 stanza ID of a message
 *  after which messages should be returned. Implies forward paging.
 * @param { string } [options.before] - The XEP-0359 stanza ID of a message
 *  before which messages should be returned. Implies backward paging.
 * @param { string } [options.end] - A date string in ISO-8601 format,
 *  before which messages should be returned. Implies backward paging.
 * @param { string } [options.start] - A date string in ISO-8601 format,
 *  after which messages should be returned. Implies forward paging.
 * @param { string } [options.with] - The JID of the entity with
 *  which messages were exchanged.
 * @param { boolean } [options.groupchat] - True if archive in groupchat.
 */

/**
 * Fetch XEP-0313 archived messages based on the passed in criteria.
 * @param { ChatBox | ChatRoom } model
 * @param { MAMOptions } [options]
 * @param { ('forwards'|'backwards'|null)} [should_page=null] - Determines whether
 *  this function should recursively page through the entire result set if a limited
 *  number of results were returned.
 */
function _handleMAMResult() {
  _handleMAMResult = mam_utils_asyncToGenerator( /*#__PURE__*/mam_utils_regeneratorRuntime().mark(function _callee(model, result, query, options, should_page) {
    var is_muc, doParseMessage, messages, data, event_id;
    return mam_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return shared_api.emojis.initialize();
        case 2:
          is_muc = model.get('type') === shared_converse.CHATROOMS_TYPE;
          doParseMessage = function doParseMessage(s) {
            return is_muc ? parseMUCMessage(s, model) : parseMessage(s);
          };
          _context.next = 6;
          return Promise.all(result.messages.map(doParseMessage));
        case 6:
          messages = _context.sent;
          result.messages = messages;

          /**
           * Synchronous event which allows listeners to first do some
           * work based on the MAM result before calling the handlers here.
           * @event _converse#MAMResult
           */
          data = {
            query: query,
            'chatbox': model,
            messages: messages
          };
          _context.next = 11;
          return shared_api.trigger('MAMResult', data, {
            'synchronous': true
          });
        case 11:
          messages.forEach(function (m) {
            return model.queueMessage(m);
          });
          if (result.error) {
            event_id = result.error.retry_event_id = mam_utils_u.getUniqueId();
            shared_api.listen.once(event_id, function () {
              return fetchArchivedMessages(model, options, should_page);
            });
            model.createMessageFromError(result.error);
          }
        case 13:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _handleMAMResult.apply(this, arguments);
}
function fetchArchivedMessages(_x6) {
  return _fetchArchivedMessages.apply(this, arguments);
}

/**
 * Create a placeholder message which is used to indicate gaps in the history.
 * @param { _converse.ChatBox | _converse.ChatRoom } model
 * @param { MAMOptions } options
 * @param { object } result - The RSM result object
 */
function _fetchArchivedMessages() {
  _fetchArchivedMessages = mam_utils_asyncToGenerator( /*#__PURE__*/mam_utils_regeneratorRuntime().mark(function _callee2(model) {
    var options,
      should_page,
      is_muc,
      mam_jid,
      max,
      query,
      result,
      _args2 = arguments;
    return mam_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          options = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
          should_page = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : null;
          if (!model.disable_mam) {
            _context2.next = 4;
            break;
          }
          return _context2.abrupt("return");
        case 4:
          is_muc = model.get('type') === shared_converse.CHATROOMS_TYPE;
          mam_jid = is_muc ? model.get('jid') : shared_converse.bare_jid;
          _context2.next = 8;
          return shared_api.disco.supports(utils_NS.MAM, mam_jid);
        case 8:
          if (_context2.sent) {
            _context2.next = 10;
            break;
          }
          return _context2.abrupt("return");
        case 10:
          max = shared_api.settings.get('archived_messages_page_size');
          query = Object.assign({
            'groupchat': is_muc,
            'max': max,
            'with': model.get('jid')
          }, options);
          _context2.next = 14;
          return shared_api.archive.query(query);
        case 14:
          result = _context2.sent;
          _context2.next = 17;
          return handleMAMResult(model, result, query, options, should_page);
        case 17:
          if (!(result.rsm && !result.complete)) {
            _context2.next = 24;
            break;
          }
          if (!should_page) {
            _context2.next = 23;
            break;
          }
          if (should_page === 'forwards') {
            options = result.rsm.next(max, options.before).query;
          } else if (should_page === 'backwards') {
            options = result.rsm.previous(max, options.after).query;
          }
          return _context2.abrupt("return", fetchArchivedMessages(model, options, should_page));
        case 23:
          createPlaceholder(model, options, result);
        case 24:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _fetchArchivedMessages.apply(this, arguments);
}
function createPlaceholder(_x7, _x8, _x9) {
  return _createPlaceholder.apply(this, arguments);
}
/**
 * Fetches messages that might have been archived *after*
 * the last archived message in our local cache.
 * @param { _converse.ChatBox | _converse.ChatRoom }
 */
function _createPlaceholder() {
  _createPlaceholder = mam_utils_asyncToGenerator( /*#__PURE__*/mam_utils_regeneratorRuntime().mark(function _callee3(model, options, result) {
    var msgs, rsm, key, adjacent_message, msg_data;
    return mam_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (!(options.before == '' && (model.messages.length === 0 || !options.start))) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return");
        case 2:
          if (!(options.before && !options.start)) {
            _context3.next = 4;
            break;
          }
          return _context3.abrupt("return");
        case 4:
          if (!(options.before == null)) {
            _context3.next = 6;
            break;
          }
          return _context3.abrupt("return");
        case 6:
          _context3.next = 8;
          return Promise.all(result.messages);
        case 8:
          msgs = _context3.sent;
          rsm = result.rsm;
          key = "stanza_id ".concat(model.get('jid'));
          adjacent_message = msgs.find(function (m) {
            return m[key] === rsm.result.first;
          });
          msg_data = {
            'template_hook': 'getMessageTemplate',
            'time': new Date(new Date(adjacent_message['time']) - 1).toISOString(),
            'before': rsm.result.first,
            'start': options.start
          };
          model.messages.add(new MAMPlaceholderMessage(msg_data));
        case 14:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _createPlaceholder.apply(this, arguments);
}
function fetchNewestMessages(model) {
  if (model.disable_mam) {
    return;
  }
  var most_recent_msg = model.getMostRecentMessage();

  // if clear_messages_on_reconnection is true, than any recent messages
  // must have been received *after* connection and we instead must query
  // for earlier messages
  if (most_recent_msg && !shared_api.settings.get('clear_messages_on_reconnection')) {
    var should_page = shared_api.settings.get('mam_request_all_pages');
    if (should_page) {
      var stanza_id = most_recent_msg.get("stanza_id ".concat(model.get('jid')));
      if (stanza_id) {
        fetchArchivedMessages(model, {
          'after': stanza_id
        }, 'forwards');
      } else {
        fetchArchivedMessages(model, {
          'start': most_recent_msg.get('time')
        }, 'forwards');
      }
    } else {
      fetchArchivedMessages(model, {
        'before': '',
        'start': most_recent_msg.get('time')
      });
    }
  } else {
    fetchArchivedMessages(model, {
      'before': ''
    });
  }
}
;// CONCATENATED MODULE: ./src/headless/plugins/mam/index.js
/**
 * @description XEP-0313 Message Archive Management
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





var mam_Strophe = public_converse.env.Strophe;
var mam_NS = mam_Strophe.NS;
public_converse.plugins.add('converse-mam', {
  dependencies: ['converse-disco', 'converse-muc'],
  initialize: function initialize() {
    shared_api.settings.extend({
      archived_messages_page_size: '50',
      mam_request_all_pages: true,
      message_archiving: undefined,
      // Supported values are 'always', 'never', 'roster' (https://xmpp.org/extensions/xep-0313.html#prefs)
      message_archiving_timeout: 20000 // Time (in milliseconds) to wait before aborting MAM request
    });

    Object.assign(shared_api, mam_api);
    // This is mainly done to aid with tests
    Object.assign(shared_converse, {
      onMAMError: onMAMError,
      onMAMPreferences: onMAMPreferences,
      handleMAMResult: handleMAMResult,
      MAMPlaceholderMessage: MAMPlaceholderMessage
    });

    /************************ Event Handlers ************************/
    shared_api.listen.on('addClientFeatures', function () {
      return shared_api.disco.own.features.add(mam_NS.MAM);
    });
    shared_api.listen.on('serviceDiscovered', getMAMPrefsFromFeature);
    shared_api.listen.on('chatRoomViewInitialized', function (view) {
      if (shared_api.settings.get('muc_show_logs_before_join')) {
        preMUCJoinMAMFetch(view.model);
        // If we want to show MAM logs before entering the MUC, we need
        // to be informed once it's clear that this MUC supports MAM.
        view.model.features.on('change:mam_enabled', function () {
          return preMUCJoinMAMFetch(view.model);
        });
      }
    });
    shared_api.listen.on('enteredNewRoom', function (muc) {
      return muc.features.get('mam_enabled') && fetchNewestMessages(muc);
    });
    shared_api.listen.on('chatReconnected', function (chat) {
      if (chat.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
        fetchNewestMessages(chat);
      }
    });
    shared_api.listen.on('afterMessagesFetched', function (chat) {
      if (chat.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
        fetchNewestMessages(chat);
      }
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/ping/utils.js

var ping_utils_converse$env = public_converse.env,
  ping_utils_Strophe = ping_utils_converse$env.Strophe,
  ping_utils_$iq = ping_utils_converse$env.$iq;
var lastStanzaDate;
function utils_onWindowStateChanged(data) {
  data.state === 'visible' && shared_api.ping(null, 5000);
}
function setLastStanzaDate(date) {
  lastStanzaDate = date;
}
function pong(ping) {
  lastStanzaDate = new Date();
  var from = ping.getAttribute('from');
  var id = ping.getAttribute('id');
  var iq = ping_utils_$iq({
    type: 'result',
    to: from,
    id: id
  });
  shared_converse.connection.sendIQ(iq);
  return true;
}
function registerPongHandler() {
  var connection = shared_converse.connection;
  if (connection.disco) {
    shared_api.disco.own.features.add(ping_utils_Strophe.NS.PING);
  }
  return connection.addHandler(pong, ping_utils_Strophe.NS.PING, "iq", "get");
}
function registerPingHandler() {
  shared_converse.connection.addHandler(function () {
    if (shared_api.settings.get('ping_interval') > 0) {
      // Handler on each stanza, saves the received date
      // in order to ping only when needed.
      lastStanzaDate = new Date();
      return true;
    }
  });
}
var intervalId;
function registerHandlers() {
  // Wrapper so that we can spy on registerPingHandler in tests
  registerPongHandler();
  registerPingHandler();
  clearInterval(intervalId);
  intervalId = setInterval(onEverySecond, 1000);
}
function unregisterIntervalHandler() {
  clearInterval(intervalId);
}
function onEverySecond() {
  if (shared_converse.isTestEnv() || !shared_api.connection.authenticated()) {
    return;
  }
  var ping_interval = shared_api.settings.get('ping_interval');
  if (ping_interval > 0) {
    var _lastStanzaDate;
    var now = new Date();
    lastStanzaDate = (_lastStanzaDate = lastStanzaDate) !== null && _lastStanzaDate !== void 0 ? _lastStanzaDate : now;
    if ((now - lastStanzaDate) / 1000 > ping_interval) {
      shared_api.ping();
    }
  }
}
;// CONCATENATED MODULE: ./src/headless/plugins/ping/api.js
function ping_api_typeof(obj) {
  "@babel/helpers - typeof";

  return ping_api_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;
  }, ping_api_typeof(obj);
}
function ping_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  ping_api_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" == ping_api_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 ping_api_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 ping_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        ping_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        ping_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var ping_api_converse$env = public_converse.env,
  ping_api_Strophe = ping_api_converse$env.Strophe,
  ping_api_$iq = ping_api_converse$env.$iq,
  ping_api_u = ping_api_converse$env.u;
/* harmony default export */ const ping_api = ({
  /**
   * Pings the entity represented by the passed in JID by sending an IQ stanza to it.
   * @method api.ping
   * @param { String } [jid] - The JID of the service to ping
   *  If the ping is sent out to the user's bare JID and no response is received it will attempt to reconnect.
   * @param { number } [timeout] - The amount of time in
   *  milliseconds to wait for a response. The default is 10000;
   * @returns { Boolean | null }
   *  Whether the pinged entity responded with a non-error IQ stanza.
   *  If we already know we're not connected, no ping is sent out and `null` is returned.
   */
  ping: function ping(jid, timeout) {
    return ping_api_asyncToGenerator( /*#__PURE__*/ping_api_regeneratorRuntime().mark(function _callee() {
      var iq, result;
      return ping_api_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (shared_api.connection.authenticated()) {
              _context.next = 3;
              break;
            }
            log.warn("Not pinging when we know we're not authenticated");
            return _context.abrupt("return", null);
          case 3:
            // XXX: We could first check here if the server advertised that it supports PING.
            // However, some servers don't advertise while still responding to pings
            // const feature = _converse.disco_entities[_converse.domain].features.findWhere({'var': Strophe.NS.PING});
            setLastStanzaDate(new Date());
            jid = jid || ping_api_Strophe.getDomainFromJid(shared_converse.bare_jid);
            iq = ping_api_$iq({
              'type': 'get',
              'to': jid,
              'id': ping_api_u.getUniqueId('ping')
            }).c('ping', {
              'xmlns': ping_api_Strophe.NS.PING
            });
            _context.next = 8;
            return shared_api.sendIQ(iq, timeout || 10000, false);
          case 8:
            result = _context.sent;
            if (!(result === null)) {
              _context.next = 15;
              break;
            }
            log.warn("Timeout while pinging ".concat(jid));
            if (jid === ping_api_Strophe.getDomainFromJid(shared_converse.bare_jid)) {
              shared_api.connection.reconnect();
            }
            return _context.abrupt("return", false);
          case 15:
            if (!ping_api_u.isErrorStanza(result)) {
              _context.next = 19;
              break;
            }
            log.error("Error while pinging ".concat(jid));
            log.error(result);
            return _context.abrupt("return", false);
          case 19:
            return _context.abrupt("return", true);
          case 20:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/ping/index.js
/**
 * @description
 * Converse.js plugin which add support for application-level pings
 * as specified in XEP-0199 XMPP Ping.
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



var ping_Strophe = public_converse.env.Strophe;
ping_Strophe.addNamespace('PING', "urn:xmpp:ping");
public_converse.plugins.add('converse-ping', {
  initialize: function initialize() {
    shared_api.settings.extend({
      ping_interval: 60 //in seconds
    });

    Object.assign(shared_api, ping_api);
    shared_api.listen.on('connected', registerHandlers);
    shared_api.listen.on('reconnected', registerHandlers);
    shared_api.listen.on('disconnected', unregisterIntervalHandler);
    shared_api.listen.on('windowStateChanged', utils_onWindowStateChanged);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/pubsub.js
function pubsub_typeof(obj) {
  "@babel/helpers - typeof";

  return pubsub_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;
  }, pubsub_typeof(obj);
}
function pubsub_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  pubsub_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" == pubsub_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 pubsub_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 pubsub_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        pubsub_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        pubsub_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @module converse-pubsub
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



var pubsub_converse$env = public_converse.env,
  pubsub_Strophe = pubsub_converse$env.Strophe,
  pubsub_$iq = pubsub_converse$env.$iq;
pubsub_Strophe.addNamespace('PUBSUB_ERROR', pubsub_Strophe.NS.PUBSUB + "#errors");
public_converse.plugins.add('converse-pubsub', {
  dependencies: ["converse-disco"],
  initialize: function initialize() {
    /************************ BEGIN API ************************/
    // We extend the default converse.js API to add methods specific to MUC groupchats.
    Object.assign(shared_converse.api, {
      /**
       * The "pubsub" namespace groups methods relevant to PubSub
       *
       * @namespace _converse.api.pubsub
       * @memberOf _converse.api
       */
      'pubsub': {
        /**
         * Publshes an item to a PubSub node
         *
         * @method _converse.api.pubsub.publish
         * @param { string } jid The JID of the pubsub service where the node resides.
         * @param { string } node The node being published to
         * @param {Strophe.Builder} item The Strophe.Builder representation of the XML element being published
         * @param { object } options An object representing the publisher options
         *      (see https://xmpp.org/extensions/xep-0060.html#publisher-publish-options)
         * @param { boolean } strict_options Indicates whether the publisher
         *      options are a strict requirement or not. If they're NOT
         *      strict, then Converse will publish to the node even if
         *      the publish options precondication cannot be met.
         */
        'publish': function publish(jid, node, item, options) {
          var _arguments = arguments;
          return pubsub_asyncToGenerator( /*#__PURE__*/pubsub_regeneratorRuntime().mark(function _callee() {
            var strict_options, stanza, el;
            return pubsub_regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  strict_options = _arguments.length > 4 && _arguments[4] !== undefined ? _arguments[4] : true;
                  stanza = pubsub_$iq({
                    'from': shared_converse.bare_jid,
                    'type': 'set',
                    'to': jid
                  }).c('pubsub', {
                    'xmlns': pubsub_Strophe.NS.PUBSUB
                  }).c('publish', {
                    'node': node
                  }).cnode(item.tree()).up().up();
                  if (!options) {
                    _context.next = 12;
                    break;
                  }
                  jid = jid || shared_converse.bare_jid;
                  _context.next = 6;
                  return shared_api.disco.supports(pubsub_Strophe.NS.PUBSUB + '#publish-options', jid);
                case 6:
                  if (!_context.sent) {
                    _context.next = 11;
                    break;
                  }
                  stanza.c('publish-options').c('x', {
                    'xmlns': pubsub_Strophe.NS.XFORM,
                    'type': 'submit'
                  }).c('field', {
                    'var': 'FORM_TYPE',
                    'type': 'hidden'
                  }).c('value').t("".concat(pubsub_Strophe.NS.PUBSUB, "#publish-options")).up().up();
                  Object.keys(options).forEach(function (k) {
                    return stanza.c('field', {
                      'var': k
                    }).c('value').t(options[k]).up().up();
                  });
                  _context.next = 12;
                  break;
                case 11:
                  log.warn("_converse.api.publish: ".concat(jid, " does not support #publish-options, ") + "so we didn't set them even though they were provided.");
                case 12:
                  _context.prev = 12;
                  _context.next = 15;
                  return shared_api.sendIQ(stanza);
                case 15:
                  _context.next = 28;
                  break;
                case 17:
                  _context.prev = 17;
                  _context.t0 = _context["catch"](12);
                  if (!(_context.t0 instanceof Element && strict_options && _context.t0.querySelector("precondition-not-met[xmlns=\"".concat(pubsub_Strophe.NS.PUBSUB_ERROR, "\"]")))) {
                    _context.next = 27;
                    break;
                  }
                  // The publish-options precondition couldn't be
                  // met. We re-publish but without publish-options.
                  el = stanza.tree();
                  el.querySelector('publish-options').outerHTML = '';
                  log.warn("PubSub: Republishing without publish options. ".concat(el.outerHTML));
                  _context.next = 25;
                  return shared_api.sendIQ(el);
                case 25:
                  _context.next = 28;
                  break;
                case 27:
                  throw _context.t0;
                case 28:
                case "end":
                  return _context.stop();
              }
            }, _callee, null, [[12, 17]]);
          }))();
        }
      }
    });
    /************************ END API ************************/
  }
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/isNumber.js



/** `Object#toString` result references. */
var isNumber_numberTag = '[object Number]';

/**
 * Checks if `value` is classified as a `Number` primitive or object.
 *
 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
 * classified as numbers, use the `_.isFinite` method.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
 * @example
 *
 * _.isNumber(3);
 * // => true
 *
 * _.isNumber(Number.MIN_VALUE);
 * // => true
 *
 * _.isNumber(Infinity);
 * // => true
 *
 * _.isNumber('3');
 * // => false
 */
function isNumber(value) {
  return typeof value == 'number' || lodash_es_isObjectLike(value) && _baseGetTag(value) == isNumber_numberTag;
}
/* harmony default export */ const lodash_es_isNumber = (isNumber);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isNaN.js


/**
 * Checks if `value` is `NaN`.
 *
 * **Note:** This method is based on
 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
 * `undefined` and other non-number values.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 * @example
 *
 * _.isNaN(NaN);
 * // => true
 *
 * _.isNaN(new Number(NaN));
 * // => true
 *
 * isNaN(undefined);
 * // => true
 *
 * _.isNaN(undefined);
 * // => false
 */
function isNaN_isNaN(value) {
  // An `NaN` primitive is the only value that is not equal to itself.
  // Perform the `toStringTag` check first to avoid errors with some
  // ActiveX objects in IE.
  return lodash_es_isNumber(value) && value != +value;
}
/* harmony default export */ const lodash_es_isNaN = (isNaN_isNaN);
;// CONCATENATED MODULE: ./src/headless/plugins/status/status.js
function status_typeof(obj) {
  "@babel/helpers - typeof";

  return status_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;
  }, status_typeof(obj);
}
function status_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  status_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" == status_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 status_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 status_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        status_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        status_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function status_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function status_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, status_toPropertyKey(descriptor.key), descriptor);
  }
}
function status_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) status_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) status_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function status_toPropertyKey(arg) {
  var key = status_toPrimitive(arg, "string");
  return status_typeof(key) === "symbol" ? key : String(key);
}
function status_toPrimitive(input, hint) {
  if (status_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (status_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function status_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) status_setPrototypeOf(subClass, superClass);
}
function status_setPrototypeOf(o, p) {
  status_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return status_setPrototypeOf(o, p);
}
function status_createSuper(Derived) {
  var hasNativeReflectConstruct = status_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = status_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = status_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return status_possibleConstructorReturn(this, result);
  };
}
function status_possibleConstructorReturn(self, call) {
  if (call && (status_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 status_assertThisInitialized(self);
}
function status_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function status_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 status_getPrototypeOf(o) {
  status_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return status_getPrototypeOf(o);
}




var status_converse$env = public_converse.env,
  status_Strophe = status_converse$env.Strophe,
  $pres = status_converse$env.$pres;
var XMPPStatus = /*#__PURE__*/function (_Model) {
  status_inherits(XMPPStatus, _Model);
  var _super = status_createSuper(XMPPStatus);
  function XMPPStatus() {
    status_classCallCheck(this, XMPPStatus);
    return _super.apply(this, arguments);
  }
  status_createClass(XMPPStatus, [{
    key: "defaults",
    value: function defaults() {
      // eslint-disable-line class-methods-use-this
      return {
        "status": shared_api.settings.get("default_state")
      };
    }
  }, {
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.on('change', function (item) {
        if (!lodash_es_isObject(item.changed)) {
          return;
        }
        if ('status' in item.changed || 'status_message' in item.changed) {
          shared_api.user.presence.send(_this.get('status'), null, _this.get('status_message'));
        }
      });
    }
  }, {
    key: "getDisplayName",
    value: function getDisplayName() {
      return this.getFullname() || this.getNickname() || shared_converse.bare_jid;
    }
  }, {
    key: "getNickname",
    value: function getNickname() {
      // eslint-disable-line class-methods-use-this
      return shared_api.settings.get('nickname');
    }
  }, {
    key: "getFullname",
    value: function getFullname() {
      // eslint-disable-line class-methods-use-this
      return ''; // Gets overridden in converse-vcard
    }

    /** Constructs a presence stanza
     * @param { string } [type]
     * @param { string } [to] - The JID to which this presence should be sent
     * @param { string } [status_message]
     */
  }, {
    key: "constructPresence",
    value: function () {
      var _constructPresence = status_asyncToGenerator( /*#__PURE__*/status_regeneratorRuntime().mark(function _callee(type) {
        var to,
          status_message,
          presence,
          xmppstatus,
          nick,
          priority,
          idle,
          idle_seconds,
          idle_since,
          _args = arguments;
        return status_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              to = _args.length > 1 && _args[1] !== undefined ? _args[1] : null;
              status_message = _args.length > 2 ? _args[2] : undefined;
              type = typeof type === 'string' ? type : this.get('status') || shared_api.settings.get("default_state");
              status_message = typeof status_message === 'string' ? status_message : this.get('status_message');
              if (type === 'subscribe') {
                presence = $pres({
                  to: to,
                  type: type
                });
                xmppstatus = shared_converse.xmppstatus;
                nick = xmppstatus.getNickname();
                if (nick) presence.c('nick', {
                  'xmlns': status_Strophe.NS.NICK
                }).t(nick).up();
              } else if (type === 'unavailable' || type === 'probe' || type === 'error' || type === 'unsubscribe' || type === 'unsubscribed' || type === 'subscribed') {
                presence = $pres({
                  to: to,
                  type: type
                });
              } else if (type === 'offline') {
                presence = $pres({
                  to: to,
                  type: 'unavailable'
                });
              } else if (type === 'online') {
                presence = $pres({
                  to: to
                });
              } else {
                presence = $pres({
                  to: to
                }).c('show').t(type).up();
              }
              if (status_message) presence.c('status').t(status_message).up();
              priority = shared_api.settings.get("priority");
              presence.c('priority').t(lodash_es_isNaN(Number(priority)) ? 0 : priority).up();
              idle = shared_converse.idle, idle_seconds = shared_converse.idle_seconds;
              if (idle) {
                idle_since = new Date();
                idle_since.setSeconds(idle_since.getSeconds() - idle_seconds);
                presence.c('idle', {
                  xmlns: status_Strophe.NS.IDLE,
                  since: idle_since.toISOString()
                });
              }

              /**
               * *Hook* which allows plugins to modify a presence stanza
               * @event _converse#constructedPresence
               */
              _context.next = 12;
              return shared_api.hook('constructedPresence', null, presence);
            case 12:
              presence = _context.sent;
              return _context.abrupt("return", presence);
            case 14:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function constructPresence(_x) {
        return _constructPresence.apply(this, arguments);
      }
      return constructPresence;
    }()
  }]);
  return XMPPStatus;
}(Model);

;// CONCATENATED MODULE: ./src/headless/plugins/status/api.js
function status_api_typeof(obj) {
  "@babel/helpers - typeof";

  return status_api_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;
  }, status_api_typeof(obj);
}
function status_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  status_api_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" == status_api_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 status_api_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 status_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        status_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        status_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


/* harmony default export */ const status_api = ({
  /**
   * Set and get the user's chat status, also called their *availability*.
   * @namespace _converse.api.user.status
   * @memberOf _converse.api.user
   */
  status: {
    /**
     * Return the current user's availability status.
     * @async
     * @method _converse.api.user.status.get
     * @example _converse.api.user.status.get();
     */
    get: function get() {
      return status_api_asyncToGenerator( /*#__PURE__*/status_api_regeneratorRuntime().mark(function _callee() {
        return status_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('statusInitialized');
            case 2:
              return _context.abrupt("return", shared_converse.xmppstatus.get('status'));
            case 3:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * The user's status can be set to one of the following values:
     *
     * @async
     * @method _converse.api.user.status.set
     * @param { string } value The user's chat status (e.g. 'away', 'dnd', 'offline', 'online', 'unavailable' or 'xa')
     * @param { string } [message] A custom status message
     *
     * @example _converse.api.user.status.set('dnd');
     * @example _converse.api.user.status.set('dnd', 'In a meeting');
     */
    set: function set(value, message) {
      return status_api_asyncToGenerator( /*#__PURE__*/status_api_regeneratorRuntime().mark(function _callee2() {
        var data;
        return status_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              data = {
                'status': value
              };
              if (Object.keys(STATUS_WEIGHTS).includes(value)) {
                _context2.next = 3;
                break;
              }
              throw new Error('Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1');
            case 3:
              if (typeof message === 'string') {
                data.status_message = message;
              }
              _context2.next = 6;
              return shared_api.waitUntil('statusInitialized');
            case 6:
              shared_converse.xmppstatus.save(data);
            case 7:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    },
    /**
     * Set and retrieve the user's custom status message.
     *
     * @namespace _converse.api.user.status.message
     * @memberOf _converse.api.user.status
     */
    message: {
      /**
       * @async
       * @method _converse.api.user.status.message.get
       * @returns { Promise<string> } The status message
       * @example const message = _converse.api.user.status.message.get()
       */
      get: function get() {
        return status_api_asyncToGenerator( /*#__PURE__*/status_api_regeneratorRuntime().mark(function _callee3() {
          return status_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
            while (1) switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return shared_api.waitUntil('statusInitialized');
              case 2:
                return _context3.abrupt("return", shared_converse.xmppstatus.get('status_message'));
              case 3:
              case "end":
                return _context3.stop();
            }
          }, _callee3);
        }))();
      },
      /**
       * @async
       * @method _converse.api.user.status.message.set
       * @param { string } status The status message
       * @example _converse.api.user.status.message.set('In a meeting');
       */
      set: function set(status) {
        return status_api_asyncToGenerator( /*#__PURE__*/status_api_regeneratorRuntime().mark(function _callee4() {
          return status_api_regeneratorRuntime().wrap(function _callee4$(_context4) {
            while (1) switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return shared_api.waitUntil('statusInitialized');
              case 2:
                shared_converse.xmppstatus.save({
                  status_message: status
                });
              case 3:
              case "end":
                return _context4.stop();
            }
          }, _callee4);
        }))();
      }
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/status/utils.js


var status_utils_converse$env = public_converse.env,
  status_utils_Strophe = status_utils_converse$env.Strophe,
  utils_$build = status_utils_converse$env.$build;
function utils_onStatusInitialized(reconnecting) {
  /**
   * Triggered when the user's own chat status has been initialized.
   * @event _converse#statusInitialized
   * @example _converse.api.listen.on('statusInitialized', status => { ... });
   * @example _converse.api.waitUntil('statusInitialized').then(() => { ... });
   */
  shared_api.trigger('statusInitialized', reconnecting);
}
function initStatus(reconnecting) {
  // If there's no xmppstatus obj, then we were never connected to
  // begin with, so we set reconnecting to false.
  reconnecting = shared_converse.xmppstatus === undefined ? false : reconnecting;
  if (reconnecting) {
    utils_onStatusInitialized(reconnecting);
  } else {
    var id = "converse.xmppstatus-".concat(shared_converse.bare_jid);
    shared_converse.xmppstatus = new shared_converse.XMPPStatus({
      id: id
    });
    initStorage(shared_converse.xmppstatus, id, 'session');
    shared_converse.xmppstatus.fetch({
      'success': function success() {
        return utils_onStatusInitialized(reconnecting);
      },
      'error': function error() {
        return utils_onStatusInitialized(reconnecting);
      },
      'silent': true
    });
  }
}
function onUserActivity() {
  var _converse$connection;
  /* Resets counters and flags relating to CSI and auto_away/auto_xa */
  if (shared_converse.idle_seconds > 0) {
    shared_converse.idle_seconds = 0;
  }
  if (!((_converse$connection = shared_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.authenticated)) {
    // We can't send out any stanzas when there's no authenticated connection.
    // This can happen when the connection reconnects.
    return;
  }
  if (shared_converse.inactive) {
    shared_converse.sendCSI(shared_converse.ACTIVE);
  }
  if (shared_converse.idle) {
    shared_converse.idle = false;
    shared_api.user.presence.send();
  }
  if (shared_converse.auto_changed_status === true) {
    shared_converse.auto_changed_status = false;
    // XXX: we should really remember the original state here, and
    // then set it back to that...
    shared_converse.xmppstatus.set('status', shared_api.settings.get("default_state"));
  }
}
function utils_onEverySecond() {
  var _converse$connection2;
  /* An interval handler running every second.
   * Used for CSI and the auto_away and auto_xa features.
   */
  if (!((_converse$connection2 = shared_converse.connection) !== null && _converse$connection2 !== void 0 && _converse$connection2.authenticated)) {
    // We can't send out any stanzas when there's no authenticated connection.
    // This can happen when the connection reconnects.
    return;
  }
  var stat = shared_converse.xmppstatus.get('status');
  shared_converse.idle_seconds++;
  if (shared_api.settings.get("csi_waiting_time") > 0 && shared_converse.idle_seconds > shared_api.settings.get("csi_waiting_time") && !shared_converse.inactive) {
    shared_converse.sendCSI(shared_converse.INACTIVE);
  }
  if (shared_api.settings.get("idle_presence_timeout") > 0 && shared_converse.idle_seconds > shared_api.settings.get("idle_presence_timeout") && !shared_converse.idle) {
    shared_converse.idle = true;
    shared_api.user.presence.send();
  }
  if (shared_api.settings.get("auto_away") > 0 && shared_converse.idle_seconds > shared_api.settings.get("auto_away") && stat !== 'away' && stat !== 'xa' && stat !== 'dnd') {
    shared_converse.auto_changed_status = true;
    shared_converse.xmppstatus.set('status', 'away');
  } else if (shared_api.settings.get("auto_xa") > 0 && shared_converse.idle_seconds > shared_api.settings.get("auto_xa") && stat !== 'xa' && stat !== 'dnd') {
    shared_converse.auto_changed_status = true;
    shared_converse.xmppstatus.set('status', 'xa');
  }
}

/**
 * Send out a Client State Indication (XEP-0352)
 * @function sendCSI
 * @param { String } stat - The user's chat status
 */
function sendCSI(stat) {
  shared_api.send(utils_$build(stat, {
    xmlns: status_utils_Strophe.NS.CSI
  }));
  shared_converse.inactive = stat === shared_converse.INACTIVE ? true : false;
}

/**
 * Set an interval of one second and register a handler for it.
 * Required for the auto_away, auto_xa and csi_waiting_time features.
 */
function registerIntervalHandler() {
  if (shared_api.settings.get("auto_away") < 1 && shared_api.settings.get("auto_xa") < 1 && shared_api.settings.get("csi_waiting_time") < 1 && shared_api.settings.get("idle_presence_timeout") < 1) {
    // Waiting time of less then one second means features aren't used.
    return;
  }
  shared_converse.idle_seconds = 0;
  shared_converse.auto_changed_status = false; // Was the user's status changed by Converse?

  var unloadevent = shared_converse.unloadevent;
  window.addEventListener('click', shared_converse.onUserActivity);
  window.addEventListener('focus', shared_converse.onUserActivity);
  window.addEventListener('keypress', shared_converse.onUserActivity);
  window.addEventListener('mousemove', shared_converse.onUserActivity);
  window.addEventListener(unloadevent, shared_converse.onUserActivity, {
    'once': true,
    'passive': true
  });
  shared_converse.everySecondTrigger = window.setInterval(shared_converse.onEverySecond, 1000);
}
function addStatusToMUCJoinPresence(_, stanza) {
  var xmppstatus = shared_converse.xmppstatus;
  var status = xmppstatus.get('status');
  if (['away', 'chat', 'dnd', 'xa'].includes(status)) {
    stanza.c('show').t(status).up();
  }
  var status_message = xmppstatus.get('status_message');
  if (status_message) {
    stanza.c('status').t(status_message).up();
  }
  return stanza;
}
;// CONCATENATED MODULE: ./src/headless/plugins/status/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





var plugins_status_Strophe = public_converse.env.Strophe;
plugins_status_Strophe.addNamespace('IDLE', 'urn:xmpp:idle:1');
public_converse.plugins.add('converse-status', {
  initialize: function initialize() {
    shared_api.settings.extend({
      auto_away: 0,
      // Seconds after which user status is set to 'away'
      auto_xa: 0,
      // Seconds after which user status is set to 'xa'
      csi_waiting_time: 0,
      // Support for XEP-0352. Seconds before client is considered idle and CSI is sent out.
      default_state: 'online',
      idle_presence_timeout: 300,
      // Seconds after which an idle presence is sent
      priority: 0
    });
    shared_api.promises.add(['statusInitialized']);
    shared_converse.XMPPStatus = XMPPStatus;
    shared_converse.onUserActivity = onUserActivity;
    shared_converse.onEverySecond = utils_onEverySecond;
    shared_converse.sendCSI = sendCSI;
    shared_converse.registerIntervalHandler = registerIntervalHandler;
    Object.assign(shared_converse.api.user, status_api);
    if (shared_api.settings.get("idle_presence_timeout") > 0) {
      shared_api.listen.on('addClientFeatures', function () {
        return shared_api.disco.own.features.add(plugins_status_Strophe.NS.IDLE);
      });
    }
    shared_api.listen.on('presencesInitialized', function (reconnecting) {
      if (!reconnecting) {
        shared_converse.registerIntervalHandler();
      }
    });
    shared_api.listen.on('clearSession', function () {
      if (shouldClearCache() && shared_converse.xmppstatus) {
        shared_converse.xmppstatus.destroy();
        delete shared_converse.xmppstatus;
        shared_api.promises.add(['statusInitialized']);
      }
    });
    shared_api.listen.on('connected', function () {
      return initStatus(false);
    });
    shared_api.listen.on('reconnected', function () {
      return initStatus(true);
    });
    shared_api.listen.on('constructedMUCPresence', addStatusToMUCJoinPresence);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/filter.js

var RosterFilter = Model.extend({
  initialize: function initialize() {
    this.set({
      'filter_text': '',
      'filter_type': 'contacts',
      'chat_state': 'online'
    });
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/utils.js
function roster_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return roster_utils_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;
  }, roster_utils_typeof(obj);
}
function roster_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  roster_utils_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" == roster_utils_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 roster_utils_toConsumableArray(arr) {
  return roster_utils_arrayWithoutHoles(arr) || roster_utils_iterableToArray(arr) || roster_utils_unsupportedIterableToArray(arr) || roster_utils_nonIterableSpread();
}
function roster_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function roster_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return roster_utils_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 roster_utils_arrayLikeToArray(o, minLen);
}
function roster_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function roster_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return roster_utils_arrayLikeToArray(arr);
}
function roster_utils_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 roster_utils_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 roster_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        roster_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        roster_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}







var utils_$pres = public_converse.env.$pres;
function initRoster() {
  // Initialize the collections that represent the roster contacts and groups
  var roster = shared_converse.roster = new shared_converse.RosterContacts();
  var id = "converse.contacts-".concat(shared_converse.bare_jid);
  initStorage(roster, id);
  var filter = shared_converse.roster_filter = new RosterFilter();
  filter.id = "_converse.rosterfilter-".concat(shared_converse.bare_jid);
  initStorage(filter, filter.id);
  filter.fetch();
  id = "converse-roster-model-".concat(shared_converse.bare_jid);
  roster.data = new Model();
  roster.data.id = id;
  initStorage(roster.data, id);
  roster.data.fetch();
  /**
   * Triggered once the `_converse.RosterContacts`
   * been created, but not yet populated with data.
   * This event is useful when you want to create views for these collections.
   * @event _converse#chatBoxMaximized
   * @example _converse.api.listen.on('rosterInitialized', () => { ... });
   * @example _converse.api.waitUntil('rosterInitialized').then(() => { ... });
   */
  shared_api.trigger('rosterInitialized');
}

/**
 * Fetch all the roster groups, and then the roster contacts.
 * Emit an event after fetching is done in each case.
 * @private
 * @param { Bool } ignore_cache - If set to to true, the local cache
 *      will be ignored it's guaranteed that the XMPP server
 *      will be queried for the roster.
 */
function populateRoster() {
  return _populateRoster.apply(this, arguments);
}
function _populateRoster() {
  _populateRoster = roster_utils_asyncToGenerator( /*#__PURE__*/roster_utils_regeneratorRuntime().mark(function _callee() {
    var ignore_cache,
      _args = arguments;
    return roster_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          ignore_cache = _args.length > 0 && _args[0] !== undefined ? _args[0] : false;
          if (ignore_cache) {
            shared_converse.send_initial_presence = true;
          }
          _context.prev = 2;
          _context.next = 5;
          return shared_converse.roster.fetchRosterContacts();
        case 5:
          shared_api.trigger('rosterContactsFetched');
          _context.next = 11;
          break;
        case 8:
          _context.prev = 8;
          _context.t0 = _context["catch"](2);
          log.error(_context.t0);
        case 11:
          _context.prev = 11;
          shared_converse.send_initial_presence && shared_api.user.presence.send();
          return _context.finish(11);
        case 14:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[2, 8, 11, 14]]);
  }));
  return _populateRoster.apply(this, arguments);
}
function updateUnreadCounter(chatbox) {
  var _converse$roster;
  var contact = (_converse$roster = shared_converse.roster) === null || _converse$roster === void 0 ? void 0 : _converse$roster.get(chatbox.get('jid'));
  contact === null || contact === void 0 ? void 0 : contact.save({
    'num_unread': chatbox.get('num_unread')
  });
}
function registerPresenceHandler() {
  unregisterPresenceHandler();
  shared_converse.presence_ref = shared_converse.connection.addHandler(function (presence) {
    shared_converse.roster.presenceHandler(presence);
    return true;
  }, null, 'presence', null);
}
function unregisterPresenceHandler() {
  if (shared_converse.presence_ref !== undefined) {
    shared_converse.connection.deleteHandler(shared_converse.presence_ref);
    delete shared_converse.presence_ref;
  }
}
function clearPresences() {
  return _clearPresences.apply(this, arguments);
}
/**
 * Roster specific event handler for the clearSession event
 */
function _clearPresences() {
  _clearPresences = roster_utils_asyncToGenerator( /*#__PURE__*/roster_utils_regeneratorRuntime().mark(function _callee2() {
    var _converse$presences;
    return roster_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return (_converse$presences = shared_converse.presences) === null || _converse$presences === void 0 ? void 0 : _converse$presences.clearStore();
        case 2:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _clearPresences.apply(this, arguments);
}
function utils_onClearSession() {
  return roster_utils_onClearSession.apply(this, arguments);
}

/**
 * Roster specific event handler for the presencesInitialized event
 * @param { Boolean } reconnecting
 */
function roster_utils_onClearSession() {
  roster_utils_onClearSession = roster_utils_asyncToGenerator( /*#__PURE__*/roster_utils_regeneratorRuntime().mark(function _callee3() {
    var _converse$roster$data;
    return roster_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return clearPresences();
        case 2:
          if (!shouldClearCache()) {
            _context3.next = 12;
            break;
          }
          if (!shared_converse.rostergroups) {
            _context3.next = 7;
            break;
          }
          _context3.next = 6;
          return shared_converse.rostergroups.clearStore();
        case 6:
          delete shared_converse.rostergroups;
        case 7:
          if (!shared_converse.roster) {
            _context3.next = 12;
            break;
          }
          (_converse$roster$data = shared_converse.roster.data) === null || _converse$roster$data === void 0 ? void 0 : _converse$roster$data.destroy();
          _context3.next = 11;
          return shared_converse.roster.clearStore();
        case 11:
          delete shared_converse.roster;
        case 12:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return roster_utils_onClearSession.apply(this, arguments);
}
function onPresencesInitialized(reconnecting) {
  if (reconnecting) {
    /**
     * Similar to `rosterInitialized`, but instead pertaining to reconnection.
     * This event indicates that the roster and its groups are now again
     * available after Converse.js has reconnected.
     * @event _converse#rosterReadyAfterReconnection
     * @example _converse.api.listen.on('rosterReadyAfterReconnection', () => { ... });
     */
    shared_api.trigger('rosterReadyAfterReconnection');
  } else {
    initRoster();
  }
  shared_converse.roster.onConnected();
  registerPresenceHandler();
  populateRoster(!shared_converse.connection.restored);
}

/**
 * Roster specific event handler for the statusInitialized event
 * @param { Boolean } reconnecting
 */
function roster_utils_onStatusInitialized(_x) {
  return _onStatusInitialized.apply(this, arguments);
}

/**
 * Roster specific event handler for the chatBoxesInitialized event
 */
function _onStatusInitialized() {
  _onStatusInitialized = roster_utils_asyncToGenerator( /*#__PURE__*/roster_utils_regeneratorRuntime().mark(function _callee4(reconnecting) {
    var id;
    return roster_utils_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          if (!reconnecting) {
            _context4.next = 7;
            break;
          }
          _context4.t0 = !shared_converse.connection.hasResumed();
          if (!_context4.t0) {
            _context4.next = 5;
            break;
          }
          _context4.next = 5;
          return clearPresences();
        case 5:
          _context4.next = 11;
          break;
        case 7:
          shared_converse.presences = new shared_converse.Presences();
          id = "converse.presences-".concat(shared_converse.bare_jid);
          initStorage(shared_converse.presences, id, 'session');
          // We might be continuing an existing session, so we fetch
          // cached presence data.
          shared_converse.presences.fetch();
        case 11:
          /**
           * Triggered once the _converse.Presences collection has been
           * initialized and its cached data fetched.
           * Returns a boolean indicating whether this event has fired due to
           * Converse having reconnected.
           * @event _converse#presencesInitialized
           * @type { bool }
           * @example _converse.api.listen.on('presencesInitialized', reconnecting => { ... });
           */
          shared_api.trigger('presencesInitialized', reconnecting);
        case 12:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _onStatusInitialized.apply(this, arguments);
}
function onChatBoxesInitialized() {
  shared_converse.chatboxes.on('change:num_unread', updateUnreadCounter);
  shared_converse.chatboxes.on('add', function (chatbox) {
    if (chatbox.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
      chatbox.setRosterContact(chatbox.get('jid'));
    }
  });
}

/**
 * Roster specific handler for the rosterContactsFetched promise
 */
function onRosterContactsFetched() {
  shared_converse.roster.on('add', function (contact) {
    // When a new contact is added, check if we already have a
    // chatbox open for it, and if so attach it to the chatbox.
    var chatbox = shared_converse.chatboxes.findWhere({
      'jid': contact.get('jid')
    });
    chatbox === null || chatbox === void 0 ? void 0 : chatbox.setRosterContact(contact.get('jid'));
  });
}

/**
 * Reject or cancel another user's subscription to our presence updates.
 * @function rejectPresenceSubscription
 * @param { String } jid - The Jabber ID of the user whose subscription is being canceled
 * @param { String } message - An optional message to the user
 */
function rejectPresenceSubscription(jid, message) {
  var pres = utils_$pres({
    to: jid,
    type: "unsubscribed"
  });
  if (message && message !== "") {
    pres.c("status").t(message);
  }
  shared_api.send(pres);
}
function contactsComparator(contact1, contact2) {
  var status1 = contact1.presence.get('show') || 'offline';
  var status2 = contact2.presence.get('show') || 'offline';
  if (STATUS_WEIGHTS[status1] === STATUS_WEIGHTS[status2]) {
    var name1 = contact1.getDisplayName().toLowerCase();
    var name2 = contact2.getDisplayName().toLowerCase();
    return name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
  } else {
    return STATUS_WEIGHTS[status1] < STATUS_WEIGHTS[status2] ? -1 : 1;
  }
}
function groupsComparator(a, b) {
  var HEADER_WEIGHTS = {};
  HEADER_WEIGHTS[shared_converse.HEADER_UNREAD] = 0;
  HEADER_WEIGHTS[shared_converse.HEADER_REQUESTING_CONTACTS] = 1;
  HEADER_WEIGHTS[shared_converse.HEADER_CURRENT_CONTACTS] = 2;
  HEADER_WEIGHTS[shared_converse.HEADER_UNGROUPED] = 3;
  HEADER_WEIGHTS[shared_converse.HEADER_PENDING_CONTACTS] = 4;
  var WEIGHTS = HEADER_WEIGHTS;
  var special_groups = Object.keys(HEADER_WEIGHTS);
  var a_is_special = special_groups.includes(a);
  var b_is_special = special_groups.includes(b);
  if (!a_is_special && !b_is_special) {
    return a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0;
  } else if (a_is_special && b_is_special) {
    return WEIGHTS[a] < WEIGHTS[b] ? -1 : WEIGHTS[a] > WEIGHTS[b] ? 1 : 0;
  } else if (!a_is_special && b_is_special) {
    var a_header = shared_converse.HEADER_CURRENT_CONTACTS;
    return WEIGHTS[a_header] < WEIGHTS[b] ? -1 : WEIGHTS[a_header] > WEIGHTS[b] ? 1 : 0;
  } else if (a_is_special && !b_is_special) {
    var b_header = shared_converse.HEADER_CURRENT_CONTACTS;
    return WEIGHTS[a] < WEIGHTS[b_header] ? -1 : WEIGHTS[a] > WEIGHTS[b_header] ? 1 : 0;
  }
}
function getGroupsAutoCompleteList() {
  var roster = shared_converse.roster;
  var groups = roster.reduce(function (groups, contact) {
    return groups.concat(contact.get('groups'));
  }, []);
  return roster_utils_toConsumableArray(new Set(groups.filter(function (i) {
    return i;
  })));
}
;// CONCATENATED MODULE: ./src/headless/plugins/roster/contact.js
function contact_typeof(obj) {
  "@babel/helpers - typeof";

  return contact_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;
  }, contact_typeof(obj);
}
function contact_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  contact_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" == contact_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 contact_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 contact_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? contact_ownKeys(Object(source), !0).forEach(function (key) {
      contact_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : contact_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function contact_defineProperty(obj, key, value) {
  key = contact_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 contact_toPropertyKey(arg) {
  var key = contact_toPrimitive(arg, "string");
  return contact_typeof(key) === "symbol" ? key : String(key);
}
function contact_toPrimitive(input, hint) {
  if (contact_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (contact_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function contact_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 contact_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        contact_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        contact_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var contact_converse$env = public_converse.env,
  contact_Strophe = contact_converse$env.Strophe,
  contact_$iq = contact_converse$env.$iq,
  contact_$pres = contact_converse$env.$pres;

/**
 * @class
 * @namespace RosterContact
 */
var RosterContact = Model.extend({
  idAttribute: 'jid',
  defaults: {
    'chat_state': undefined,
    'groups': [],
    'image': shared_converse.DEFAULT_IMAGE,
    'image_type': shared_converse.DEFAULT_IMAGE_TYPE,
    'num_unread': 0,
    'status': undefined
  },
  initialize: function initialize(attributes) {
    var _this = this;
    return contact_asyncToGenerator( /*#__PURE__*/contact_regeneratorRuntime().mark(function _callee() {
      var jid;
      return contact_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.initialized = getOpenPromise();
            _this.setPresence();
            jid = attributes.jid;
            _this.set(contact_objectSpread(contact_objectSpread({}, attributes), {
              'jid': contact_Strophe.getBareJidFromJid(jid).toLowerCase(),
              'user_id': contact_Strophe.getNodeFromJid(jid)
            }));
            /**
             * When a contact's presence status has changed.
             * The presence status is either `online`, `offline`, `dnd`, `away` or `xa`.
             * @event _converse#contactPresenceChanged
             * @type { _converse.RosterContact }
             * @example _converse.api.listen.on('contactPresenceChanged', contact => { ... });
             */
            _this.listenTo(_this.presence, 'change:show', function () {
              return shared_api.trigger('contactPresenceChanged', _this);
            });
            _this.listenTo(_this.presence, 'change:show', function () {
              return _this.trigger('presenceChanged');
            });
            /**
             * Synchronous event which provides a hook for further initializing a RosterContact
             * @event _converse#rosterContactInitialized
             * @param { _converse.RosterContact } contact
             */
            _context.next = 8;
            return shared_api.trigger('rosterContactInitialized', _this, {
              'Synchronous': true
            });
          case 8:
            _this.initialized.resolve();
          case 9:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  setPresence: function setPresence() {
    var jid = this.get('jid');
    this.presence = shared_converse.presences.findWhere(jid) || shared_converse.presences.create({
      jid: jid
    });
  },
  openChat: function openChat() {
    var attrs = this.attributes;
    shared_api.chats.open(attrs.jid, attrs, true);
  },
  /**
   * Return a string of tab-separated values that are to be used when
   * matching against filter text.
   *
   * The goal is to be able to filter against the VCard fullname,
   * roster nickname and JID.
   * @returns { String } Lower-cased, tab-separated values
   */
  getFilterCriteria: function getFilterCriteria() {
    var nick = this.get('nickname');
    var jid = this.get('jid');
    var criteria = this.getDisplayName();
    criteria = !criteria.includes(jid) ? criteria.concat("   ".concat(jid)) : criteria;
    criteria = !criteria.includes(nick) ? criteria.concat("   ".concat(nick)) : criteria;
    return criteria.toLowerCase();
  },
  getDisplayName: function getDisplayName() {
    // Gets overridden in converse-vcard where the fullname is may be returned
    if (this.get('nickname')) {
      return this.get('nickname');
    } else {
      return this.get('jid');
    }
  },
  getFullname: function getFullname() {
    // Gets overridden in converse-vcard where the fullname may be returned
    return this.get('jid');
  },
  /**
   * Send a presence subscription request to this roster contact
   * @method _converse.RosterContacts#subscribe
   * @param { String } message - An optional message to explain the
   *      reason for the subscription request.
   */
  subscribe: function subscribe(message) {
    shared_api.user.presence.send('subscribe', this.get('jid'), message);
    this.save('ask', "subscribe"); // ask === 'subscribe' Means we have asked to subscribe to them.
    return this;
  },
  /**
   * Upon receiving the presence stanza of type "subscribed",
   * the user SHOULD acknowledge receipt of that subscription
   * state notification by sending a presence stanza of type
   * "subscribe" to the contact
   * @private
   * @method _converse.RosterContacts#ackSubscribe
   */
  ackSubscribe: function ackSubscribe() {
    shared_api.send(contact_$pres({
      'type': 'subscribe',
      'to': this.get('jid')
    }));
  },
  /**
   * Upon receiving the presence stanza of type "unsubscribed",
   * the user SHOULD acknowledge receipt of that subscription state
   * notification by sending a presence stanza of type "unsubscribe"
   * this step lets the user's server know that it MUST no longer
   * send notification of the subscription state change to the user.
   * @private
   * @method _converse.RosterContacts#ackUnsubscribe
   */
  ackUnsubscribe: function ackUnsubscribe() {
    shared_api.send(contact_$pres({
      'type': 'unsubscribe',
      'to': this.get('jid')
    }));
    this.removeFromRoster();
    this.destroy();
  },
  /**
   * Unauthorize this contact's presence subscription
   * @private
   * @method _converse.RosterContacts#unauthorize
   * @param { String } message - Optional message to send to the person being unauthorized
   */
  unauthorize: function unauthorize(message) {
    rejectPresenceSubscription(this.get('jid'), message);
    return this;
  },
  /**
   * Authorize presence subscription
   * @private
   * @method _converse.RosterContacts#authorize
   * @param { String } message - Optional message to send to the person being authorized
   */
  authorize: function authorize(message) {
    var pres = contact_$pres({
      'to': this.get('jid'),
      'type': "subscribed"
    });
    if (message && message !== "") {
      pres.c("status").t(message);
    }
    shared_api.send(pres);
    return this;
  },
  /**
   * Instruct the XMPP server to remove this contact from our roster
   * @private
   * @method _converse.RosterContacts#
   * @returns { Promise }
   */
  removeFromRoster: function removeFromRoster() {
    var iq = contact_$iq({
      type: 'set'
    }).c('query', {
      xmlns: contact_Strophe.NS.ROSTER
    }).c('item', {
      jid: this.get('jid'),
      subscription: "remove"
    });
    return shared_api.sendIQ(iq);
  }
});
/* harmony default export */ const contact = (RosterContact);
;// CONCATENATED MODULE: ./src/headless/plugins/roster/contacts.js
function contacts_typeof(obj) {
  "@babel/helpers - typeof";

  return contacts_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;
  }, contacts_typeof(obj);
}
function contacts_toConsumableArray(arr) {
  return contacts_arrayWithoutHoles(arr) || contacts_iterableToArray(arr) || contacts_unsupportedIterableToArray(arr) || contacts_nonIterableSpread();
}
function contacts_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function contacts_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return contacts_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 contacts_arrayLikeToArray(o, minLen);
}
function contacts_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function contacts_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return contacts_arrayLikeToArray(arr);
}
function contacts_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 contacts_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  contacts_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" == contacts_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 contacts_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 contacts_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        contacts_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        contacts_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}







var contacts_converse$env = public_converse.env,
  contacts_Strophe = contacts_converse$env.Strophe,
  contacts_$iq = contacts_converse$env.$iq,
  contacts_sizzle = contacts_converse$env.sizzle,
  contacts_u = contacts_converse$env.u;
var RosterContacts = Collection.extend({
  model: contact,
  initialize: function initialize() {
    var id = "roster.state-".concat(shared_converse.bare_jid, "-").concat(this.get('jid'));
    this.state = new Model({
      id: id,
      'collapsed_groups': []
    });
    initStorage(this.state, id);
    this.state.fetch();
  },
  onConnected: function onConnected() {
    // Called as soon as the connection has been established
    // (either after initial login, or after reconnection).
    // Use the opportunity to register stanza handlers.
    this.registerRosterHandler();
    this.registerRosterXHandler();
  },
  registerRosterHandler: function registerRosterHandler() {
    // Register a handler for roster IQ "set" stanzas, which update
    // roster contacts.
    shared_converse.connection.addHandler(function (iq) {
      shared_converse.roster.onRosterPush(iq);
      return true;
    }, contacts_Strophe.NS.ROSTER, 'iq', "set");
  },
  registerRosterXHandler: function registerRosterXHandler() {
    // Register a handler for RosterX message stanzas, which are
    // used to suggest roster contacts to a user.
    var t = 0;
    shared_converse.connection.addHandler(function (msg) {
      window.setTimeout(function () {
        shared_converse.connection.flush();
        shared_converse.roster.subscribeToSuggestedItems.bind(shared_converse.roster)(msg);
      }, t);
      t += msg.querySelectorAll('item').length * 250;
      return true;
    }, contacts_Strophe.NS.ROSTERX, 'message', null);
  },
  /**
   * Fetches the roster contacts, first by trying the browser cache,
   * and if that's empty, then by querying the XMPP server.
   * @returns {promise} Promise which resolves once the contacts have been fetched.
   */
  fetchRosterContacts: function fetchRosterContacts() {
    var _this = this;
    return contacts_asyncToGenerator( /*#__PURE__*/contacts_regeneratorRuntime().mark(function _callee() {
      var result;
      return contacts_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return new Promise(function (resolve, reject) {
              _this.fetch({
                'add': true,
                'silent': true,
                'success': resolve,
                'error': function error(_, e) {
                  return reject(e);
                }
              });
            });
          case 2:
            result = _context.sent;
            if (contacts_u.isErrorObject(result)) {
              log.error(result);
              // Force a full roster refresh
              shared_converse.session.save('roster_cached', false);
              _this.data.save('version', undefined);
            }
            if (!shared_converse.session.get('roster_cached')) {
              _context.next = 8;
              break;
            }
            /**
             * The contacts roster has been retrieved from the local cache (`sessionStorage`).
             * @event _converse#cachedRoster
             * @type { _converse.RosterContacts }
             * @example _converse.api.listen.on('cachedRoster', (items) => { ... });
             * @example _converse.api.waitUntil('cachedRoster').then(items => { ... });
             */
            shared_api.trigger('cachedRoster', result);
            _context.next = 10;
            break;
          case 8:
            shared_converse.send_initial_presence = true;
            return _context.abrupt("return", shared_converse.roster.fetchFromServer());
          case 10:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  subscribeToSuggestedItems: function subscribeToSuggestedItems(msg) {
    Array.from(msg.querySelectorAll('item')).forEach(function (item) {
      if (item.getAttribute('action') === 'add') {
        shared_converse.roster.addAndSubscribe(item.getAttribute('jid'), shared_converse.xmppstatus.getNickname() || shared_converse.xmppstatus.getFullname());
      }
    });
    return true;
  },
  isSelf: function isSelf(jid) {
    return contacts_u.isSameBareJID(jid, shared_converse.connection.jid);
  },
  /**
   * Add a roster contact and then once we have confirmation from
   * the XMPP server we subscribe to that contact's presence updates.
   * @method _converse.RosterContacts#addAndSubscribe
   * @param { String } jid - The Jabber ID of the user being added and subscribed to.
   * @param { String } name - The name of that user
   * @param { Array<String> } groups - Any roster groups the user might belong to
   * @param { String } message - An optional message to explain the reason for the subscription request.
   * @param { Object } attributes - Any additional attributes to be stored on the user's model.
   */
  addAndSubscribe: function addAndSubscribe(jid, name, groups, message, attributes) {
    var _this2 = this;
    return contacts_asyncToGenerator( /*#__PURE__*/contacts_regeneratorRuntime().mark(function _callee2() {
      var contact;
      return contacts_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return _this2.addContactToRoster(jid, name, groups, attributes);
          case 2:
            contact = _context2.sent;
            if (contact instanceof shared_converse.RosterContact) {
              contact.subscribe(message);
            }
          case 4:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  /**
   * Send an IQ stanza to the XMPP server to add a new roster contact.
   * @method _converse.RosterContacts#sendContactAddIQ
   * @param { String } jid - The Jabber ID of the user being added
   * @param { String } name - The name of that user
   * @param { Array<String> } groups - Any roster groups the user might belong to
   */
  sendContactAddIQ: function sendContactAddIQ(jid, name, groups) {
    name = name ? name : null;
    var iq = contacts_$iq({
      'type': 'set'
    }).c('query', {
      'xmlns': contacts_Strophe.NS.ROSTER
    }).c('item', {
      jid: jid,
      name: name
    });
    groups.forEach(function (g) {
      return iq.c('group').t(g).up();
    });
    return shared_api.sendIQ(iq);
  },
  /**
   * Adds a RosterContact instance to _converse.roster and
   * registers the contact on the XMPP server.
   * Returns a promise which is resolved once the XMPP server has responded.
   * @method _converse.RosterContacts#addContactToRoster
   * @param { String } jid - The Jabber ID of the user being added and subscribed to.
   * @param { String } name - The name of that user
   * @param { Array<String> } groups - Any roster groups the user might belong to
   * @param { Object } attributes - Any additional attributes to be stored on the user's model.
   */
  addContactToRoster: function addContactToRoster(jid, name, groups, attributes) {
    var _this3 = this;
    return contacts_asyncToGenerator( /*#__PURE__*/contacts_regeneratorRuntime().mark(function _callee3() {
      var __;
      return contacts_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return shared_api.waitUntil('rosterContactsFetched');
          case 2:
            groups = groups || [];
            _context3.prev = 3;
            _context3.next = 6;
            return _this3.sendContactAddIQ(jid, name, groups);
          case 6:
            _context3.next = 14;
            break;
          case 8:
            _context3.prev = 8;
            _context3.t0 = _context3["catch"](3);
            __ = shared_converse.__;
            log.error(_context3.t0);
            alert(__('Sorry, there was an error while trying to add %1$s as a contact.', name || jid));
            return _context3.abrupt("return", _context3.t0);
          case 14:
            return _context3.abrupt("return", _this3.create(Object.assign({
              'ask': undefined,
              'nickname': name,
              groups: groups,
              jid: jid,
              'requesting': false,
              'subscription': 'none'
            }, attributes), {
              'sort': false
            }));
          case 15:
          case "end":
            return _context3.stop();
        }
      }, _callee3, null, [[3, 8]]);
    }))();
  },
  subscribeBack: function subscribeBack(bare_jid, presence) {
    var _this4 = this;
    return contacts_asyncToGenerator( /*#__PURE__*/contacts_regeneratorRuntime().mark(function _callee4() {
      var contact, _sizzle$pop, nickname, _contact;
      return contacts_regeneratorRuntime().wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            contact = _this4.get(bare_jid);
            if (!(contact instanceof shared_converse.RosterContact)) {
              _context4.next = 5;
              break;
            }
            contact.authorize().subscribe();
            _context4.next = 10;
            break;
          case 5:
            // Can happen when a subscription is retried or roster was deleted
            nickname = ((_sizzle$pop = contacts_sizzle("nick[xmlns=\"".concat(contacts_Strophe.NS.NICK, "\"]"), presence).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent) || null;
            _context4.next = 8;
            return _this4.addContactToRoster(bare_jid, nickname, [], {
              'subscription': 'from'
            });
          case 8:
            _contact = _context4.sent;
            if (_contact instanceof shared_converse.RosterContact) {
              _contact.authorize().subscribe();
            }
          case 10:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }))();
  },
  /**
   * Handle roster updates from the XMPP server.
   * See: https://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push
   * @method _converse.RosterContacts#onRosterPush
   * @param { Element } iq - The IQ stanza received from the XMPP server.
   */
  onRosterPush: function onRosterPush(iq) {
    var id = iq.getAttribute('id');
    var from = iq.getAttribute('from');
    if (from && from !== shared_converse.bare_jid) {
      // https://tools.ietf.org/html/rfc6121#page-15
      //
      // A receiving client MUST ignore the stanza unless it has no 'from'
      // attribute (i.e., implicitly from the bare JID of the user's
      // account) or it has a 'from' attribute whose value matches the
      // user's bare JID <user@domainpart>.
      log.warn("Ignoring roster illegitimate roster push message from ".concat(iq.getAttribute('from')));
      return;
    }
    shared_api.send(contacts_$iq({
      type: 'result',
      id: id,
      from: shared_converse.connection.jid
    }));
    var query = contacts_sizzle("query[xmlns=\"".concat(contacts_Strophe.NS.ROSTER, "\"]"), iq).pop();
    this.data.save('version', query.getAttribute('ver'));
    var items = contacts_sizzle("item", query);
    if (items.length > 1) {
      log.error(iq);
      throw new Error('Roster push query may not contain more than one "item" element.');
    }
    if (items.length === 0) {
      log.warn(iq);
      log.warn('Received a roster push stanza without an "item" element.');
      return;
    }
    this.updateContact(items.pop());
    /**
     * When the roster receives a push event from server (i.e. new entry in your contacts roster).
     * @event _converse#rosterPush
     * @type { Element }
     * @example _converse.api.listen.on('rosterPush', iq => { ... });
     */
    shared_api.trigger('rosterPush', iq);
    return;
  },
  rosterVersioningSupported: function rosterVersioningSupported() {
    return shared_api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver') && this.data.get('version');
  },
  /**
   * Fetch the roster from the XMPP server
   * @emits _converse#roster
   * @returns {promise}
   */
  fetchFromServer: function fetchFromServer() {
    var _this5 = this;
    return contacts_asyncToGenerator( /*#__PURE__*/contacts_regeneratorRuntime().mark(function _callee5() {
      var stanza, iq, query, items, jids;
      return contacts_regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            stanza = contacts_$iq({
              'type': 'get',
              'id': contacts_u.getUniqueId('roster')
            }).c('query', {
              xmlns: contacts_Strophe.NS.ROSTER
            });
            if (_this5.rosterVersioningSupported()) {
              stanza.attrs({
                'ver': _this5.data.get('version')
              });
            }
            _context5.next = 4;
            return shared_api.sendIQ(stanza, null, false);
          case 4:
            iq = _context5.sent;
            if (!(iq.getAttribute('type') === 'result')) {
              _context5.next = 10;
              break;
            }
            query = contacts_sizzle("query[xmlns=\"".concat(contacts_Strophe.NS.ROSTER, "\"]"), iq).pop();
            if (query) {
              items = contacts_sizzle("item", query);
              if (!_this5.data.get('version') && _this5.models.length) {
                // We're getting the full roster, so remove all cached
                // contacts that aren't included in it.
                jids = items.map(function (item) {
                  return item.getAttribute('jid');
                });
                _this5.forEach(function (m) {
                  return !m.get('requesting') && !jids.includes(m.get('jid')) && m.destroy();
                });
              }
              items.forEach(function (item) {
                return _this5.updateContact(item);
              });
              _this5.data.save('version', query.getAttribute('ver'));
            }
            _context5.next = 14;
            break;
          case 10:
            if (contacts_u.isServiceUnavailableError(iq)) {
              _context5.next = 14;
              break;
            }
            // Some unknown error happened, so we will try to fetch again if the page reloads.
            log.error(iq);
            log.error("Error while trying to fetch roster from the server");
            return _context5.abrupt("return");
          case 14:
            shared_converse.session.save('roster_cached', true);
            /**
             * When the roster has been received from the XMPP server.
             * See also the `cachedRoster` event further up, which gets called instead of
             * `roster` if its already in `sessionStorage`.
             * @event _converse#roster
             * @type { Element }
             * @example _converse.api.listen.on('roster', iq => { ... });
             * @example _converse.api.waitUntil('roster').then(iq => { ... });
             */
            shared_api.trigger('roster', iq);
          case 16:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    }))();
  },
  /**
   * Update or create RosterContact models based on the given `item` XML
   * node received in the resulting IQ stanza from the server.
   * @param { Element } item
   */
  updateContact: function updateContact(item) {
    var jid = item.getAttribute('jid');
    var contact = this.get(jid);
    var subscription = item.getAttribute("subscription");
    if (subscription === "remove") {
      return contact === null || contact === void 0 ? void 0 : contact.destroy();
    }
    var ask = item.getAttribute("ask");
    var nickname = item.getAttribute('name');
    var groups = contacts_toConsumableArray(new Set(contacts_sizzle('group', item).map(function (e) {
      return e.textContent;
    })));
    if (contact) {
      // We only find out about requesting contacts via the
      // presence handler, so if we receive a contact
      // here, we know they aren't requesting anymore.
      contact.save({
        subscription: subscription,
        ask: ask,
        nickname: nickname,
        groups: groups,
        'requesting': null
      });
    } else {
      this.create({
        nickname: nickname,
        ask: ask,
        groups: groups,
        jid: jid,
        subscription: subscription
      }, {
        sort: false
      });
    }
  },
  createRequestingContact: function createRequestingContact(presence) {
    var _sizzle$pop2;
    var bare_jid = contacts_Strophe.getBareJidFromJid(presence.getAttribute('from'));
    var nickname = ((_sizzle$pop2 = contacts_sizzle("nick[xmlns=\"".concat(contacts_Strophe.NS.NICK, "\"]"), presence).pop()) === null || _sizzle$pop2 === void 0 ? void 0 : _sizzle$pop2.textContent) || null;
    var user_data = {
      'jid': bare_jid,
      'subscription': 'none',
      'ask': null,
      'requesting': true,
      'nickname': nickname
    };
    /**
     * Triggered when someone has requested to subscribe to your presence (i.e. to be your contact).
     * @event _converse#contactRequest
     * @type { _converse.RosterContact }
     * @example _converse.api.listen.on('contactRequest', contact => { ... });
     */
    shared_api.trigger('contactRequest', this.create(user_data));
  },
  handleIncomingSubscription: function handleIncomingSubscription(presence) {
    var jid = presence.getAttribute('from'),
      bare_jid = contacts_Strophe.getBareJidFromJid(jid),
      contact = this.get(bare_jid);
    if (!shared_api.settings.get('allow_contact_requests')) {
      var __ = shared_converse.__;
      rejectPresenceSubscription(jid, __("This client does not allow presence subscriptions"));
    }
    if (shared_api.settings.get('auto_subscribe')) {
      if (!contact || contact.get('subscription') !== 'to') {
        this.subscribeBack(bare_jid, presence);
      } else {
        contact.authorize();
      }
    } else {
      if (contact) {
        if (contact.get('subscription') !== 'none') {
          contact.authorize();
        } else if (contact.get('ask') === "subscribe") {
          contact.authorize();
        }
      } else {
        this.createRequestingContact(presence);
      }
    }
  },
  handleOwnPresence: function handleOwnPresence(presence) {
    var jid = presence.getAttribute('from'),
      resource = contacts_Strophe.getResourceFromJid(jid),
      presence_type = presence.getAttribute('type');
    if (shared_converse.connection.jid !== jid && presence_type !== 'unavailable' && (shared_api.settings.get('synchronize_availability') === true || shared_api.settings.get('synchronize_availability') === resource)) {
      var _presence$querySelect, _presence$querySelect2;
      // Another resource has changed its status and
      // synchronize_availability option set to update,
      // we'll update ours as well.
      var show = ((_presence$querySelect = presence.querySelector('show')) === null || _presence$querySelect === void 0 ? void 0 : _presence$querySelect.textContent) || 'online';
      shared_converse.xmppstatus.save({
        'status': show
      }, {
        'silent': true
      });
      var status_message = (_presence$querySelect2 = presence.querySelector('status')) === null || _presence$querySelect2 === void 0 ? void 0 : _presence$querySelect2.textContent;
      if (status_message) shared_converse.xmppstatus.save({
        status_message: status_message
      });
    }
    if (shared_converse.jid === jid && presence_type === 'unavailable') {
      // XXX: We've received an "unavailable" presence from our
      // own resource. Apparently this happens due to a
      // Prosody bug, whereby we send an IQ stanza to remove
      // a roster contact, and Prosody then sends
      // "unavailable" globally, instead of directed to the
      // particular user that's removed.
      //
      // Here is the bug report: https://prosody.im/issues/1121
      //
      // I'm not sure whether this might legitimately happen
      // in other cases.
      //
      // As a workaround for now we simply send our presence again,
      // otherwise we're treated as offline.
      shared_api.user.presence.send();
    }
  },
  presenceHandler: function presenceHandler(presence) {
    var presence_type = presence.getAttribute('type');
    if (presence_type === 'error') return true;
    var jid = presence.getAttribute('from');
    var bare_jid = contacts_Strophe.getBareJidFromJid(jid);
    if (this.isSelf(bare_jid)) {
      return this.handleOwnPresence(presence);
    } else if (contacts_sizzle("query[xmlns=\"".concat(contacts_Strophe.NS.MUC, "\"]"), presence).length) {
      return; // Ignore MUC
    }

    var contact = this.get(bare_jid);
    if (contact) {
      var _presence$querySelect3;
      var status = (_presence$querySelect3 = presence.querySelector('status')) === null || _presence$querySelect3 === void 0 ? void 0 : _presence$querySelect3.textContent;
      if (contact.get('status') !== status) contact.save({
        status: status
      });
    }
    if (presence_type === 'subscribed' && contact) {
      contact.ackSubscribe();
    } else if (presence_type === 'unsubscribed' && contact) {
      contact.ackUnsubscribe();
    } else if (presence_type === 'unsubscribe') {
      return;
    } else if (presence_type === 'subscribe') {
      this.handleIncomingSubscription(presence);
    } else if (presence_type === 'unavailable' && contact) {
      var resource = contacts_Strophe.getResourceFromJid(jid);
      contact.presence.removeResource(resource);
    } else if (contact) {
      // presence_type is undefined
      contact.presence.addResource(presence);
    }
  }
});
/* harmony default export */ const contacts = (RosterContacts);
;// CONCATENATED MODULE: ./src/headless/plugins/roster/api.js
function roster_api_typeof(obj) {
  "@babel/helpers - typeof";

  return roster_api_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;
  }, roster_api_typeof(obj);
}
function roster_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  roster_api_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" == roster_api_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 roster_api_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 roster_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        roster_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        roster_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

var roster_api_Strophe = public_converse.env.Strophe;
/* harmony default export */ const roster_api = ({
  /**
   * @namespace _converse.api.contacts
   * @memberOf _converse.api
   */
  contacts: {
    /**
     * This method is used to retrieve roster contacts.
     *
     * @method _converse.api.contacts.get
     * @params {(string[]|string)} jid|jids The JID or JIDs of
     *      the contacts to be returned.
     * @returns {promise} Promise which resolves with the
     *  _converse.RosterContact (or an array of them) representing the contact.
     *
     * @example
     * // Fetch a single contact
     * _converse.api.listen.on('rosterContactsFetched', function () {
     *     const contact = await _converse.api.contacts.get('buddy@example.com')
     *     // ...
     * });
     *
     * @example
     * // To get multiple contacts, pass in an array of JIDs:
     * _converse.api.listen.on('rosterContactsFetched', function () {
     *     const contacts = await _converse.api.contacts.get(
     *         ['buddy1@example.com', 'buddy2@example.com']
     *     )
     *     // ...
     * });
     *
     * @example
     * // To return all contacts, simply call ``get`` without any parameters:
     * _converse.api.listen.on('rosterContactsFetched', function () {
     *     const contacts = await _converse.api.contacts.get();
     *     // ...
     * });
     */
    get: function get(jids) {
      return roster_api_asyncToGenerator( /*#__PURE__*/roster_api_regeneratorRuntime().mark(function _callee() {
        var _getter;
        return roster_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('rosterContactsFetched');
            case 2:
              _getter = function _getter(jid) {
                return shared_converse.roster.get(roster_api_Strophe.getBareJidFromJid(jid));
              };
              if (!(jids === undefined)) {
                _context.next = 7;
                break;
              }
              jids = shared_converse.roster.pluck('jid');
              _context.next = 9;
              break;
            case 7:
              if (!(typeof jids === 'string')) {
                _context.next = 9;
                break;
              }
              return _context.abrupt("return", _getter(jids));
            case 9:
              return _context.abrupt("return", jids.map(_getter));
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * Add a contact.
     *
     * @method _converse.api.contacts.add
     * @param { string } jid The JID of the contact to be added
     * @param { string } [name] A custom name to show the user by in the roster
     * @example
     *     _converse.api.contacts.add('buddy@example.com')
     * @example
     *     _converse.api.contacts.add('buddy@example.com', 'Buddy')
     */
    add: function add(jid, name) {
      return roster_api_asyncToGenerator( /*#__PURE__*/roster_api_regeneratorRuntime().mark(function _callee2() {
        return roster_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return shared_api.waitUntil('rosterContactsFetched');
            case 2:
              if (!(typeof jid !== 'string' || !jid.includes('@'))) {
                _context2.next = 4;
                break;
              }
              throw new TypeError('contacts.add: invalid jid');
            case 4:
              return _context2.abrupt("return", shared_converse.roster.addAndSubscribe(jid, name));
            case 5:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/presence.js





var presence_converse$env = public_converse.env,
  presence_Strophe = presence_converse$env.Strophe,
  presence_dayjs = presence_converse$env.dayjs,
  presence_sizzle = presence_converse$env.sizzle;
var Resource = Model.extend({
  'idAttribute': 'name'
});
var Resources = Collection.extend({
  'model': Resource
});
var Presence = Model.extend({
  idAttribute: 'jid',
  defaults: {
    'show': 'offline'
  },
  initialize: function initialize() {
    this.resources = new Resources();
    var id = "converse.identities-".concat(this.get('jid'));
    initStorage(this.resources, id, 'session');
    this.listenTo(this.resources, 'update', this.onResourcesChanged);
    this.listenTo(this.resources, 'change', this.onResourcesChanged);
  },
  onResourcesChanged: function onResourcesChanged() {
    var _hpr$attributes;
    var hpr = this.getHighestPriorityResource();
    var show = (hpr === null || hpr === void 0 ? void 0 : (_hpr$attributes = hpr.attributes) === null || _hpr$attributes === void 0 ? void 0 : _hpr$attributes.show) || 'offline';
    if (this.get('show') !== show) {
      this.save({
        show: show
      });
    }
  },
  /**
   * Return the resource with the highest priority.
   * If multiple resources have the same priority, take the latest one.
   * @private
   */
  getHighestPriorityResource: function getHighestPriorityResource() {
    return this.resources.sortBy(function (r) {
      return "".concat(r.get('priority'), "-").concat(r.get('timestamp'));
    }).reverse()[0];
  },
  /**
   * Adds a new resource and it's associated attributes as taken
   * from the passed in presence stanza.
   * Also updates the presence if the resource has higher priority (and is newer).
   * @private
   * @param { Element } presence: The presence stanza
   */
  addResource: function addResource(presence) {
    var _presence$querySelect, _presence$querySelect2, _presence$querySelect3;
    var jid = presence.getAttribute('from');
    var name = presence_Strophe.getResourceFromJid(jid);
    var delay = presence_sizzle("delay[xmlns=\"".concat(presence_Strophe.NS.DELAY, "\"]"), presence).pop();
    var priority = (_presence$querySelect = presence.querySelector('priority')) === null || _presence$querySelect === void 0 ? void 0 : _presence$querySelect.textContent;
    var resource = this.resources.get(name);
    var settings = {
      name: name,
      'priority': lodash_es_isNaN(parseInt(priority, 10)) ? 0 : parseInt(priority, 10),
      'show': (_presence$querySelect2 = (_presence$querySelect3 = presence.querySelector('show')) === null || _presence$querySelect3 === void 0 ? void 0 : _presence$querySelect3.textContent) !== null && _presence$querySelect2 !== void 0 ? _presence$querySelect2 : 'online',
      'timestamp': delay ? presence_dayjs(delay.getAttribute('stamp')).toISOString() : new Date().toISOString()
    };
    if (resource) {
      resource.save(settings);
    } else {
      this.resources.create(settings);
    }
  },
  /**
   * Remove the passed in resource from the resources map.
   * Also redetermines the presence given that there's one less
   * resource.
   * @private
   * @param { string } name: The resource name
   */
  removeResource: function removeResource(name) {
    var resource = this.resources.get(name);
    resource === null || resource === void 0 ? void 0 : resource.destroy();
  }
});
var Presences = Collection.extend({
  'model': Presence
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







public_converse.plugins.add('converse-roster', {
  dependencies: ['converse-status'],
  initialize: function initialize() {
    shared_api.settings.extend({
      'allow_contact_requests': true,
      'auto_subscribe': false,
      'synchronize_availability': true
    });
    shared_api.promises.add(['cachedRoster', 'roster', 'rosterContactsFetched', 'rosterInitialized']);

    // API methods only available to plugins
    Object.assign(shared_converse.api, roster_api);
    var __ = shared_converse.__;
    shared_converse.HEADER_CURRENT_CONTACTS = __('My contacts');
    shared_converse.HEADER_PENDING_CONTACTS = __('Pending contacts');
    shared_converse.HEADER_REQUESTING_CONTACTS = __('Contact requests');
    shared_converse.HEADER_UNGROUPED = __('Ungrouped');
    shared_converse.HEADER_UNREAD = __('New messages');
    shared_converse.Presence = Presence;
    shared_converse.Presences = Presences;
    shared_converse.RosterContact = contact;
    shared_converse.RosterContacts = contacts;
    shared_api.listen.on('beforeTearDown', function () {
      return unregisterPresenceHandler();
    });
    shared_api.listen.on('chatBoxesInitialized', onChatBoxesInitialized);
    shared_api.listen.on('clearSession', utils_onClearSession);
    shared_api.listen.on('presencesInitialized', onPresencesInitialized);
    shared_api.listen.on('statusInitialized', roster_utils_onStatusInitialized);
    shared_api.listen.on('streamResumptionFailed', function () {
      return shared_converse.session.set('roster_cached', false);
    });
    shared_api.waitUntil('rosterContactsFetched').then(onRosterContactsFetched);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/smacks/utils.js
function smacks_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return smacks_utils_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;
  }, smacks_utils_typeof(obj);
}
function smacks_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  smacks_utils_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" == smacks_utils_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 smacks_utils_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 smacks_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        smacks_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        smacks_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var smacks_utils_Strophe = public_converse.env.Strophe;
var smacks_utils_u = public_converse.env.utils;
function isStreamManagementSupported() {
  if (shared_api.connection.isType('bosh') && !shared_converse.isTestEnv()) {
    return false;
  }
  return shared_api.disco.stream.getFeature('sm', smacks_utils_Strophe.NS.SM);
}
function handleAck(el) {
  if (!shared_converse.session.get('smacks_enabled')) {
    return true;
  }
  var handled = parseInt(el.getAttribute('h'), 10);
  var last_known_handled = shared_converse.session.get('num_stanzas_handled_by_server');
  var delta = handled - last_known_handled;
  if (delta < 0) {
    var err_msg = "New reported stanza count lower than previous. " + "New: ".concat(handled, " - Previous: ").concat(last_known_handled);
    log.error(err_msg);
  }
  var unacked_stanzas = shared_converse.session.get('unacked_stanzas');
  if (delta > unacked_stanzas.length) {
    var _err_msg = "Higher reported acknowledge count than unacknowledged stanzas. " + "Reported Acknowledged Count: ".concat(delta, " -") + "Unacknowledged Stanza Count: ".concat(unacked_stanzas.length, " -") + "New: ".concat(handled, " - Previous: ").concat(last_known_handled);
    log.error(_err_msg);
  }
  shared_converse.session.save({
    'num_stanzas_handled_by_server': handled,
    'num_stanzas_since_last_ack': 0,
    'unacked_stanzas': unacked_stanzas.slice(delta)
  });
  return true;
}
function sendAck() {
  if (shared_converse.session.get('smacks_enabled')) {
    var h = shared_converse.session.get('num_stanzas_handled');
    var stanza = smacks_utils_u.toStanza("<a xmlns=\"".concat(smacks_utils_Strophe.NS.SM, "\" h=\"").concat(h, "\"/>"));
    shared_api.send(stanza);
  }
  return true;
}
function stanzaHandler(el) {
  if (shared_converse.session.get('smacks_enabled')) {
    if (smacks_utils_u.isTagEqual(el, 'iq') || smacks_utils_u.isTagEqual(el, 'presence') || smacks_utils_u.isTagEqual(el, 'message')) {
      var h = shared_converse.session.get('num_stanzas_handled');
      shared_converse.session.save('num_stanzas_handled', h + 1);
    }
  }
  return true;
}
function initSessionData() {
  shared_converse.session.save({
    'smacks_enabled': shared_converse.session.get('smacks_enabled') || false,
    'num_stanzas_handled': shared_converse.session.get('num_stanzas_handled') || 0,
    'num_stanzas_handled_by_server': shared_converse.session.get('num_stanzas_handled_by_server') || 0,
    'num_stanzas_since_last_ack': shared_converse.session.get('num_stanzas_since_last_ack') || 0,
    'unacked_stanzas': shared_converse.session.get('unacked_stanzas') || []
  });
}
function resetSessionData() {
  var _converse$session;
  (_converse$session = shared_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.save({
    'smacks_enabled': false,
    'num_stanzas_handled': 0,
    'num_stanzas_handled_by_server': 0,
    'num_stanzas_since_last_ack': 0,
    'unacked_stanzas': []
  });
}
function saveSessionData(el) {
  var data = {
    'smacks_enabled': true
  };
  if (['1', 'true'].includes(el.getAttribute('resume'))) {
    data['smacks_stream_id'] = el.getAttribute('id');
  }
  shared_converse.session.save(data);
  return true;
}
function onFailedStanza(el) {
  if (el.querySelector('item-not-found')) {
    // Stream resumption must happen before resource binding but
    // enabling a new stream must happen after resource binding.
    // Since resumption failed, we simply continue.
    //
    // After resource binding, sendEnableStanza will be called
    // based on the afterResourceBinding event.
    log.warn('Could not resume previous SMACKS session, session id not found. ' + 'A new session will be established.');
  } else {
    log.error('Failed to enable stream management');
    log.error(el.outerHTML);
  }
  resetSessionData();
  /**
   * Triggered when the XEP-0198 stream could not be resumed.
   * @event _converse#streamResumptionFailed
   */
  shared_api.trigger('streamResumptionFailed');
  return true;
}
function resendUnackedStanzas() {
  var stanzas = shared_converse.session.get('unacked_stanzas');
  // We clear the unacked_stanzas array because it'll get populated
  // again in `onStanzaSent`
  shared_converse.session.save('unacked_stanzas', []);

  // XXX: Currently we're resending *all* unacked stanzas, including
  // IQ[type="get"] stanzas that longer have handlers (because the
  // page reloaded or we reconnected, causing removal of handlers).
  //
  // *Side-note:* Is it necessary to clear handlers upon reconnection?
  //
  // I've considered not resending those stanzas, but then keeping
  // track of what's been sent and ack'd and their order gets
  // prohibitively complex.
  //
  // It's unclear how much of a problem this poses.
  //
  // Two possible solutions are running @converse/headless as a
  // service worker or handling IQ[type="result"] stanzas
  // differently, more like push stanzas, so that they don't need
  // explicit handlers.
  stanzas.forEach(function (s) {
    return shared_api.send(s);
  });
}
function onResumedStanza(el) {
  saveSessionData(el);
  handleAck(el);
  resendUnackedStanzas();
  shared_converse.connection.do_bind = false; // No need to bind our resource anymore
  shared_converse.connection.authenticated = true;
  shared_converse.connection.restored = true;
  shared_converse.connection._changeConnectStatus(smacks_utils_Strophe.Status.CONNECTED, null);
}
function sendResumeStanza() {
  return _sendResumeStanza.apply(this, arguments);
}
function _sendResumeStanza() {
  _sendResumeStanza = smacks_utils_asyncToGenerator( /*#__PURE__*/smacks_utils_regeneratorRuntime().mark(function _callee() {
    var promise, previous_id, h, stanza;
    return smacks_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          promise = getOpenPromise();
          shared_converse.connection._addSysHandler(function (el) {
            return promise.resolve(onResumedStanza(el));
          }, smacks_utils_Strophe.NS.SM, 'resumed');
          shared_converse.connection._addSysHandler(function (el) {
            return promise.resolve(onFailedStanza(el));
          }, smacks_utils_Strophe.NS.SM, 'failed');
          previous_id = shared_converse.session.get('smacks_stream_id');
          h = shared_converse.session.get('num_stanzas_handled');
          stanza = smacks_utils_u.toStanza("<resume xmlns=\"".concat(smacks_utils_Strophe.NS.SM, "\" h=\"").concat(h, "\" previd=\"").concat(previous_id, "\"/>"));
          shared_api.send(stanza);
          shared_converse.connection.flush();
          _context.next = 10;
          return promise;
        case 10:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _sendResumeStanza.apply(this, arguments);
}
function sendEnableStanza() {
  return _sendEnableStanza.apply(this, arguments);
}
function _sendEnableStanza() {
  _sendEnableStanza = smacks_utils_asyncToGenerator( /*#__PURE__*/smacks_utils_regeneratorRuntime().mark(function _callee2() {
    var promise, resume, stanza;
    return smacks_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(!shared_api.settings.get('enable_smacks') || shared_converse.session.get('smacks_enabled'))) {
            _context2.next = 2;
            break;
          }
          return _context2.abrupt("return");
        case 2:
          _context2.next = 4;
          return isStreamManagementSupported();
        case 4:
          if (!_context2.sent) {
            _context2.next = 14;
            break;
          }
          promise = getOpenPromise();
          shared_converse.connection._addSysHandler(function (el) {
            return promise.resolve(saveSessionData(el));
          }, smacks_utils_Strophe.NS.SM, 'enabled');
          shared_converse.connection._addSysHandler(function (el) {
            return promise.resolve(onFailedStanza(el));
          }, smacks_utils_Strophe.NS.SM, 'failed');
          resume = shared_api.connection.isType('websocket') || shared_converse.isTestEnv();
          stanza = smacks_utils_u.toStanza("<enable xmlns=\"".concat(smacks_utils_Strophe.NS.SM, "\" resume=\"").concat(resume, "\"/>"));
          shared_api.send(stanza);
          shared_converse.connection.flush();
          _context2.next = 14;
          return promise;
        case 14:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _sendEnableStanza.apply(this, arguments);
}
var smacks_handlers = [];
function enableStreamManagement() {
  return _enableStreamManagement.apply(this, arguments);
}
function _enableStreamManagement() {
  _enableStreamManagement = smacks_utils_asyncToGenerator( /*#__PURE__*/smacks_utils_regeneratorRuntime().mark(function _callee3() {
    var _converse$session2;
    var conn;
    return smacks_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (shared_api.settings.get('enable_smacks')) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return");
        case 2:
          _context3.next = 4;
          return isStreamManagementSupported();
        case 4:
          if (_context3.sent) {
            _context3.next = 6;
            break;
          }
          return _context3.abrupt("return");
        case 6:
          conn = shared_converse.connection;
          while (smacks_handlers.length) {
            conn.deleteHandler(smacks_handlers.pop());
          }
          smacks_handlers.push(conn.addHandler(stanzaHandler));
          smacks_handlers.push(conn.addHandler(sendAck, smacks_utils_Strophe.NS.SM, 'r'));
          smacks_handlers.push(conn.addHandler(handleAck, smacks_utils_Strophe.NS.SM, 'a'));
          if (!((_converse$session2 = shared_converse.session) !== null && _converse$session2 !== void 0 && _converse$session2.get('smacks_stream_id'))) {
            _context3.next = 16;
            break;
          }
          _context3.next = 14;
          return sendResumeStanza();
        case 14:
          _context3.next = 17;
          break;
        case 16:
          resetSessionData();
        case 17:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _enableStreamManagement.apply(this, arguments);
}
function onStanzaSent(stanza) {
  if (!shared_converse.session) {
    log.warn('No _converse.session!');
    return;
  }
  if (!shared_converse.session.get('smacks_enabled')) {
    return;
  }
  if (smacks_utils_u.isTagEqual(stanza, 'iq') || smacks_utils_u.isTagEqual(stanza, 'presence') || smacks_utils_u.isTagEqual(stanza, 'message')) {
    var stanza_string = smacks_utils_Strophe.serialize(stanza);
    shared_converse.session.save('unacked_stanzas', (shared_converse.session.get('unacked_stanzas') || []).concat([stanza_string]));
    var max_unacked = shared_api.settings.get('smacks_max_unacked_stanzas');
    if (max_unacked > 0) {
      var num = shared_converse.session.get('num_stanzas_since_last_ack') + 1;
      if (num % max_unacked === 0) {
        // Request confirmation of sent stanzas
        shared_api.send(smacks_utils_u.toStanza("<r xmlns=\"".concat(smacks_utils_Strophe.NS.SM, "\"/>")));
      }
      shared_converse.session.save({
        'num_stanzas_since_last_ack': num
      });
    }
  }
}
;// CONCATENATED MODULE: ./src/headless/plugins/smacks/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse.js plugin which adds support for XEP-0198: Stream Management
 */


var smacks_Strophe = public_converse.env.Strophe;
smacks_Strophe.addNamespace('SM', 'urn:xmpp:sm:3');
public_converse.plugins.add('converse-smacks', {
  initialize: function initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'enable_smacks': true,
      'smacks_max_unacked_stanzas': 5
    });
    shared_api.listen.on('afterResourceBinding', sendEnableStanza);
    shared_api.listen.on('beforeResourceBinding', enableStreamManagement);
    shared_api.listen.on('send', onStanzaSent);
    shared_api.listen.on('userSessionInitialized', initSessionData);
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/vcard.js
function vcard_typeof(obj) {
  "@babel/helpers - typeof";

  return vcard_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;
  }, vcard_typeof(obj);
}



/**
 * Represents a VCard
 * @class
 * @namespace _converse.VCard
 * @memberOf _converse
 */
var VCard = Model.extend({
  idAttribute: 'jid',
  defaults: {
    'image': shared_converse.DEFAULT_IMAGE,
    'image_type': shared_converse.DEFAULT_IMAGE_TYPE
  },
  set: function set(key, val, options) {
    // Override Model.prototype.set to make sure that the
    // default `image` and `image_type` values are maintained.
    var attrs;
    if (vcard_typeof(key) === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }
    if ('image' in attrs && !attrs['image']) {
      attrs['image'] = shared_converse.DEFAULT_IMAGE;
      attrs['image_type'] = shared_converse.DEFAULT_IMAGE_TYPE;
      return Model.prototype.set.call(this, attrs, options);
    } else {
      return Model.prototype.set.apply(this, arguments);
    }
  },
  getDisplayName: function getDisplayName() {
    return this.get('nickname') || this.get('fullname') || this.get('jid');
  }
});
/* harmony default export */ const vcard = (VCard);
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/utils.js
function vcard_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return vcard_utils_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;
  }, vcard_utils_typeof(obj);
}
function vcard_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  vcard_utils_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" == vcard_utils_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 vcard_utils_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 vcard_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        vcard_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        vcard_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}




var vcard_utils_converse$env = public_converse.env,
  vcard_utils_Strophe = vcard_utils_converse$env.Strophe,
  vcard_utils_$iq = vcard_utils_converse$env.$iq,
  vcard_utils_u = vcard_utils_converse$env.u;
function onVCardData(_x, _x2) {
  return _onVCardData.apply(this, arguments);
}
function _onVCardData() {
  _onVCardData = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee(jid, iq) {
    var vcard, result, _vcard$querySelector, _vcard$querySelector2, _vcard$querySelector3, _vcard$querySelector4, _vcard$querySelector5, _vcard$querySelector6, _vcard$querySelector7, buffer, ab;
    return vcard_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          vcard = iq.querySelector('vCard');
          result = {};
          if (vcard !== null) {
            result = {
              'stanza': iq,
              'fullname': (_vcard$querySelector = vcard.querySelector('FN')) === null || _vcard$querySelector === void 0 ? void 0 : _vcard$querySelector.textContent,
              'nickname': (_vcard$querySelector2 = vcard.querySelector('NICKNAME')) === null || _vcard$querySelector2 === void 0 ? void 0 : _vcard$querySelector2.textContent,
              'image': (_vcard$querySelector3 = vcard.querySelector('PHOTO BINVAL')) === null || _vcard$querySelector3 === void 0 ? void 0 : _vcard$querySelector3.textContent,
              'image_type': (_vcard$querySelector4 = vcard.querySelector('PHOTO TYPE')) === null || _vcard$querySelector4 === void 0 ? void 0 : _vcard$querySelector4.textContent,
              'url': (_vcard$querySelector5 = vcard.querySelector('URL')) === null || _vcard$querySelector5 === void 0 ? void 0 : _vcard$querySelector5.textContent,
              'role': (_vcard$querySelector6 = vcard.querySelector('ROLE')) === null || _vcard$querySelector6 === void 0 ? void 0 : _vcard$querySelector6.textContent,
              'email': (_vcard$querySelector7 = vcard.querySelector('EMAIL USERID')) === null || _vcard$querySelector7 === void 0 ? void 0 : _vcard$querySelector7.textContent,
              'vcard_updated': new Date().toISOString(),
              'vcard_error': undefined
            };
          }
          if (!result.image) {
            _context.next = 9;
            break;
          }
          buffer = vcard_utils_u.base64ToArrayBuffer(result['image']);
          _context.next = 7;
          return crypto.subtle.digest('SHA-1', buffer);
        case 7:
          ab = _context.sent;
          result['image_hash'] = vcard_utils_u.arrayBufferToHex(ab);
        case 9:
          return _context.abrupt("return", result);
        case 10:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _onVCardData.apply(this, arguments);
}
function createStanza(type, jid, vcard_el) {
  var iq = vcard_utils_$iq(jid ? {
    'type': type,
    'to': jid
  } : {
    'type': type
  });
  if (!vcard_el) {
    iq.c("vCard", {
      'xmlns': vcard_utils_Strophe.NS.VCARD
    });
  } else {
    iq.cnode(vcard_el);
  }
  return iq;
}
function onOccupantAvatarChanged(occupant) {
  var hash = occupant.get('image_hash');
  var vcards = [];
  if (occupant.get('jid')) {
    vcards.push(shared_converse.vcards.get(occupant.get('jid')));
  }
  vcards.push(shared_converse.vcards.get(occupant.get('from')));
  vcards.forEach(function (v) {
    return hash && (v === null || v === void 0 ? void 0 : v.get('image_hash')) !== hash && shared_api.vcard.update(v, true);
  });
}
function setVCardOnModel(_x3) {
  return _setVCardOnModel.apply(this, arguments);
}
function _setVCardOnModel() {
  _setVCardOnModel = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee2(model) {
    var jid;
    return vcard_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(model instanceof shared_converse.Message)) {
            _context2.next = 6;
            break;
          }
          if (!['error', 'info'].includes(model.get('type'))) {
            _context2.next = 3;
            break;
          }
          return _context2.abrupt("return");
        case 3:
          jid = model.get('from');
          _context2.next = 7;
          break;
        case 6:
          jid = model.get('jid');
        case 7:
          if (jid) {
            _context2.next = 10;
            break;
          }
          log.warn("Could not set VCard on model because no JID found!");
          return _context2.abrupt("return");
        case 10:
          _context2.next = 12;
          return shared_api.waitUntil('VCardsInitialized');
        case 12:
          model.vcard = shared_converse.vcards.get(jid) || shared_converse.vcards.create({
            jid: jid
          });
          model.vcard.on('change', function () {
            return model.trigger('vcard:change');
          });
          model.trigger('vcard:add');
        case 15:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _setVCardOnModel.apply(this, arguments);
}
function getVCardForOccupant(occupant) {
  var _occupant$collection;
  var muc = occupant === null || occupant === void 0 ? void 0 : (_occupant$collection = occupant.collection) === null || _occupant$collection === void 0 ? void 0 : _occupant$collection.chatroom;
  var nick = occupant.get('nick');
  if (nick && (muc === null || muc === void 0 ? void 0 : muc.get('nick')) === nick) {
    return shared_converse.xmppstatus.vcard;
  } else {
    var jid = occupant.get('jid') || occupant.get('from');
    if (jid) {
      return shared_converse.vcards.get(jid) || shared_converse.vcards.create({
        jid: jid
      });
    } else {
      log.warn("Could not get VCard for occupant because no JID found!");
      return;
    }
  }
}
function setVCardOnOccupant(_x4) {
  return _setVCardOnOccupant.apply(this, arguments);
}
function _setVCardOnOccupant() {
  _setVCardOnOccupant = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee3(occupant) {
    return vcard_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return shared_api.waitUntil('VCardsInitialized');
        case 2:
          occupant.vcard = getVCardForOccupant(occupant);
          if (occupant.vcard) {
            occupant.vcard.on('change', function () {
              return occupant.trigger('vcard:change');
            });
            occupant.trigger('vcard:add');
          }
        case 4:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _setVCardOnOccupant.apply(this, arguments);
}
function getVCardForMUCMessage(message) {
  var _message$collection;
  var muc = message === null || message === void 0 ? void 0 : (_message$collection = message.collection) === null || _message$collection === void 0 ? void 0 : _message$collection.chatbox;
  var nick = vcard_utils_Strophe.getResourceFromJid(message.get('from'));
  if (nick && (muc === null || muc === void 0 ? void 0 : muc.get('nick')) === nick) {
    return shared_converse.xmppstatus.vcard;
  } else {
    var _message$occupant;
    var jid = ((_message$occupant = message.occupant) === null || _message$occupant === void 0 ? void 0 : _message$occupant.get('jid')) || message.get('from');
    if (jid) {
      return shared_converse.vcards.get(jid) || shared_converse.vcards.create({
        jid: jid
      });
    } else {
      log.warn("Could not get VCard for message because no JID found! msgid: ".concat(message.get('msgid')));
      return;
    }
  }
}
function setVCardOnMUCMessage(_x5) {
  return _setVCardOnMUCMessage.apply(this, arguments);
}
function _setVCardOnMUCMessage() {
  _setVCardOnMUCMessage = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee4(message) {
    return vcard_utils_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          if (!['error', 'info'].includes(message.get('type'))) {
            _context4.next = 4;
            break;
          }
          return _context4.abrupt("return");
        case 4:
          _context4.next = 6;
          return shared_api.waitUntil('VCardsInitialized');
        case 6:
          message.vcard = getVCardForMUCMessage(message);
          if (message.vcard) {
            message.vcard.on('change', function () {
              return message.trigger('vcard:change');
            });
            message.trigger('vcard:add');
          }
        case 8:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _setVCardOnMUCMessage.apply(this, arguments);
}
function initVCardCollection() {
  return _initVCardCollection.apply(this, arguments);
}
function _initVCardCollection() {
  _initVCardCollection = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee5() {
    var id, vcards, jid, status;
    return vcard_utils_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          shared_converse.vcards = new shared_converse.VCards();
          id = "".concat(shared_converse.bare_jid, "-converse.vcards");
          initStorage(shared_converse.vcards, id);
          _context5.next = 5;
          return new Promise(function (resolve) {
            shared_converse.vcards.fetch({
              'success': resolve,
              'error': resolve
            }, {
              'silent': true
            });
          });
        case 5:
          vcards = shared_converse.vcards;
          if (shared_converse.session) {
            jid = shared_converse.session.get('bare_jid');
            status = shared_converse.xmppstatus;
            status.vcard = vcards.get(jid) || vcards.create({
              'jid': jid
            });
            if (status.vcard) {
              status.vcard.on('change', function () {
                return status.trigger('vcard:change');
              });
              status.trigger('vcard:add');
            }
          }
          /**
           * Triggered as soon as the `_converse.vcards` collection has been initialized and populated from cache.
           * @event _converse#VCardsInitialized
           */
          shared_api.trigger('VCardsInitialized');
        case 8:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
  return _initVCardCollection.apply(this, arguments);
}
function clearVCardsSession() {
  if (shouldClearCache()) {
    shared_api.promises.add('VCardsInitialized');
    if (shared_converse.vcards) {
      shared_converse.vcards.clearStore();
      delete shared_converse.vcards;
    }
  }
}
function getVCard(_x6) {
  return _getVCard.apply(this, arguments);
}
function _getVCard() {
  _getVCard = vcard_utils_asyncToGenerator( /*#__PURE__*/vcard_utils_regeneratorRuntime().mark(function _callee6(jid) {
    var to, iq;
    return vcard_utils_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          to = vcard_utils_Strophe.getBareJidFromJid(jid) === shared_converse.bare_jid ? null : jid;
          _context6.prev = 1;
          _context6.next = 4;
          return shared_api.sendIQ(createStanza("get", to));
        case 4:
          iq = _context6.sent;
          _context6.next = 10;
          break;
        case 7:
          _context6.prev = 7;
          _context6.t0 = _context6["catch"](1);
          return _context6.abrupt("return", {
            jid: jid,
            'stanza': _context6.t0,
            'vcard_error': new Date().toISOString()
          });
        case 10:
          return _context6.abrupt("return", onVCardData(jid, iq));
        case 11:
        case "end":
          return _context6.stop();
      }
    }, _callee6, null, [[1, 7]]);
  }));
  return _getVCard.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/api.js
function vcard_api_typeof(obj) {
  "@babel/helpers - typeof";

  return vcard_api_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;
  }, vcard_api_typeof(obj);
}
function vcard_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  vcard_api_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" == vcard_api_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 vcard_api_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 vcard_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        vcard_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        vcard_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var vcard_api_converse$env = public_converse.env,
  api_dayjs = vcard_api_converse$env.dayjs,
  vcard_api_u = vcard_api_converse$env.u;
/* harmony default export */ const vcard_api = ({
  /**
   * The XEP-0054 VCard API
   *
   * This API lets you access and update user VCards
   *
   * @namespace _converse.api.vcard
   * @memberOf _converse.api
   */
  vcard: {
    /**
     * Enables setting new values for a VCard.
     *
     * Sends out an IQ stanza to set the user's VCard and if
     * successful, it updates the {@link _converse.VCard}
     * for the passed in JID.
     *
     * @method _converse.api.vcard.set
     * @param { string } jid The JID for which the VCard should be set
     * @param { object } data A map of VCard keys and values
     * @example
     * let jid = _converse.bare_jid;
     * _converse.api.vcard.set( jid, {
     *     'fn': 'John Doe',
     *     'nickname': 'jdoe'
     * }).then(() => {
     *     // Succes
     * }).catch((e) => {
     *     // Failure, e is your error object
     * }).
     */
    set: function set(jid, data) {
      return vcard_api_asyncToGenerator( /*#__PURE__*/vcard_api_regeneratorRuntime().mark(function _callee() {
        var div, vcard_el, result;
        return vcard_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (jid) {
                _context.next = 2;
                break;
              }
              throw Error("No jid provided for the VCard data");
            case 2:
              div = document.createElement('div');
              vcard_el = vcard_api_u.toStanza("\n                <vCard xmlns=\"vcard-temp\">\n                    <FN>".concat(data.fn, "</FN>\n                    <NICKNAME>").concat(data.nickname, "</NICKNAME>\n                    <URL>").concat(data.url, "</URL>\n                    <ROLE>").concat(data.role, "</ROLE>\n                    <EMAIL><INTERNET/><PREF/><USERID>").concat(data.email, "</USERID></EMAIL>\n                    <PHOTO>\n                        <TYPE>").concat(data.image_type, "</TYPE>\n                        <BINVAL>").concat(data.image, "</BINVAL>\n                    </PHOTO>\n                </vCard>"), div);
              _context.prev = 4;
              _context.next = 7;
              return shared_api.sendIQ(createStanza("set", jid, vcard_el));
            case 7:
              result = _context.sent;
              _context.next = 13;
              break;
            case 10:
              _context.prev = 10;
              _context.t0 = _context["catch"](4);
              throw _context.t0;
            case 13:
              _context.next = 15;
              return shared_api.vcard.update(jid, true);
            case 15:
              return _context.abrupt("return", result);
            case 16:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[4, 10]]);
      }))();
    },
    /**
     * @method _converse.api.vcard.get
     * @param {Model|string} model Either a `Model` instance, or a string JID.
     *     If a `Model` instance is passed in, then it must have either a `jid`
     *     attribute or a `muc_jid` attribute.
     * @param { boolean } [force] A boolean indicating whether the vcard should be
     *     fetched from the server even if it's been fetched before.
     * @returns {promise} A Promise which resolves with the VCard data for a particular JID or for
     *     a `Model` instance which represents an entity with a JID (such as a roster contact,
     *     chat or chatroom occupant).
     *
     * @example
     * const { api } = _converse;
     * api.waitUntil('rosterContactsFetched').then(() => {
     *     api.vcard.get('someone@example.org').then(
     *         (vcard) => {
     *             // Do something with the vcard...
     *         }
     *     );
     * });
     */
    get: function get(model, force) {
      if (typeof model === 'string') {
        return getVCard(model);
      }
      var error_date = model.get('vcard_error');
      var already_tried_today = error_date && api_dayjs(error_date).isSame(new Date(), "day");
      if (force || !model.get('vcard_updated') && !already_tried_today) {
        var jid = model.get('jid');
        if (!jid) {
          log.error("No JID to get vcard for");
        }
        return getVCard(jid);
      } else {
        return Promise.resolve({});
      }
    },
    /**
     * Fetches the VCard associated with a particular `Model` instance
     * (by using its `jid` or `muc_jid` attribute) and then updates the model with the
     * returned VCard data.
     *
     * @method _converse.api.vcard.update
     * @param { Model } model A `Model` instance
     * @param { boolean } [force] A boolean indicating whether the vcard should be
     *     fetched again even if it's been fetched before.
     * @returns {promise} A promise which resolves once the update has completed.
     * @example
     * const { api } = _converse;
     * api.waitUntil('rosterContactsFetched').then(async () => {
     *     const chatbox = await api.chats.get('someone@example.org');
     *     api.vcard.update(chatbox);
     * });
     */
    update: function update(model, force) {
      var _this = this;
      return vcard_api_asyncToGenerator( /*#__PURE__*/vcard_api_regeneratorRuntime().mark(function _callee2() {
        var data;
        return vcard_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return _this.get(model, force);
            case 2:
              data = _context2.sent;
              model = typeof model === 'string' ? shared_converse.vcards.get(model) : model;
              if (model) {
                _context2.next = 7;
                break;
              }
              log.error("Could not find a VCard model for ".concat(model));
              return _context2.abrupt("return");
            case 7:
              if (Object.keys(data).length) {
                delete data['stanza'];
                model.save(data);
              }
            case 8:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    }
  }
});
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






var vcard_Strophe = public_converse.env.Strophe;
public_converse.plugins.add('converse-vcard', {
  dependencies: ["converse-status", "converse-roster"],
  // Overrides mentioned here will be picked up by converse.js's
  // plugin architecture they will replace existing methods on the
  // relevant objects or classes.
  // New functions which don't exist yet can also be added.
  overrides: {
    XMPPStatus: {
      getNickname: function getNickname() {
        var _converse = this.__super__._converse;
        var nick = this.__super__.getNickname.apply(this);
        if (!nick && _converse.xmppstatus.vcard) {
          return _converse.xmppstatus.vcard.get('nickname');
        } else {
          return nick;
        }
      },
      getFullname: function getFullname() {
        var _converse = this.__super__._converse;
        var fullname = this.__super__.getFullname.apply(this);
        if (!fullname && _converse.xmppstatus.vcard) {
          return _converse.xmppstatus.vcard.get('fullname');
        } else {
          return fullname;
        }
      }
    },
    RosterContact: {
      getDisplayName: function getDisplayName() {
        if (!this.get('nickname') && this.vcard) {
          return this.vcard.getDisplayName();
        } else {
          return this.__super__.getDisplayName.apply(this);
        }
      },
      getFullname: function getFullname() {
        if (this.vcard) {
          return this.vcard.get('fullname');
        } else {
          return this.__super__.getFullname.apply(this);
        }
      }
    }
  },
  initialize: function initialize() {
    shared_api.promises.add('VCardsInitialized');
    shared_converse.VCard = vcard;
    shared_converse.VCards = Collection.extend({
      model: shared_converse.VCard,
      initialize: function initialize() {
        this.on('add', function (v) {
          return v.get('jid') && shared_api.vcard.update(v);
        });
      }
    });
    shared_api.listen.on('chatRoomInitialized', function (m) {
      setVCardOnModel(m);
      m.occupants.forEach(setVCardOnOccupant);
      m.listenTo(m.occupants, 'add', setVCardOnOccupant);
      m.listenTo(m.occupants, 'change:image_hash', function (o) {
        return onOccupantAvatarChanged(o);
      });
    });
    shared_api.listen.on('chatBoxInitialized', function (m) {
      return setVCardOnModel(m);
    });
    shared_api.listen.on('chatRoomMessageInitialized', function (m) {
      return setVCardOnMUCMessage(m);
    });
    shared_api.listen.on('addClientFeatures', function () {
      return shared_api.disco.own.features.add(vcard_Strophe.NS.VCARD);
    });
    shared_api.listen.on('clearSession', function () {
      return clearVCardsSession();
    });
    shared_api.listen.on('messageInitialized', function (m) {
      return setVCardOnModel(m);
    });
    shared_api.listen.on('rosterContactInitialized', function (m) {
      return setVCardOnModel(m);
    });
    shared_api.listen.on('statusInitialized', initVCardCollection);
    Object.assign(shared_converse.api, vcard_api);
  }
});
;// CONCATENATED MODULE: ./src/headless/index.js
/* START: Removable components
 * --------------------
 * Any of the following components may be removed if they're not needed.
 */
 // XEP-0199 XMPP Ping
 // XEP-0206 BOSH
 // XEP-0115 Entity Capabilities
 // RFC-6121 Instant messaging

 // XEP-0030 Service discovery
 // XEP-0050 Ad Hoc Commands
 // Support for headline messages
 // XEP-0313 Message Archive Management
 // XEP-0045 Multi-user chat
 // XEP-0199 XMPP Ping
 // XEP-0060 Pubsub
 // RFC-6121 Contacts Roster
 // XEP-0198 Stream Management

 // XEP-0054 VCard-temp
/* END: Removable components */


/* harmony default export */ const headless = ((/* unused pure expression or super */ null && (converse)));
;// CONCATENATED MODULE: external "jed"
const external_jed_namespaceObject = jed;
var external_jed_default = /*#__PURE__*/__webpack_require__.n(external_jed_namespaceObject);
;// CONCATENATED MODULE: ./src/i18n/index.js
function i18n_typeof(obj) {
  "@babel/helpers - typeof";

  return i18n_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;
  }, i18n_typeof(obj);
}
function i18n_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  i18n_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" == i18n_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 i18n_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 i18n_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        i18n_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        i18n_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @module i18n
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the internationalization module
 */



var i18n_dayjs = public_converse.env.dayjs;
var jed_instance;

/**
 * @private
 * @param { string } locale
 * @param { string[] } supported_locales
 */
function isConverseLocale(locale, supported_locales) {
  return typeof locale === 'string' && supported_locales.includes(locale);
}

/**
 * Determines which locale is supported by the user's system as well
 * as by the relevant library (e.g. converse.js or dayjs).
 * @private
 * @param { string } preferred_locale
 * @param { Function } isSupportedByLibrary - Returns a boolean indicating whether
 *   the locale is supported.
 * @returns { string }
 */
function _getLocale(preferred_locale, isSupportedByLibrary) {
  if (preferred_locale === 'en' || isSupportedByLibrary(preferred_locale)) {
    return preferred_locale;
  }
  var languages = window.navigator.languages;
  var locale;
  for (var i = 0; i < languages.length && !locale; i++) {
    locale = isLocaleAvailable(languages[i], isSupportedByLibrary);
  }
  return locale || 'en';
}

/**
 * Check whether the locale or sub locale (e.g. en-US, en) is supported.
 * @private
 * @param { String } locale - The locale to check for
 * @param { Function } available - Returns a boolean indicating whether the locale is supported
 */
function isLocaleAvailable(locale, available) {
  if (available(locale)) {
    return locale;
  } else {
    var sublocale = locale.split('-')[0];
    if (sublocale !== locale && available(sublocale)) {
      return sublocale;
    }
  }
}

/**
 * Given a locale, return the closest locale returned by dayJS
 * @private
 * @param { string } locale
 */
function getDayJSLocale(locale) {
  var dayjs_locale = locale.toLowerCase().replace('_', '-');
  return dayjs_locale === 'ug' ? 'ug-cn' : dayjs_locale;
}

/**
 * Fetch the translations for the given local at the given URL.
 * @private
 * @returns { Jed }
 */
function fetchTranslations() {
  return _fetchTranslations.apply(this, arguments);
}
/**
 * @namespace i18n
 */
function _fetchTranslations() {
  _fetchTranslations = i18n_asyncToGenerator( /*#__PURE__*/i18n_regeneratorRuntime().mark(function _callee2() {
    var api, locale, dayjs_locale, _yield$import, data;
    return i18n_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          api = shared_converse.api, locale = shared_converse.locale;
          dayjs_locale = getDayJSLocale(locale);
          if (!(!isConverseLocale(locale, api.settings.get('locales')) || locale === 'en')) {
            _context2.next = 4;
            break;
          }
          return _context2.abrupt("return");
        case 4:
          _context2.next = 6;
          return __webpack_require__(7521)("./".concat(locale, "/LC_MESSAGES/converse.po"));
        case 6:
          _yield$import = _context2.sent;
          data = _yield$import.default;
          _context2.next = 10;
          return __webpack_require__(3683)("./".concat(dayjs_locale, ".js"));
        case 10:
          i18n_dayjs.locale(_getLocale(dayjs_locale, function (l) {
            return i18n_dayjs.locale(l);
          }));
          return _context2.abrupt("return", new (external_jed_default())(data));
        case 12:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _fetchTranslations.apply(this, arguments);
}
Object.assign(i18n, {
  /**
   * @param { string } preferred_locale
   * @param { string[] } available_locales
   */
  getLocale: function getLocale(preferred_locale, available_locales) {
    return _getLocale(preferred_locale, function (preferred) {
      return isConverseLocale(preferred, available_locales);
    });
  },
  /**
   * @param { string } str - The string to be translated
   */
  translate: function translate(str) {
    if (!jed_instance) {
      return external_jed_default().sprintf.apply((external_jed_default()), arguments);
    }
    var t = jed_instance.translate(str);
    if (arguments.length > 1) {
      return t.fetch.apply(t, [].slice.call(arguments, 1));
    } else {
      return t.fetch();
    }
  },
  initialize: function initialize() {
    return i18n_asyncToGenerator( /*#__PURE__*/i18n_regeneratorRuntime().mark(function _callee() {
      var preferred_locale;
      return i18n_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (!shared_converse.isTestEnv()) {
              _context.next = 4;
              break;
            }
            shared_converse.locale = 'en';
            _context.next = 16;
            break;
          case 4:
            _context.prev = 4;
            preferred_locale = shared_api.settings.get('i18n');
            shared_converse.locale = i18n.getLocale(preferred_locale, shared_api.settings.get('locales'));
            _context.next = 9;
            return fetchTranslations();
          case 9:
            jed_instance = _context.sent;
            _context.next = 16;
            break;
          case 12:
            _context.prev = 12;
            _context.t0 = _context["catch"](4);
            log.fatal(_context.t0.message);
            shared_converse.locale = 'en';
          case 16:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[4, 12]]);
    }))();
  },
  __: function __() {
    return i18n.translate.apply(i18n, arguments);
  }
});
var __ = i18n.__;
;// CONCATENATED MODULE: ./src/shared/registry.js

var registry = {};

/**
 * The "elements" namespace groups methods relevant to registering custom
 * HTML elements.
 * @namespace api.elements
 * @memberOf api
 */
shared_api.elements = {
  registry: registry,
  /**
   * Defines a new custom HTML element.
   *
   * By using this API instead of `customElements.define` from the DOM,
   * we can allow custom elements to be overwritten.
   *
   * Once `converse.initialize()` is called, `api.elements.register()`
   * will get called and all custom elements will be registered to the DOM,
   * from which point onward they cannot be overwritten.
   *
   * @method api.elements.define
   * @param { string } name
   * @param { object } constructor
   */
  define: function define(name, constructor) {
    this.registry[name] = constructor;
  },
  /**
   * Registers all previously defined custom HTML elements
   * @method api.elements.register
   */
  register: function register() {
    Object.keys(registry).forEach(function (name) {
      if (!customElements.get(name)) {
        customElements.define(name, registry[name]);
      }
    });
  }
};
;// CONCATENATED MODULE: ./src/shared/components/element.js
function element_typeof(obj) {
  "@babel/helpers - typeof";

  return element_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;
  }, element_typeof(obj);
}
function element_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function element_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, element_toPropertyKey(descriptor.key), descriptor);
  }
}
function element_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) element_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) element_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function element_toPropertyKey(arg) {
  var key = element_toPrimitive(arg, "string");
  return element_typeof(key) === "symbol" ? key : String(key);
}
function element_toPrimitive(input, hint) {
  if (element_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (element_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function element_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    element_get = Reflect.get.bind();
  } else {
    element_get = function _get(target, property, receiver) {
      var base = element_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return element_get.apply(this, arguments);
}
function element_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = element_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function element_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) element_setPrototypeOf(subClass, superClass);
}
function element_setPrototypeOf(o, p) {
  element_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return element_setPrototypeOf(o, p);
}
function element_createSuper(Derived) {
  var hasNativeReflectConstruct = element_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = element_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = element_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return element_possibleConstructorReturn(this, result);
  };
}
function element_possibleConstructorReturn(self, call) {
  if (call && (element_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 element_assertThisInitialized(self);
}
function element_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function element_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 element_getPrototypeOf(o) {
  element_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return element_getPrototypeOf(o);
}


var CustomElement = /*#__PURE__*/function (_LitElement) {
  element_inherits(CustomElement, _LitElement);
  var _super = element_createSuper(CustomElement);
  function CustomElement() {
    element_classCallCheck(this, CustomElement);
    return _super.apply(this, arguments);
  }
  element_createClass(CustomElement, [{
    key: "createRenderRoot",
    value: function createRenderRoot() {
      // Render without the shadow DOM
      return this;
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this$initialize;
      element_get(element_getPrototypeOf(CustomElement.prototype), "connectedCallback", this).call(this);
      (_this$initialize = this.initialize) === null || _this$initialize === void 0 ? void 0 : _this$initialize.call(this);
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      element_get(element_getPrototypeOf(CustomElement.prototype), "disconnectedCallback", this).call(this);
      this.stopListening();
    }
  }]);
  return CustomElement;
}(external_lit_namespaceObject.LitElement);
Object.assign(CustomElement.prototype, Events);
;// CONCATENATED MODULE: ./src/shared/constants.js
// These are all the view-layer plugins.
//
// For the full Converse build, this list serves
// as a whitelist (see src/converse.js) in addition to the
// CORE_PLUGINS list in src/headless/consts.js.
var VIEW_PLUGINS = ['converse-adhoc-views', 'converse-bookmark-views', 'converse-chatboxviews', 'converse-chatview', 'converse-controlbox', 'converse-dragresize', 'converse-fullscreen', 'converse-headlines-view', 'converse-mam-views', 'converse-minimize', 'converse-modal', 'converse-muc-views', 'converse-notification', 'converse-omemo', 'converse-profile', 'converse-push', 'converse-register', 'converse-roomslist', 'converse-rootview', 'converse-rosterview', 'converse-singleton'];
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(3379);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(7795);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(569);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(3565);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(9216);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ./node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(4589);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/styles/index.scss
var styles = __webpack_require__(9790);
;// CONCATENATED MODULE: ./src/shared/styles/index.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(styles/* default */.Z, options);




       /* harmony default export */ const shared_styles = (styles/* default */.Z && styles/* default */.Z.locals ? styles/* default */.Z.locals : undefined);

// EXTERNAL MODULE: ./node_modules/bootstrap.native/dist/bootstrap-native.js
var bootstrap_native = __webpack_require__(783);
var bootstrap_native_default = /*#__PURE__*/__webpack_require__.n(bootstrap_native);
;// CONCATENATED MODULE: ./src/plugins/modal/templates/modal-alert.js
var modal_alert_templateObject;
function modal_alert_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const modal_alert = (function (o) {
  return (0,external_lit_namespaceObject.html)(modal_alert_templateObject || (modal_alert_templateObject = modal_alert_taggedTemplateLiteral(["<div class=\"alert ", "\" role=\"alert\"><p>", "</p></div>"])), o.type, o.message);
});
;// CONCATENATED MODULE: external "lit-html"
const external_lit_html_namespaceObject = lit-html;
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/view.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.

// View
// ----

// Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.










var paddedLt = /^\s*</;

// Caches a local reference to `Element.prototype` for faster access.
var ElementProto = typeof Element !== 'undefined' && Element.prototype || {};
var view_indexOf = function indexOf(array, item) {
  for (var i = 0, len = array.length; i < len; i++) if (array[i] === item) return i;
  return -1;
};

// Creating a View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = function View(options) {
  this.cid = lodash_es_uniqueId('view');
  this._domEvents = [];
  this.preinitialize.apply(this, arguments);
  lodash_es_assignIn(this, lodash_es_pick(options, viewOptions));
  this._ensureElement();
  this.initialize.apply(this, arguments);
};
View.extend = inherits;

// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;

// List of view options to be set as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

// Set up all inheritable **View** properties and methods.
Object.assign(View.prototype, Events, {
  // The default `tagName` of a View's element is `"div"`.
  tagName: 'div',
  $: function $(selector) {
    return this.el.querySelectorAll(selector);
  },
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the View
  preinitialize: function preinitialize() {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function initialize() {},
  // **render** is the core function that your view should override, in order
  // to populate its element (`this.el`), with the appropriate HTML. The
  // convention is for **render** to always return `this`.
  render: function render() {
    lodash_es_isFunction(this.beforeRender) && this.beforeRender();
    lodash_es_isFunction(this.toHTML) && (0,external_lit_html_namespaceObject.render)(this.toHTML(), this.el);
    lodash_es_isFunction(this.afterRender) && this.afterRender();
    return this;
  },
  // Remove this view by taking the element out of the DOM, and removing any
  // applicable Backbone.Events listeners.
  remove: function remove() {
    this._removeElement();
    this.stopListening();
    return this;
  },
  // Remove this view's element from the document and all event listeners
  // attached to it. Exposed for subclasses using an alternative DOM
  // manipulation API.
  _removeElement: function _removeElement() {
    this.undelegateEvents();
    if (this.el.parentNode) this.el.parentNode.removeChild(this.el);
  },
  // Change the view's element (`this.el` property) and re-delegate the
  // view's events on the new element.
  setElement: function setElement(element) {
    this.undelegateEvents();
    this._setElement(element);
    this.delegateEvents();
    return this;
  },
  // Apply the `element` to the view. `element` can be a CSS selector,
  // a string of HTML, or an Element node. If passed a NodeList or CSS
  // selector, uses just the first match.
  _setElement: function _setElement(element) {
    if (typeof element == 'string') {
      if (paddedLt.test(element)) {
        var el = document.createElement('div');
        el.innerHTML = element;
        this.el = el.firstChild;
      } else {
        this.el = document.querySelector(element);
      }
    } else if (element && !lodash_es_isElement(element) && element.length) {
      this.el = element[0];
    } else {
      this.el = element;
    }
  },
  // Set callbacks, where `this.events` is a hash of
  //
  // *{"event selector": "callback"}*
  //
  //     {
  //       'mousedown .title':  'edit',
  //       'click .button':     'save',
  //       'click .open':       function(e) { ... }
  //     }
  //
  // pairs. Callbacks will be bound to the view, with `this` set properly.
  // Uses event delegation for efficiency.
  // Omitting the selector binds the event to `this.el`.
  delegateEvents: function delegateEvents(events) {
    events || (events = lodash_es_result(this, 'events'));
    if (!events) return this;
    this.undelegateEvents();
    for (var key in events) {
      var method = events[key];
      if (!lodash_es_isFunction(method)) method = this[method];
      if (!method) continue;
      var match = key.match(delegateEventSplitter);
      this.delegate(match[1], match[2], method.bind(this));
    }
    return this;
  },
  // Make a event delegation handler for the given `eventName` and `selector`
  // and attach it to `this.el`.
  // If selector is empty, the listener will be bound to `this.el`. If not, a
  // new handler that will recursively traverse up the event target's DOM
  // hierarchy looking for a node that matches the selector. If one is found,
  // the event's `delegateTarget` property is set to it and the return the
  // result of calling bound `listener` with the parameters given to the
  // handler.
  delegate: function delegate(eventName, selector, listener) {
    var root = this.el;
    if (!root) {
      return this;
    }
    if (typeof selector === 'function') {
      listener = selector;
      selector = null;
    }
    // Given that `focus` and `blur` events do not bubble, do not delegate these events
    if (['focus', 'blur'].indexOf(eventName) !== -1) {
      var els = this.el.querySelectorAll(selector);
      for (var i = 0, len = els.length; i < len; i++) {
        var item = els[i];
        item.addEventListener(eventName, listener, false);
        this._domEvents.push({
          el: item,
          eventName: eventName,
          handler: listener
        });
      }
      return listener;
    }
    var handler = selector ? function (e) {
      var node = e.target || e.srcElement;
      for (; node && node != root; node = node.parentNode) {
        if (node.matches(selector)) {
          e.delegateTarget = node;
          listener(e);
        }
      }
    } : listener;
    this.el.addEventListener(eventName, handler, false);
    this._domEvents.push({
      el: this.el,
      eventName: eventName,
      handler: handler,
      listener: listener,
      selector: selector
    });
    return this;
  },
  // Clears all callbacks previously bound to the view by `delegateEvents`.
  // You usually don't need to use this, but may wish to if you have multiple
  // Backbone views attached to the same DOM element.
  undelegateEvents: function undelegateEvents() {
    if (this.el) {
      for (var i = 0, len = this._domEvents.length; i < len; i++) {
        var item = this._domEvents[i];
        item.el.removeEventListener(item.eventName, item.handler, false);
      }
      this._domEvents.length = 0;
    }
    return this;
  },
  // A finer-grained `undelegateEvents` for removing a single delegated event.
  // `selector` and `listener` are both optional.
  undelegate: function undelegate(eventName, selector, listener) {
    if (typeof selector === 'function') {
      listener = selector;
      selector = null;
    }
    if (this.el) {
      var handlers = this._domEvents.slice();
      var i = handlers.length;
      while (i--) {
        var item = handlers[i];
        var match = item.eventName === eventName && (listener ? item.listener === listener : true) && (selector ? item.selector === selector : true);
        if (!match) {
          continue;
        }
        item.el.removeEventListener(item.eventName, item.handler, false);
        this._domEvents.splice(i, 1);
      }
    }
    return this;
  },
  // Produces a DOM element to be assigned to your view. Exposed for
  // subclasses using an alternative DOM manipulation API.
  _createElement: function _createElement(tagName) {
    return document.createElement(tagName);
  },
  // Ensure that the View has a DOM element to render into.
  // If `this.el` is a string, pass it through `$()`, take the first
  // matching element, and re-assign it to `el`. Otherwise, create
  // an element from the `id`, `className` and `tagName` properties.
  _ensureElement: function _ensureElement() {
    if (!this.el) {
      var attrs = lodash_es_assignIn({}, lodash_es_result(this, 'attributes'));
      if (this.id) attrs.id = lodash_es_result(this, 'id');
      if (this.className) attrs['class'] = lodash_es_result(this, 'className');
      this.setElement(this._createElement(lodash_es_result(this, 'tagName')));
      this._setAttributes(attrs);
    } else {
      this.setElement(lodash_es_result(this, 'el'));
    }
  },
  // Set attributes from a hash on this view's element.  Exposed for
  // subclasses using an alternative DOM manipulation API.
  _setAttributes: function _setAttributes(attrs) {
    for (var attr in attrs) {
      attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]);
    }
  }
});
;// CONCATENATED MODULE: ./src/templates/audio.js
var audio_templateObject, audio_templateObject2;
function audio_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const audio = (function (url, hide_url) {
  return (0,external_lit_namespaceObject.html)(audio_templateObject || (audio_templateObject = audio_taggedTemplateLiteral(["<audio controls src=\"", "\"></audio>", ""])), url, hide_url ? '' : (0,external_lit_namespaceObject.html)(audio_templateObject2 || (audio_templateObject2 = audio_taggedTemplateLiteral(["<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), url, url));
});
;// CONCATENATED MODULE: ./src/templates/file.js
var file_templateObject;
function file_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const file = (function (url, name) {
  var i18n_download = __('Download file "%1$s"', name);
  return (0,external_lit_namespaceObject.html)(file_templateObject || (file_templateObject = file_taggedTemplateLiteral(["<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), url, i18n_download);
});
;// CONCATENATED MODULE: ./src/templates/form_captcha.js
var form_captcha_templateObject, form_captcha_templateObject2;
function form_captcha_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_captcha = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_captcha_templateObject || (form_captcha_templateObject = form_captcha_taggedTemplateLiteral(["\n    <fieldset class=\"form-group\">\n        ", "\n        <img src=\"data:", ";base64,", "\">\n        <input name=\"", "\" type=\"text\" ?required=\"", "\" />\n    </fieldset>\n"])), o.label ? (0,external_lit_namespaceObject.html)(form_captcha_templateObject2 || (form_captcha_templateObject2 = form_captcha_taggedTemplateLiteral(["<label>", "</label>"])), o.label) : '', o.type, o.data, o.name, o.required);
});
;// CONCATENATED MODULE: ./src/templates/form_checkbox.js
var form_checkbox_templateObject;
function form_checkbox_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_checkbox = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_checkbox_templateObject || (form_checkbox_templateObject = form_checkbox_taggedTemplateLiteral(["\n    <fieldset class=\"form-group\">\n        <input id=\"", "\" name=\"", "\" type=\"checkbox\" ?checked=", " ?required=", " />\n        <label class=\"form-check-label\" for=\"", "\">", "</label>\n    </fieldset>"])), o.id, o.name, o.checked, o.required, o.id, o.label);
});
;// CONCATENATED MODULE: ./src/templates/form_help.js
var form_help_templateObject;
function form_help_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_help = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_help_templateObject || (form_help_templateObject = form_help_taggedTemplateLiteral(["<p class=\"form-help\">", "</p>"])), o.text);
});
;// CONCATENATED MODULE: ./src/templates/form_input.js
var form_input_templateObject, form_input_templateObject2, _templateObject3;
function form_input_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_input = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_input_templateObject || (form_input_templateObject = form_input_taggedTemplateLiteral(["\n    <div class=\"form-group\">\n        ", "\n\n        <!-- This is a hack to prevent Chrome from auto-filling the username in\n             any of the other input fields in the MUC configuration form. -->\n        ", "\n\n        <input\n            autocomplete=\"", "\"\n            class=\"form-control\"\n            id=\"", "\"\n            name=\"", "\"\n            placeholder=\"", "\"\n            type=\"", "\"\n            value=\"", "\"\n            ?required=", " />\n    </div>"])), o.type !== 'hidden' ? (0,external_lit_namespaceObject.html)(form_input_templateObject2 || (form_input_templateObject2 = form_input_taggedTemplateLiteral(["<label for=\"", "\">", "</label>"])), o.id, o.label) : '', o.type === 'password' && o.fixed_username ? (0,external_lit_namespaceObject.html)(_templateObject3 || (_templateObject3 = form_input_taggedTemplateLiteral(["\n            <input class=\"hidden-username\" type=\"text\" autocomplete=\"username\" value=\"", "\"></input>\n        "])), o.fixed_username) : '', o.autocomplete || '', o.id, o.name, o.placeholder || '', o.type, o.value || '', o.required);
});
;// CONCATENATED MODULE: ./src/templates/form_select.js
var form_select_templateObject, form_select_templateObject2;
function form_select_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

var tplOption = function tplOption(o) {
  return (0,external_lit_namespaceObject.html)(form_select_templateObject || (form_select_templateObject = form_select_taggedTemplateLiteral(["<option value=\"", "\" ?selected=\"", "\">", "</option>"])), o.value, o.selected, o.label);
};
/* harmony default export */ const form_select = (function (o) {
  var _o$options;
  return (0,external_lit_namespaceObject.html)(form_select_templateObject2 || (form_select_templateObject2 = form_select_taggedTemplateLiteral(["\n    <div class=\"form-group\">\n        <label for=\"", "\">", "</label>\n        <select class=\"form-control\" id=\"", "\" name=\"", "\" ?multiple=\"", "\">\n            ", "\n        </select>\n    </div>"])), o.id, o.label, o.id, o.name, o.multiple, (_o$options = o.options) === null || _o$options === void 0 ? void 0 : _o$options.map(function (o) {
    return tplOption(o);
  }));
});
;// CONCATENATED MODULE: ./src/templates/form_textarea.js
var form_textarea_templateObject;
function form_textarea_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const form_textarea = (function (o) {
  var id = core.getUniqueId();
  return (0,external_lit_namespaceObject.html)(form_textarea_templateObject || (form_textarea_templateObject = form_textarea_taggedTemplateLiteral(["\n        <div class=\"form-group\">\n            <label class=\"label-ta\" for=\"", "\">", "</label>\n            <textarea name=\"", "\" id=\"", "\" class=\"form-control\">", "</textarea>\n        </div>\n    "])), id, o.label, o.name, id, o.value);
});
;// CONCATENATED MODULE: ./src/templates/form_url.js
var form_url_templateObject;
function form_url_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_url = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_url_templateObject || (form_url_templateObject = form_url_taggedTemplateLiteral(["\n    <label>", "\n        <a class=\"form-url\" target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>\n    </label>"])), o.label, o.value, o.value);
});
;// CONCATENATED MODULE: ./src/templates/form_username.js
var form_username_templateObject, form_username_templateObject2;
function form_username_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const form_username = (function (o) {
  return (0,external_lit_namespaceObject.html)(form_username_templateObject || (form_username_templateObject = form_username_taggedTemplateLiteral(["\n    <div class=\"form-group\">\n        ", "\n        <div class=\"input-group\">\n                <input name=\"", "\"\n                       class=\"form-control\"\n                       type=\"", "\"\n                       value=\"", "\"\n                       ?required=\"", "\" />\n            <div class=\"input-group-append\">\n                <div class=\"input-group-text\" title=\"", "\">", "</div>\n            </div>\n        </div>\n    </div>"])), o.label ? (0,external_lit_namespaceObject.html)(form_username_templateObject2 || (form_username_templateObject2 = form_username_taggedTemplateLiteral(["<label>", "</label>"])), o.label) : '', o.name, o.type, o.value || '', o.required, o.domain, o.domain);
});
;// CONCATENATED MODULE: ./src/templates/hyperlink.js
var hyperlink_templateObject, hyperlink_templateObject2;
function hyperlink_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


function onClickXMPPURI(ev) {
  ev.preventDefault();
  shared_api.rooms.open(ev.target.href);
}
/* harmony default export */ const hyperlink = (function (uri, url_text) {
  var href_text = uri.normalizePath().toString();
  if (!uri._parts.protocol && !url_text.startsWith('http://') && !url_text.startsWith('https://')) {
    href_text = 'http://' + href_text;
  }
  if (uri._parts.protocol === 'xmpp' && uri._parts.query === 'join') {
    return (0,external_lit_namespaceObject.html)(hyperlink_templateObject || (hyperlink_templateObject = hyperlink_taggedTemplateLiteral(["\n            <a target=\"_blank\"\n               rel=\"noopener\"\n               @click=", "\n               href=\"", "\">", "</a>"])), onClickXMPPURI, href_text, url_text);
  }
  return (0,external_lit_namespaceObject.html)(hyperlink_templateObject2 || (hyperlink_templateObject2 = hyperlink_taggedTemplateLiteral(["<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), href_text, url_text);
});
;// CONCATENATED MODULE: ./src/templates/video.js
var video_templateObject, video_templateObject2;
function video_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const video = (function (url, hide_url) {
  return (0,external_lit_namespaceObject.html)(video_templateObject || (video_templateObject = video_taggedTemplateLiteral(["<video controls preload=\"metadata\" src=\"", "\"></video>", ""])), url, hide_url ? '' : (0,external_lit_namespaceObject.html)(video_templateObject2 || (video_templateObject2 = video_taggedTemplateLiteral(["<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), url, url));
});
;// CONCATENATED MODULE: ./src/utils/html.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the DOM/HTML utilities module.
 */

















var html_converse$env = public_converse.env,
  html_sizzle = html_converse$env.sizzle,
  html_Strophe = html_converse$env.Strophe;
var APPROVED_URL_PROTOCOLS = ['http', 'https', 'xmpp', 'mailto'];
function getAutoCompleteProperty(name, options) {
  return {
    'muc#roomconfig_lang': 'language',
    'muc#roomconfig_roomsecret': options !== null && options !== void 0 && options.new_password ? 'new-password' : 'current-password'
  }[name];
}
var XFORM_TYPE_MAP = {
  'text-private': 'password',
  'text-single': 'text',
  'fixed': 'label',
  'boolean': 'checkbox',
  'hidden': 'hidden',
  'jid-multi': 'textarea',
  'list-single': 'dropdown',
  'list-multi': 'dropdown'
};
var XFORM_VALIDATE_TYPE_MAP = {
  'xs:anyURI': 'url',
  'xs:byte': 'number',
  'xs:date': 'date',
  'xs:dateTime': 'datetime',
  'xs:int': 'number',
  'xs:integer': 'number',
  'xs:time': 'time'
};
var EMPTY_TEXT_REGEX = /\s*\n\s*/;
function stripEmptyTextNodes(el) {
  var _el$tree, _el$tree2, _el;
  el = (_el$tree = (_el$tree2 = (_el = el).tree) === null || _el$tree2 === void 0 ? void 0 : _el$tree2.call(_el)) !== null && _el$tree !== void 0 ? _el$tree : el;
  var n;
  var text_nodes = [];
  var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, function (node) {
    if (node.parentElement.nodeName.toLowerCase() === 'body') {
      return NodeFilter.FILTER_REJECT;
    }
    return NodeFilter.FILTER_ACCEPT;
  });
  while (n = walker.nextNode()) text_nodes.push(n);
  text_nodes.forEach(function (n) {
    return EMPTY_TEXT_REGEX.test(n.data) && n.parentElement.removeChild(n);
  });
  return el;
}
var html_serializer = new XMLSerializer();

/**
 * Given two XML or HTML elements, determine if they're equal
 * @param { Element } actual
 * @param { Element } expected
 * @returns { Boolean }
 */
function isEqualNode(actual, expected) {
  if (!core.isElement(actual)) throw new Error("Element being compared must be an Element!");
  actual = stripEmptyTextNodes(actual);
  expected = stripEmptyTextNodes(expected);
  var isEqual = actual.isEqualNode(expected);
  if (!isEqual) {
    // XXX: This is a hack.
    // When creating two XML elements, one via DOMParser, and one via
    // createElementNS (or createElement), then "isEqualNode" doesn't match.
    //
    // For example, in the following code `isEqual` is false:
    // ------------------------------------------------------
    // const a = document.createElementNS('foo', 'div');
    // a.setAttribute('xmlns', 'foo');
    //
    // const b = (new DOMParser()).parseFromString('<div xmlns="foo"></div>', 'text/xml').firstElementChild;
    // const isEqual = a.isEqualNode(div); //  false
    //
    // The workaround here is to serialize both elements to string and then use
    // DOMParser again for both (via xmlHtmlNode).
    //
    // This is not efficient, but currently this is only being used in tests.
    //
    var xmlHtmlNode = html_Strophe.xmlHtmlNode;
    var actual_string = html_serializer.serializeToString(actual);
    var expected_string = html_serializer.serializeToString(expected);
    isEqual = actual_string === expected_string || xmlHtmlNode(actual_string).isEqualNode(xmlHtmlNode(expected_string));
  }
  return isEqual;
}

/**
 * Given an HTMLElement representing a form field, return it's name and value.
 * @param { HTMLElement } field
 * @returns { { string, string } | null }
 */
function getNameAndValue(field) {
  var name = field.getAttribute('name');
  if (!name) {
    return null; // See #1924
  }

  var value;
  if (field.getAttribute('type') === 'checkbox') {
    value = field.checked && 1 || 0;
  } else if (field.tagName == "TEXTAREA") {
    value = field.value.split('\n').filter(function (s) {
      return s.trim();
    });
  } else if (field.tagName == "SELECT") {
    value = core.getSelectValues(field);
  } else {
    value = field.value;
  }
  return {
    name: name,
    value: value
  };
}
function getInputType(field) {
  var type = XFORM_TYPE_MAP[field.getAttribute('type')];
  if (type == 'text') {
    var datatypes = field.getElementsByTagNameNS("http://jabber.org/protocol/xdata-validate", "validate");
    if (datatypes.length === 1) {
      var datatype = datatypes[0].getAttribute("datatype");
      return XFORM_VALIDATE_TYPE_MAP[datatype] || type;
    }
  }
  return type;
}
function slideOutWrapup(el) {
  /* Wrapup function for slideOut. */
  el.removeAttribute('data-slider-marker');
  el.classList.remove('collapsed');
  el.style.overflow = '';
  el.style.height = '';
}
function getFileName(url) {
  var uri = getURI(url);
  try {
    return decodeURI(uri.filename());
  } catch (error) {
    log.debug(error);
    return uri.filename();
  }
}

/**
 * Returns the markup for a URL that points to a downloadable asset
 * (such as a video, image or audio file).
 * @method u#getOOBURLMarkup
 * @param { String } url
 * @returns { TemplateResult }
 */
function getOOBURLMarkup(url) {
  var uri = getURI(url);
  if (uri === null) {
    return url;
  }
  if (isVideoURL(uri)) {
    return video(url);
  } else if (isAudioURL(uri)) {
    return audio(url);
  } else if (isImageURL(uri)) {
    return file(uri.toString(), getFileName(uri));
  } else {
    return file(uri.toString(), getFileName(uri));
  }
}

/**
 * Return the height of the passed in DOM element,
 * based on the heights of its children.
 * @method u#calculateElementHeight
 * @param { HTMLElement } el
 * @returns {number}
 */
core.calculateElementHeight = function (el) {
  return Array.from(el.children).reduce(function (result, child) {
    return result + child.offsetHeight;
  }, 0);
};
core.getNextElement = function (el) {
  var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '*';
  var next_el = el.nextElementSibling;
  while (next_el !== null && !html_sizzle.matchesSelector(next_el, selector)) {
    next_el = next_el.nextElementSibling;
  }
  return next_el;
};
core.getPreviousElement = function (el) {
  var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '*';
  var prev_el = el.previousElementSibling;
  while (prev_el !== null && !html_sizzle.matchesSelector(prev_el, selector)) {
    prev_el = prev_el.previousElementSibling;
  }
  return prev_el;
};
core.getFirstChildElement = function (el) {
  var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '*';
  var first_el = el.firstElementChild;
  while (first_el !== null && !html_sizzle.matchesSelector(first_el, selector)) {
    first_el = first_el.nextElementSibling;
  }
  return first_el;
};
core.getLastChildElement = function (el) {
  var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '*';
  var last_el = el.lastElementChild;
  while (last_el !== null && !html_sizzle.matchesSelector(last_el, selector)) {
    last_el = last_el.previousElementSibling;
  }
  return last_el;
};
core.toggleClass = function (className, el) {
  core.hasClass(className, el) ? removeClass(className, el) : addClass(className, el);
};

/**
 * Has an element a class?
 * @method u#hasClass
 * @param { string } className
 * @param { Element } el
 */
function hasClass(className, el) {
  return el instanceof Element && el.classList.contains(className);
}

/**
 * Add a class to an element.
 * @method u#addClass
 * @param { string } className
 * @param { Element } el
 */
function addClass(className, el) {
  el instanceof Element && el.classList.add(className);
  return el;
}

/**
 * Remove a class from an element.
 * @method u#removeClass
 * @param { string } className
 * @param { Element } el
 */
function removeClass(className, el) {
  el instanceof Element && el.classList.remove(className);
  return el;
}

/**
 * Remove an element from its parent
 * @method u#removeElement
 * @param { Element } el
 */
function removeElement(el) {
  el instanceof Element && el.parentNode && el.parentNode.removeChild(el);
  return el;
}
core.getElementFromTemplateResult = function (tr) {
  var div = document.createElement('div');
  (0,external_lit_namespaceObject.render)(tr, div);
  return div.firstElementChild;
};
core.showElement = function (el) {
  removeClass('collapsed', el);
  removeClass('hidden', el);
};
core.hideElement = function (el) {
  el instanceof Element && el.classList.add('hidden');
  return el;
};
function ancestor(el, selector) {
  var parent = el;
  while (parent !== null && !html_sizzle.matchesSelector(parent, selector)) {
    parent = parent.parentElement;
  }
  return parent;
}

/**
 * Return the element's siblings until one matches the selector.
 * @private
 * @method u#nextUntil
 * @param { HTMLElement } el
 * @param { String } selector
 */
core.nextUntil = function (el, selector) {
  var matches = [];
  var sibling_el = el.nextElementSibling;
  while (sibling_el !== null && !sibling_el.matches(selector)) {
    matches.push(sibling_el);
    sibling_el = sibling_el.nextElementSibling;
  }
  return matches;
};

/**
 * Helper method that replace HTML-escaped symbols with equivalent characters
 * (e.g. transform occurrences of '&amp;' to '&')
 * @private
 * @method u#unescapeHTML
 * @param { String } string - a String containing the HTML-escaped symbols.
 */
core.unescapeHTML = function (string) {
  var div = document.createElement('div');
  div.innerHTML = string;
  return div.innerText;
};
core.escapeHTML = function (string) {
  return string.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};
function isProtocolApproved(protocol) {
  var safeProtocolsList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : APPROVED_URL_PROTOCOLS;
  return !!safeProtocolsList.includes(protocol);
}

// Will return false if URL is malformed or contains disallowed characters
function isUrlValid(urlString) {
  try {
    var url = new URL(urlString);
    return !!url;
  } catch (error) {
    return false;
  }
}
function getHyperlinkTemplate(url) {
  var http_url = RegExp('^w{3}.', 'ig').test(url) ? "http://".concat(url) : url;
  var uri = getURI(url);
  if (uri !== null && isUrlValid(http_url) && (isProtocolApproved(uri._parts.protocol) || !uri._parts.protocol)) {
    return hyperlink(uri, url);
  }
  return url;
}
core.slideInAllElements = function (elements) {
  var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300;
  return Promise.all(Array.from(elements).map(function (e) {
    return core.slideIn(e, duration);
  }));
};
core.slideToggleElement = function (el, duration) {
  if (core.hasClass('collapsed', el) || core.hasClass('hidden', el)) {
    return core.slideOut(el, duration);
  } else {
    return core.slideIn(el, duration);
  }
};

/**
 * Shows/expands an element by sliding it out of itself
 * @method slideOut
 * @param { HTMLElement } el - The HTML string
 * @param { Number } duration - The duration amount in milliseconds
 */
function slideOut(el) {
  var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
  return new Promise(function (resolve, reject) {
    if (!el) {
      var err = 'An element needs to be passed in to slideOut';
      log.warn(err);
      reject(new Error(err));
      return;
    }
    var marker = el.getAttribute('data-slider-marker');
    if (marker) {
      el.removeAttribute('data-slider-marker');
      cancelAnimationFrame(marker);
    }
    var end_height = core.calculateElementHeight(el);
    if (window.converse_disable_effects) {
      // Effects are disabled (for tests)
      el.style.height = end_height + 'px';
      slideOutWrapup(el);
      resolve();
      return;
    }
    if (!core.hasClass('collapsed', el) && !core.hasClass('hidden', el)) {
      resolve();
      return;
    }
    var steps = duration / 17; // We assume 17ms per animation which is ~60FPS
    var height = 0;
    function draw() {
      height += end_height / steps;
      if (height < end_height) {
        el.style.height = height + 'px';
        el.setAttribute('data-slider-marker', requestAnimationFrame(draw).toString());
      } else {
        // We recalculate the height to work around an apparent
        // browser bug where browsers don't know the correct
        // offsetHeight beforehand.
        el.removeAttribute('data-slider-marker');
        el.style.height = core.calculateElementHeight(el) + 'px';
        el.style.overflow = '';
        el.style.height = '';
        resolve();
      }
    }
    el.style.height = '0';
    el.style.overflow = 'hidden';
    el.classList.remove('hidden');
    el.classList.remove('collapsed');
    el.setAttribute('data-slider-marker', requestAnimationFrame(draw).toString());
  });
}

/**
 * Hides/contracts an element by sliding it into itself
 * @method slideIn
 * @param { HTMLElement } el - The HTML string
 * @param { Number } duration - The duration amount in milliseconds
 */
function slideIn(el) {
  var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
  return new Promise(function (resolve, reject) {
    if (!el) {
      var err = 'An element needs to be passed in to slideIn';
      log.warn(err);
      return reject(new Error(err));
    } else if (core.hasClass('collapsed', el)) {
      return resolve(el);
    } else if (window.converse_disable_effects) {
      // Effects are disabled (for tests)
      el.classList.add('collapsed');
      el.style.height = '';
      return resolve(el);
    }
    var marker = el.getAttribute('data-slider-marker');
    if (marker) {
      el.removeAttribute('data-slider-marker');
      cancelAnimationFrame(marker);
    }
    var original_height = el.offsetHeight,
      steps = duration / 17; // We assume 17ms per animation which is ~60FPS
    var height = original_height;
    el.style.overflow = 'hidden';
    function draw() {
      height -= original_height / steps;
      if (height > 0) {
        el.style.height = height + 'px';
        el.setAttribute('data-slider-marker', requestAnimationFrame(draw).toString());
      } else {
        el.removeAttribute('data-slider-marker');
        el.classList.add('collapsed');
        el.style.height = '';
        resolve(el);
      }
    }
    el.setAttribute('data-slider-marker', requestAnimationFrame(draw).toString());
  });
}
function afterAnimationEnds(el, callback) {
  el.classList.remove('visible');
  callback === null || callback === void 0 ? void 0 : callback();
}
core.isInDOM = function (el) {
  return document.querySelector('body').contains(el);
};
core.isVisible = function (el) {
  if (el === null) {
    return false;
  }
  if (core.hasClass('hidden', el)) {
    return false;
  }
  // XXX: Taken from jQuery's "visible" implementation
  return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
};
core.fadeIn = function (el, callback) {
  if (!el) {
    log.warn('An element needs to be passed in to fadeIn');
  }
  if (window.converse_disable_effects) {
    el.classList.remove('hidden');
    return afterAnimationEnds(el, callback);
  }
  if (core.hasClass('hidden', el)) {
    el.classList.add('visible');
    el.classList.remove('hidden');
    el.addEventListener('webkitAnimationEnd', function () {
      return afterAnimationEnds(el, callback);
    });
    el.addEventListener('animationend', function () {
      return afterAnimationEnds(el, callback);
    });
    el.addEventListener('oanimationend', function () {
      return afterAnimationEnds(el, callback);
    });
  } else {
    afterAnimationEnds(el, callback);
  }
};

/**
 * Takes an XML field in XMPP XForm (XEP-004: Data Forms) format returns a
 * [TemplateResult](https://lit.polymer-project.org/api/classes/_lit_html_.templateresult.html).
 * @method u#xForm2TemplateResult
 * @param { Element } field - the field to convert
 * @param { Element } stanza - the containing stanza
 * @param { Object } options
 * @returns { TemplateResult }
 */
core.xForm2TemplateResult = function (field, stanza) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  if (field.getAttribute('type') === 'list-single' || field.getAttribute('type') === 'list-multi') {
    var values = core.queryChildren(field, 'value').map(function (el) {
      return el === null || el === void 0 ? void 0 : el.textContent;
    });
    var _options = core.queryChildren(field, 'option').map(function (option) {
      var _option$querySelector;
      var value = (_option$querySelector = option.querySelector('value')) === null || _option$querySelector === void 0 ? void 0 : _option$querySelector.textContent;
      return {
        'value': value,
        'label': option.getAttribute('label'),
        'selected': values.includes(value),
        'required': !!field.querySelector('required')
      };
    });
    return form_select({
      options: _options,
      'id': core.getUniqueId(),
      'label': field.getAttribute('label'),
      'multiple': field.getAttribute('type') === 'list-multi',
      'name': field.getAttribute('var'),
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('type') === 'fixed') {
    var _field$querySelector;
    var text = (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent;
    return form_help({
      text: text
    });
  } else if (field.getAttribute('type') === 'jid-multi') {
    var _field$querySelector2;
    return form_textarea({
      'name': field.getAttribute('var'),
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector2 = field.querySelector('value')) === null || _field$querySelector2 === void 0 ? void 0 : _field$querySelector2.textContent,
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('type') === 'boolean') {
    var _field$querySelector3;
    var value = (_field$querySelector3 = field.querySelector('value')) === null || _field$querySelector3 === void 0 ? void 0 : _field$querySelector3.textContent;
    return form_checkbox({
      'id': core.getUniqueId(),
      'name': field.getAttribute('var'),
      'label': field.getAttribute('label') || '',
      'checked': (value === '1' || value === 'true') && 'checked="1"' || ''
    });
  } else if (field.getAttribute('var') === 'url') {
    var _field$querySelector4;
    return form_url({
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector4 = field.querySelector('value')) === null || _field$querySelector4 === void 0 ? void 0 : _field$querySelector4.textContent
    });
  } else if (field.getAttribute('var') === 'username') {
    var _field$querySelector5;
    return form_username({
      'domain': ' @' + options.domain,
      'name': field.getAttribute('var'),
      'type': getInputType(field),
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector5 = field.querySelector('value')) === null || _field$querySelector5 === void 0 ? void 0 : _field$querySelector5.textContent,
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('var') === 'password') {
    var _field$querySelector6;
    return form_input({
      'name': field.getAttribute('var'),
      'type': 'password',
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector6 = field.querySelector('value')) === null || _field$querySelector6 === void 0 ? void 0 : _field$querySelector6.textContent,
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('var') === 'ocr') {
    // Captcha
    var uri = field.querySelector('uri');
    var el = html_sizzle('data[cid="' + uri.textContent.replace(/^cid:/, '') + '"]', stanza)[0];
    return form_captcha({
      'label': field.getAttribute('label'),
      'name': field.getAttribute('var'),
      'data': el === null || el === void 0 ? void 0 : el.textContent,
      'type': uri.getAttribute('type'),
      'required': !!field.querySelector('required')
    });
  } else {
    var _field$querySelector7;
    var name = field.getAttribute('var');
    return form_input({
      'id': core.getUniqueId(),
      'label': field.getAttribute('label') || '',
      'name': name,
      'fixed_username': options === null || options === void 0 ? void 0 : options.fixed_username,
      'autocomplete': getAutoCompleteProperty(name, options),
      'placeholder': null,
      'required': !!field.querySelector('required'),
      'type': getInputType(field),
      'value': (_field$querySelector7 = field.querySelector('value')) === null || _field$querySelector7 === void 0 ? void 0 : _field$querySelector7.textContent
    });
  }
};
Object.assign(core, {
  hasClass: hasClass,
  addClass: addClass,
  ancestor: ancestor,
  getOOBURLMarkup: getOOBURLMarkup,
  isEqualNode: isEqualNode,
  removeClass: removeClass,
  removeElement: removeElement,
  slideIn: slideIn,
  slideOut: slideOut
});
/* harmony default export */ const utils_html = (core);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/modal/styles/_modal.scss
var _modal = __webpack_require__(8105);
;// CONCATENATED MODULE: ./src/plugins/modal/styles/_modal.scss

      
      
      
      
      
      
      
      
      

var _modal_options = {};

_modal_options.styleTagTransform = (styleTagTransform_default());
_modal_options.setAttributes = (setAttributesWithoutAttributes_default());

      _modal_options.insert = insertBySelector_default().bind(null, "head");
    
_modal_options.domAPI = (styleDomAPI_default());
_modal_options.insertStyleElement = (insertStyleElement_default());

var _modal_update = injectStylesIntoStyleTag_default()(_modal/* default */.Z, _modal_options);




       /* harmony default export */ const styles_modal = (_modal/* default */.Z && _modal/* default */.Z.locals ? _modal/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/modal/base.js









var BaseModal = View.extend({
  className: "modal",
  persistent: false,
  // Whether this modal should persist in the DOM once it's been closed
  events: {
    'click  .nav-item .nav-link': 'switchTab'
  },
  initialize: function initialize(options) {
    var _this = this;
    if (!this.id) {
      throw new Error("Each modal class must have a unique id attribute");
    }
    // Allow properties to be set via passed in options
    Object.assign(this, options);
    this.render();
    this.el.setAttribute('tabindex', '-1');
    this.el.setAttribute('role', 'dialog');
    this.el.setAttribute('aria-hidden', 'true');
    var label_id = this.el.querySelector('.modal-title').getAttribute('id');
    label_id && this.el.setAttribute('aria-labelledby', label_id);
    this.insertIntoDOM();
    var Modal = (bootstrap_native_default()).Modal;
    this.modal = new Modal(this.el, {
      backdrop: true,
      keyboard: true
    });
    this.el.addEventListener('hide.bs.modal', function () {
      return _this.onHide();
    }, false);
  },
  onHide: function onHide() {
    removeClass('selected', this.trigger_el);
    !this.persistent && shared_api.modal.remove(this);
  },
  insertIntoDOM: function insertIntoDOM() {
    var container_el = document.querySelector("#converse-modals");
    container_el.insertAdjacentElement('beforeEnd', this.el);
  },
  switchTab: function switchTab(ev) {
    var _this2 = this;
    ev.stopPropagation();
    ev.preventDefault();
    external_sizzle_default()('.nav-link.active', this.el).forEach(function (el) {
      removeClass('active', _this2.el.querySelector(el.getAttribute('href')));
      removeClass('active', el);
    });
    addClass('active', ev.target);
    addClass('active', this.el.querySelector(ev.target.getAttribute('href')));
  },
  alert: function alert(message) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'primary';
    var body = this.el.querySelector('.modal-alert');
    if (body === null) {
      log.error("Could not find a .modal-alert element in the modal to show an alert message in!");
      return;
    }
    // FIXME: Instead of adding the alert imperatively, we should
    // find a way to let the modal rerender with an alert message
    (0,external_lit_namespaceObject.render)(modal_alert({
      'type': "alert-".concat(type),
      'message': message
    }), body);
    var el = body.firstElementChild;
    setTimeout(function () {
      addClass('fade-out', el);
      setTimeout(function () {
        return removeElement(el);
      }, 600);
    }, 5000);
  },
  show: function show(ev) {
    if (ev) {
      ev.preventDefault();
      this.trigger_el = ev.target;
      !hasClass('chat-image', this.trigger_el) && addClass('selected', this.trigger_el);
    }
    this.modal.show();
  }
});
/* harmony default export */ const base = (BaseModal);
;// CONCATENATED MODULE: ./src/plugins/modal/templates/buttons.js
var buttons_templateObject, buttons_templateObject2;
function buttons_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var modal_close_button = (0,external_lit_namespaceObject.html)(buttons_templateObject || (buttons_templateObject = buttons_taggedTemplateLiteral(["<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">", "</button>"])), __('Close'));
var modal_header_close_button = (0,external_lit_namespaceObject.html)(buttons_templateObject2 || (buttons_templateObject2 = buttons_taggedTemplateLiteral(["<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"", "\"><span aria-hidden=\"true\">\xD7</span></button>"])), __('Close'));
;// CONCATENATED MODULE: ./src/plugins/modal/templates/modal.js
var modal_templateObject, modal_templateObject2;
function modal_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const modal = (function (el) {
  var _el$model, _el$model$get, _el$model2, _el$renderModal, _el$renderModal2, _el$renderModalFooter, _el$renderModalFooter2;
  var alert = (_el$model = el.model) === null || _el$model === void 0 ? void 0 : _el$model.get('alert');
  var level = (_el$model$get = (_el$model2 = el.model) === null || _el$model2 === void 0 ? void 0 : _el$model2.get('level')) !== null && _el$model$get !== void 0 ? _el$model$get : '';
  return (0,external_lit_namespaceObject.html)(modal_templateObject || (modal_templateObject = modal_taggedTemplateLiteral(["\n        <div class=\"modal-dialog\" role=\"document\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\">\n            <div class=\"modal-content\">\n                <div class=\"modal-header ", "\">\n                    <h5 class=\"modal-title\">", "</h5>\n                    ", "\n                </div>\n                <div class=\"modal-body\">\n                    <span class=\"modal-alert\">\n                        ", "\n                    </span>\n                    ", "\n                </div>\n                ", "\n            </div>\n        </div>\n    "])), level, el.getModalTitle(), modal_header_close_button, alert ? modal_alert({
    'type': "alert-".concat(alert.type),
    'message': alert.message
  }) : '', (_el$renderModal = (_el$renderModal2 = el.renderModal) === null || _el$renderModal2 === void 0 ? void 0 : _el$renderModal2.call(el)) !== null && _el$renderModal !== void 0 ? _el$renderModal : '', (_el$renderModalFooter = (_el$renderModalFooter2 = el.renderModalFooter) === null || _el$renderModalFooter2 === void 0 ? void 0 : _el$renderModalFooter2.call(el)) !== null && _el$renderModalFooter !== void 0 ? _el$renderModalFooter : (0,external_lit_namespaceObject.html)(modal_templateObject2 || (modal_templateObject2 = modal_taggedTemplateLiteral(["<div class=\"modal-footer\">", "</div>"])), modal_close_button));
});
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/element.js
function src_element_typeof(obj) {
  "@babel/helpers - typeof";

  return src_element_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;
  }, src_element_typeof(obj);
}
function src_element_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function src_element_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, src_element_toPropertyKey(descriptor.key), descriptor);
  }
}
function src_element_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) src_element_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) src_element_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function src_element_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) src_element_setPrototypeOf(subClass, superClass);
}
function src_element_createSuper(Derived) {
  var hasNativeReflectConstruct = src_element_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = src_element_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = src_element_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return src_element_possibleConstructorReturn(this, result);
  };
}
function src_element_possibleConstructorReturn(self, call) {
  if (call && (src_element_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 src_element_assertThisInitialized(self);
}
function src_element_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function element_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  element_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !element_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return element_construct(Class, arguments, src_element_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return src_element_setPrototypeOf(Wrapper, Class);
  };
  return element_wrapNativeSuper(Class);
}
function element_construct(Parent, args, Class) {
  if (src_element_isNativeReflectConstruct()) {
    element_construct = Reflect.construct.bind();
  } else {
    element_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) src_element_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return element_construct.apply(null, arguments);
}
function src_element_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 element_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function src_element_setPrototypeOf(o, p) {
  src_element_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return src_element_setPrototypeOf(o, p);
}
function src_element_getPrototypeOf(o) {
  src_element_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return src_element_getPrototypeOf(o);
}
function element_defineProperty(obj, key, value) {
  key = src_element_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 src_element_toPropertyKey(arg) {
  var key = src_element_toPrimitive(arg, "string");
  return src_element_typeof(key) === "symbol" ? key : String(key);
}
function src_element_toPrimitive(input, hint) {
  if (src_element_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (src_element_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}









var element_paddedLt = /^\s*</;

// Caches a local reference to `Element.prototype` for faster access.
var element_ElementProto = typeof Element !== 'undefined' && Element.prototype || {};

// Cached regex to split keys for `delegate`.
var element_delegateEventSplitter = /^(\S+)\s*(.*)$/;

// List of view options to be set as properties.
var element_viewOptions = ['model', 'collection', 'events'];
var ElementView = /*#__PURE__*/function (_HTMLElement) {
  src_element_inherits(ElementView, _HTMLElement);
  var _super = src_element_createSuper(ElementView);
  function ElementView(options) {
    var _this;
    src_element_classCallCheck(this, ElementView);
    _this = _super.call(this);
    // Creating a View creates its initial element outside of the DOM,
    // if an existing element is not provided...
    element_defineProperty(src_element_assertThisInitialized(_this), "events", {});
    _this.cid = lodash_es_uniqueId('view');
    _this._domEvents = [];
    lodash_es_assignIn(src_element_assertThisInitialized(_this), lodash_es_pick(options, element_viewOptions));
    return _this;
  }
  src_element_createClass(ElementView, [{
    key: "createRenderRoot",
    value: function createRenderRoot() {
      // Render without the shadow DOM
      return this;
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      if (!this._initialized) {
        this.preinitialize.apply(this, arguments);
        this.initialize.apply(this, arguments);
        this._initialized = true;
      }
      this.delegateEvents();
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      this.undelegateEvents();
      this.stopListening();
    }

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the View
  }, {
    key: "preinitialize",
    value: function preinitialize() {// eslint-disable-line class-methods-use-this
    }

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
  }, {
    key: "initialize",
    value: function initialize() {} // eslint-disable-line class-methods-use-this

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
  }, {
    key: "render",
    value: function render() {
      lodash_es_isFunction(this.beforeRender) && this.beforeRender();
      lodash_es_isFunction(this.toHTML) && (0,external_lit_html_namespaceObject.render)(this.toHTML(), this);
      lodash_es_isFunction(this.afterRender) && this.afterRender();
      return this;
    }

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save',
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
  }, {
    key: "delegateEvents",
    value: function delegateEvents() {
      if (!this.events) {
        return this;
      }
      this.undelegateEvents();
      for (var key in this.events) {
        var method = this.events[key];
        if (!lodash_es_isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(element_delegateEventSplitter);
        this.delegate(match[1], match[2], method.bind(this));
      }
      return this;
    }

    // Make a event delegation handler for the given `eventName` and `selector`
    // and attach it to `this.el`.
    // If selector is empty, the listener will be bound to `this.el`. If not, a
    // new handler that will recursively traverse up the event target's DOM
    // hierarchy looking for a node that matches the selector. If one is found,
    // the event's `delegateTarget` property is set to it and the return the
    // result of calling bound `listener` with the parameters given to the
    // handler.
  }, {
    key: "delegate",
    value: function delegate(eventName, selector, listener) {
      var root = this;
      if (!root) {
        return this;
      }
      if (typeof selector === 'function') {
        listener = selector;
        selector = null;
      }
      // Given that `focus` and `blur` events do not bubble, do not delegate these events
      if (['focus', 'blur'].indexOf(eventName) !== -1) {
        var els = this.querySelectorAll(selector);
        for (var i = 0, len = els.length; i < len; i++) {
          var item = els[i];
          item.addEventListener(eventName, listener, false);
          this._domEvents.push({
            el: item,
            eventName: eventName,
            handler: listener
          });
        }
        return listener;
      }
      var handler = selector ? function (e) {
        var node = e.target || e.srcElement;
        for (; node && node != root; node = node.parentNode) {
          if (node.matches(selector)) {
            e.delegateTarget = node;
            listener(e);
          }
        }
      } : listener;
      this.addEventListener(eventName, handler, false);
      this._domEvents.push({
        el: this,
        eventName: eventName,
        handler: handler,
        listener: listener,
        selector: selector
      });
      return this;
    }

    // Clears all callbacks previously bound to the view by `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
  }, {
    key: "undelegateEvents",
    value: function undelegateEvents() {
      if (this) {
        for (var i = 0, len = this._domEvents.length; i < len; i++) {
          var item = this._domEvents[i];
          item.el.removeEventListener(item.eventName, item.handler, false);
        }
        this._domEvents.length = 0;
      }
      return this;
    }

    // A finer-grained `undelegateEvents` for removing a single delegated event.
    // `selector` and `listener` are both optional.
  }, {
    key: "undelegate",
    value: function undelegate(eventName, selector, listener) {
      if (typeof selector === 'function') {
        listener = selector;
        selector = null;
      }
      if (this) {
        var handlers = this._domEvents.slice();
        var i = handlers.length;
        while (i--) {
          var item = handlers[i];
          var match = item.eventName === eventName && (listener ? item.listener === listener : true) && (selector ? item.selector === selector : true);
          if (!match) {
            continue;
          }
          item.el.removeEventListener(item.eventName, item.handler, false);
          this._domEvents.splice(i, 1);
        }
      }
      return this;
    }
  }]);
  return ElementView;
}( /*#__PURE__*/element_wrapNativeSuper(HTMLElement));

// Set up all inheritable **View** properties and methods.
Object.assign(ElementView.prototype, Events);
;// CONCATENATED MODULE: ./src/plugins/modal/modal.js
function modal_typeof(obj) {
  "@babel/helpers - typeof";

  return modal_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;
  }, modal_typeof(obj);
}
function modal_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  modal_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" == modal_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 modal_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 modal_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        modal_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        modal_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function modal_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function modal_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, modal_toPropertyKey(descriptor.key), descriptor);
  }
}
function modal_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) modal_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) modal_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modal_toPropertyKey(arg) {
  var key = modal_toPrimitive(arg, "string");
  return modal_typeof(key) === "symbol" ? key : String(key);
}
function modal_toPrimitive(input, hint) {
  if (modal_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modal_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function modal_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) modal_setPrototypeOf(subClass, superClass);
}
function modal_setPrototypeOf(o, p) {
  modal_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return modal_setPrototypeOf(o, p);
}
function modal_createSuper(Derived) {
  var hasNativeReflectConstruct = modal_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = modal_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = modal_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return modal_possibleConstructorReturn(this, result);
  };
}
function modal_possibleConstructorReturn(self, call) {
  if (call && (modal_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 modal_assertThisInitialized(self);
}
function modal_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function modal_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 modal_getPrototypeOf(o) {
  modal_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return modal_getPrototypeOf(o);
}





var modal_BaseModal = /*#__PURE__*/function (_ElementView) {
  modal_inherits(BaseModal, _ElementView);
  var _super = modal_createSuper(BaseModal);
  function BaseModal(options) {
    var _this;
    modal_classCallCheck(this, BaseModal);
    _this = _super.call(this);
    _this.className = 'modal';
    _this.initialized = getOpenPromise();

    // Allow properties to be set via passed in options
    Object.assign(modal_assertThisInitialized(_this), options);
    setTimeout(function () {
      return _this.insertIntoDOM();
    });
    _this.addEventListener('hide.bs.modal', function () {
      return _this.onHide();
    }, false);
    return _this;
  }
  modal_createClass(BaseModal, [{
    key: "initialize",
    value: function initialize() {
      this.modal = new (bootstrap_native_default()).Modal(this, {
        backdrop: true,
        keyboard: true
      });
      this.initialized.resolve();
      this.render();
    }
  }, {
    key: "toHTML",
    value: function toHTML() {
      return modal(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      // Intended to be overwritten
      return '';
    }
  }, {
    key: "switchTab",
    value: function switchTab(ev) {
      ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      this.tab = ev.target.getAttribute('data-name');
      this.render();
    }
  }, {
    key: "onHide",
    value: function onHide() {
      this.modal.hide();
    }
  }, {
    key: "insertIntoDOM",
    value: function insertIntoDOM() {
      var container_el = document.querySelector("#converse-modals");
      container_el.insertAdjacentElement('beforeEnd', this);
    }
  }, {
    key: "alert",
    value: function alert(message) {
      var _this2 = this;
      var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'primary';
      this.model.set('alert', {
        message: message,
        type: type
      });
      setTimeout(function () {
        _this2.model.set('alert', undefined);
      }, 5000);
    }
  }, {
    key: "show",
    value: function () {
      var _show = modal_asyncToGenerator( /*#__PURE__*/modal_regeneratorRuntime().mark(function _callee() {
        return modal_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return this.initialized;
            case 2:
              this.modal.show();
              this.render();
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function show() {
        return _show.apply(this, arguments);
      }
      return show;
    }()
  }]);
  return BaseModal;
}(ElementView);
/* harmony default export */ const modal_modal = (modal_BaseModal);
;// CONCATENATED MODULE: ./src/plugins/modal/templates/alert.js
var alert_templateObject, alert_templateObject2;
function alert_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const templates_alert = (function (o) {
  return (0,external_lit_namespaceObject.html)(alert_templateObject || (alert_templateObject = alert_taggedTemplateLiteral(["\n    <div class=\"modal-body\">\n        <span class=\"modal-alert\"></span>\n        ", "\n    </div>"])), o.messages.map(function (message) {
    return (0,external_lit_namespaceObject.html)(alert_templateObject2 || (alert_templateObject2 = alert_taggedTemplateLiteral(["<p>", "</p>"])), message);
  }));
});
;// CONCATENATED MODULE: ./src/plugins/modal/alert.js
function alert_typeof(obj) {
  "@babel/helpers - typeof";

  return alert_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;
  }, alert_typeof(obj);
}
function alert_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function alert_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, alert_toPropertyKey(descriptor.key), descriptor);
  }
}
function alert_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) alert_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) alert_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function alert_toPropertyKey(arg) {
  var key = alert_toPrimitive(arg, "string");
  return alert_typeof(key) === "symbol" ? key : String(key);
}
function alert_toPrimitive(input, hint) {
  if (alert_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (alert_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function alert_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    alert_get = Reflect.get.bind();
  } else {
    alert_get = function _get(target, property, receiver) {
      var base = alert_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return alert_get.apply(this, arguments);
}
function alert_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = alert_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function alert_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) alert_setPrototypeOf(subClass, superClass);
}
function alert_setPrototypeOf(o, p) {
  alert_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return alert_setPrototypeOf(o, p);
}
function alert_createSuper(Derived) {
  var hasNativeReflectConstruct = alert_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = alert_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = alert_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return alert_possibleConstructorReturn(this, result);
  };
}
function alert_possibleConstructorReturn(self, call) {
  if (call && (alert_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 alert_assertThisInitialized(self);
}
function alert_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function alert_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 alert_getPrototypeOf(o) {
  alert_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return alert_getPrototypeOf(o);
}



var Alert = /*#__PURE__*/function (_BaseModal) {
  alert_inherits(Alert, _BaseModal);
  var _super = alert_createSuper(Alert);
  function Alert() {
    alert_classCallCheck(this, Alert);
    return _super.apply(this, arguments);
  }
  alert_createClass(Alert, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      alert_get(alert_getPrototypeOf(Alert.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', function () {
        return _this.render();
      });
      this.addEventListener('hide.bs.modal', function () {
        return _this.remove();
      }, false);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return templates_alert(this.model.toJSON());
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      return this.model.get('title');
    }
  }]);
  return Alert;
}(modal_modal);

shared_api.elements.define('converse-alert-modal', Alert);
;// CONCATENATED MODULE: ./src/plugins/modal/templates/prompt.js
var prompt_templateObject, prompt_templateObject2, prompt_templateObject3;
function prompt_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var tplField = function tplField(f) {
  return (0,external_lit_namespaceObject.html)(prompt_templateObject || (prompt_templateObject = prompt_taggedTemplateLiteral(["\n    <div class=\"form-group\">\n        <label>\n            ", "\n            <input type=\"text\"\n                name=\"", "\"\n                class=\"", " form-control form-control--labeled\"\n                ?required=\"", "\"\n                placeholder=\"", "\" />\n        </label>\n    </div>\n"])), f.label || '', f.name, f.challenge_failed ? 'error' : '', f.required, f.placeholder);
};
/* harmony default export */ const templates_prompt = (function (el) {
  var _el$model$get, _el$model$get2;
  return (0,external_lit_namespaceObject.html)(prompt_templateObject2 || (prompt_templateObject2 = prompt_taggedTemplateLiteral(["\n        <form class=\"converse-form converse-form--modal confirm\" action=\"#\" @submit=", ">\n            <div class=\"form-group\">\n                ", "\n            </div>\n            ", "\n            <div class=\"form-group\">\n                <button type=\"submit\" class=\"btn btn-primary\">", "</button>\n                <input type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\" value=\"", "\"/>\n            </div>\n        </form>"])), function (ev) {
    return el.onConfimation(ev);
  }, (_el$model$get = el.model.get('messages')) === null || _el$model$get === void 0 ? void 0 : _el$model$get.map(function (message) {
    return (0,external_lit_namespaceObject.html)(prompt_templateObject3 || (prompt_templateObject3 = prompt_taggedTemplateLiteral(["<p>", "</p>"])), message);
  }), (_el$model$get2 = el.model.get('fields')) === null || _el$model$get2 === void 0 ? void 0 : _el$model$get2.map(function (f) {
    return tplField(f);
  }), __('OK'), __('Cancel'));
});
;// CONCATENATED MODULE: ./src/plugins/modal/confirm.js
function confirm_typeof(obj) {
  "@babel/helpers - typeof";

  return confirm_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;
  }, confirm_typeof(obj);
}
function confirm_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function confirm_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, confirm_toPropertyKey(descriptor.key), descriptor);
  }
}
function confirm_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) confirm_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) confirm_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function confirm_toPropertyKey(arg) {
  var key = confirm_toPrimitive(arg, "string");
  return confirm_typeof(key) === "symbol" ? key : String(key);
}
function confirm_toPrimitive(input, hint) {
  if (confirm_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (confirm_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function confirm_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    confirm_get = Reflect.get.bind();
  } else {
    confirm_get = function _get(target, property, receiver) {
      var base = confirm_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return confirm_get.apply(this, arguments);
}
function confirm_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = confirm_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function confirm_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) confirm_setPrototypeOf(subClass, superClass);
}
function confirm_setPrototypeOf(o, p) {
  confirm_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return confirm_setPrototypeOf(o, p);
}
function confirm_createSuper(Derived) {
  var hasNativeReflectConstruct = confirm_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = confirm_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = confirm_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return confirm_possibleConstructorReturn(this, result);
  };
}
function confirm_possibleConstructorReturn(self, call) {
  if (call && (confirm_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 confirm_assertThisInitialized(self);
}
function confirm_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function confirm_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 confirm_getPrototypeOf(o) {
  confirm_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return confirm_getPrototypeOf(o);
}




var Confirm = /*#__PURE__*/function (_BaseModal) {
  confirm_inherits(Confirm, _BaseModal);
  var _super = confirm_createSuper(Confirm);
  function Confirm(options) {
    var _this;
    confirm_classCallCheck(this, Confirm);
    _this = _super.call(this, options);
    _this.confirmation = getOpenPromise();
    return _this;
  }
  confirm_createClass(Confirm, [{
    key: "initialize",
    value: function initialize() {
      var _this2 = this;
      confirm_get(confirm_getPrototypeOf(Confirm.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', function () {
        return _this2.render();
      });
      this.addEventListener('hide.bs.modal', function () {
        if (!_this2.confirmation.isResolved) {
          _this2.confirmation.reject();
        }
      }, false);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return templates_prompt(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      return this.model.get('title');
    }
  }, {
    key: "onConfimation",
    value: function onConfimation(ev) {
      ev.preventDefault();
      var form_data = new FormData(ev.target);
      var fields = (this.model.get('fields') || []).map(function (field) {
        var value = form_data.get(field.name).trim();
        field.value = value;
        if (field.challenge) {
          field.challenge_failed = value !== field.challenge;
        }
        return field;
      });
      if (fields.filter(function (c) {
        return c.challenge_failed;
      }).length) {
        this.model.set('fields', fields);
        // Setting an array doesn't trigger a change event
        this.model.trigger('change');
        return;
      }
      this.confirmation.resolve(fields);
      this.modal.hide();
    }
  }, {
    key: "renderModalFooter",
    value: function renderModalFooter() {
      // eslint-disable-line class-methods-use-this
      return '';
    }
  }]);
  return Confirm;
}(modal_modal);

shared_api.elements.define('converse-confirm-modal', Confirm);
;// CONCATENATED MODULE: ./src/plugins/modal/api.js
function modal_api_typeof(obj) {
  "@babel/helpers - typeof";

  return modal_api_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;
  }, modal_api_typeof(obj);
}
function modal_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  modal_api_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" == modal_api_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 modal_api_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 modal_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        modal_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        modal_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}



var modals = [];
var modals_map = {};
var modal_api = {
  /**
   * API namespace for methods relating to modals
   * @namespace _converse.api.modal
   * @memberOf _converse.api
   */
  modal: {
    /**
     * Shows a modal of type `ModalClass` to the user.
     * Will create a new instance of that class if an existing one isn't
     * found.
     * @param { Class } ModalClass
     * @param { Object } [properties] - Optional properties that will be set on a newly created modal instance.
     * @param { Event } [event] - The DOM event that causes the modal to be shown.
     */
    show: function show(name, properties, ev) {
      var modal;
      if (typeof name === 'string') {
        var _this$get;
        modal = (_this$get = this.get(name)) !== null && _this$get !== void 0 ? _this$get : this.create(name, properties);
        Object.assign(modal, properties);
      } else {
        var _ModalClass$id, _this$get2;
        // Legacy...
        var ModalClass = name;
        var id = (_ModalClass$id = ModalClass.id) !== null && _ModalClass$id !== void 0 ? _ModalClass$id : properties.id;
        modal = (_this$get2 = this.get(id)) !== null && _this$get2 !== void 0 ? _this$get2 : this.create(ModalClass, properties);
      }
      modal.show(ev);
      return modal;
    },
    /**
     * Return a modal with the passed-in identifier, if it exists.
     * @param { String } id
     */
    get: function get(id) {
      var _modals_map$id;
      return (_modals_map$id = modals_map[id]) !== null && _modals_map$id !== void 0 ? _modals_map$id : modals.filter(function (m) {
        return m.id == id;
      }).pop();
    },
    /**
     * Create a modal of the passed-in type.
     * @param { String } name
     * @param { Object } [properties] - Optional properties that will be
     *  set on the modal instance.
     */
    create: function create(name, properties) {
      var modal;
      if (typeof name === 'string') {
        var ModalClass = customElements.get(name);
        modal = modals_map[name] = new ModalClass(properties);
      } else {
        // Legacy...
        var _ModalClass = name;
        modal = new _ModalClass(properties);
        modals.push(modal);
      }
      return modal;
    },
    /**
     * Remove a particular modal
     * @param { String } name
     */
    remove: function remove(name) {
      var _modal;
      var modal;
      if (typeof name === 'string') {
        modal = modals_map[name];
        delete modals_map[name];
      } else {
        // Legacy...
        modal = name;
        modals = modals.filter(function (m) {
          return m !== modal;
        });
      }
      (_modal = modal) === null || _modal === void 0 ? void 0 : _modal.remove();
    },
    /**
     * Remove all modals
     */
    removeAll: function removeAll() {
      modals.forEach(function (m) {
        return m.remove();
      });
      modals = [];
      modals_map = {};
    }
  },
  /**
   * Show a confirm modal to the user.
   * @method _converse.api.confirm
   * @param { String } title - The header text for the confirmation dialog
   * @param { (Array<String>|String) } messages - The text to show to the user
   * @param { Array<Field> } fields - An object representing a fields presented to the user.
   * @property { String } Field.label - The form label for the input field.
   * @property { String } Field.name - The name for the input field.
   * @property { String } [Field.challenge] - A challenge value that must be provided by the user.
   * @property { String } [Field.placeholder] - The placeholder for the input field.
   * @property { Boolean} [Field.required] - Whether the field is required or not
   * @returns { Promise<Array|false> } A promise which resolves with an array of
   *  filled in fields or `false` if the confirm dialog was closed or canceled.
   */
  confirm: function confirm(title) {
    var _arguments = arguments;
    return modal_api_asyncToGenerator( /*#__PURE__*/modal_api_regeneratorRuntime().mark(function _callee() {
      var messages, fields, model, confirm, result;
      return modal_api_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            messages = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : [];
            fields = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : [];
            if (typeof messages === 'string') {
              messages = [messages];
            }
            model = new Model({
              title: title,
              messages: messages,
              fields: fields,
              'type': 'confirm'
            });
            confirm = new Confirm({
              model: model
            });
            confirm.show();
            _context.prev = 6;
            _context.next = 9;
            return confirm.confirmation;
          case 9:
            result = _context.sent;
            _context.next = 15;
            break;
          case 12:
            _context.prev = 12;
            _context.t0 = _context["catch"](6);
            result = false;
          case 15:
            confirm.remove();
            return _context.abrupt("return", result);
          case 17:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[6, 12]]);
    }))();
  },
  /**
   * Show a prompt modal to the user.
   * @method _converse.api.prompt
   * @param { String } title - The header text for the prompt
   * @param { (Array<String>|String) } messages - The prompt text to show to the user
   * @param { String } placeholder - The placeholder text for the prompt input
   * @returns { Promise<String|false> } A promise which resolves with the text provided by the
   *  user or `false` if the user canceled the prompt.
   */
  prompt: function prompt(title) {
    var _arguments2 = arguments;
    return modal_api_asyncToGenerator( /*#__PURE__*/modal_api_regeneratorRuntime().mark(function _callee2() {
      var messages, placeholder, model, prompt, result, _yield$prompt$confirm;
      return modal_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            messages = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : [];
            placeholder = _arguments2.length > 2 && _arguments2[2] !== undefined ? _arguments2[2] : '';
            if (typeof messages === 'string') {
              messages = [messages];
            }
            model = new Model({
              title: title,
              messages: messages,
              'fields': [{
                'name': 'reason',
                'placeholder': placeholder
              }],
              'type': 'prompt'
            });
            prompt = new Confirm({
              model: model
            });
            prompt.show();
            _context2.prev = 6;
            _context2.next = 9;
            return prompt.confirmation;
          case 9:
            _context2.t1 = _yield$prompt$confirm = _context2.sent.pop();
            _context2.t0 = _context2.t1 === null;
            if (_context2.t0) {
              _context2.next = 13;
              break;
            }
            _context2.t0 = _yield$prompt$confirm === void 0;
          case 13:
            if (!_context2.t0) {
              _context2.next = 17;
              break;
            }
            _context2.t2 = void 0;
            _context2.next = 18;
            break;
          case 17:
            _context2.t2 = _yield$prompt$confirm.value;
          case 18:
            result = _context2.t2;
            _context2.next = 24;
            break;
          case 21:
            _context2.prev = 21;
            _context2.t3 = _context2["catch"](6);
            result = false;
          case 24:
            prompt.remove();
            return _context2.abrupt("return", result);
          case 26:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[6, 21]]);
    }))();
  },
  /**
   * Show an alert modal to the user.
   * @method _converse.api.alert
   * @param { ('info'|'warn'|'error') } type - The type of alert.
   * @param { String } title - The header text for the alert.
   * @param { (Array<String>|String) } messages - The alert text to show to the user.
   */
  alert: function alert(type, title, messages) {
    if (typeof messages === 'string') {
      messages = [messages];
    }
    var level;
    if (type === 'error') {
      level = 'alert-danger';
    } else if (type === 'info') {
      level = 'alert-info';
    } else if (type === 'warn') {
      level = 'alert-warning';
    }
    var model = new Model({
      'title': title,
      'messages': messages,
      'level': level,
      'type': 'alert'
    });
    modal_api.modal.show('converse-alert-modal', {
      model: model
    });
  }
};
/* harmony default export */ const plugins_modal_api = (modal_api);
;// CONCATENATED MODULE: ./src/plugins/modal/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



public_converse.env.BootstrapModal = base; // expose to plugins

public_converse.plugins.add('converse-modal', {
  initialize: function initialize() {
    shared_api.listen.on('disconnect', function () {
      var container = document.querySelector("#converse-modals");
      if (container) {
        container.innerHTML = '';
      }
    });
    shared_api.listen.on('clearSession', function () {
      return shared_api.modal.removeAll();
    });
    Object.assign(shared_converse.api, plugins_modal_api);
  }
});
;// CONCATENATED MODULE: ./src/shared/autocomplete/utils.js

var autocomplete_utils_u = public_converse.env.utils;
var utils_helpers = {
  getElement: function getElement(expr, el) {
    return typeof expr === 'string' ? (el || document).querySelector(expr) : expr || null;
  },
  bind: function bind(element, o) {
    if (element) {
      var _loop = function _loop() {
        if (!Object.prototype.hasOwnProperty.call(o, event)) {
          return "continue";
        }
        var callback = o[event];
        event.split(/\s+/).forEach(function (event) {
          return element.addEventListener(event, callback);
        });
      };
      for (var event in o) {
        var _ret = _loop();
        if (_ret === "continue") continue;
      }
    }
  },
  unbind: function unbind(element, o) {
    if (element) {
      var _loop2 = function _loop2() {
        if (!Object.prototype.hasOwnProperty.call(o, event)) {
          return "continue";
        }
        var callback = o[event];
        event.split(/\s+/).forEach(function (event) {
          return element.removeEventListener(event, callback);
        });
      };
      for (var event in o) {
        var _ret2 = _loop2();
        if (_ret2 === "continue") continue;
      }
    }
  },
  regExpEscape: function regExpEscape(s) {
    return s.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&');
  },
  isMention: function isMention(word, ac_triggers) {
    return ac_triggers.includes(word[0]) || autocomplete_utils_u.isMentionBoundary(word[0]) && ac_triggers.includes(word[1]);
  }
};
var FILTER_CONTAINS = function FILTER_CONTAINS(text, input) {
  return RegExp(utils_helpers.regExpEscape(input.trim()), 'i').test(text);
};
var FILTER_STARTSWITH = function FILTER_STARTSWITH(text, input) {
  return RegExp('^' + utils_helpers.regExpEscape(input.trim()), 'i').test(text);
};
var SORT_BY_LENGTH = function SORT_BY_LENGTH(a, b) {
  if (a.length !== b.length) {
    return a.length - b.length;
  }
  return a < b ? -1 : 1;
};
var SORT_BY_QUERY_POSITION = function SORT_BY_QUERY_POSITION(a, b) {
  var query = a.query.toLowerCase();
  var x = a.label.toLowerCase().indexOf(query);
  var y = b.label.toLowerCase().indexOf(query);
  if (x === y) {
    return SORT_BY_LENGTH(a, b);
  }
  return (x === -1 ? Infinity : x) < (y === -1 ? Infinity : y) ? -1 : 1;
};
var ITEM = function ITEM(text, input) {
  input = input.trim();
  var element = document.createElement('li');
  element.setAttribute('aria-selected', 'false');
  var regex = new RegExp('(' + input + ')', 'ig');
  var parts = input ? text.split(regex) : [text];
  parts.forEach(function (txt) {
    if (input && txt.match(regex)) {
      var match = document.createElement('mark');
      match.textContent = txt;
      element.appendChild(match);
    } else {
      element.appendChild(document.createTextNode(txt));
    }
  });
  return element;
};
;// CONCATENATED MODULE: ./src/shared/autocomplete/suggestion.js
function suggestion_typeof(obj) {
  "@babel/helpers - typeof";

  return suggestion_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;
  }, suggestion_typeof(obj);
}
function suggestion_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function suggestion_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, suggestion_toPropertyKey(descriptor.key), descriptor);
  }
}
function suggestion_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) suggestion_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) suggestion_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function suggestion_toPropertyKey(arg) {
  var key = suggestion_toPrimitive(arg, "string");
  return suggestion_typeof(key) === "symbol" ? key : String(key);
}
function suggestion_toPrimitive(input, hint) {
  if (suggestion_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (suggestion_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function suggestion_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) suggestion_setPrototypeOf(subClass, superClass);
}
function suggestion_createSuper(Derived) {
  var hasNativeReflectConstruct = suggestion_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = suggestion_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = suggestion_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return suggestion_possibleConstructorReturn(this, result);
  };
}
function suggestion_possibleConstructorReturn(self, call) {
  if (call && (suggestion_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 suggestion_assertThisInitialized(self);
}
function suggestion_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function suggestion_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  suggestion_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !suggestion_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return suggestion_construct(Class, arguments, suggestion_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return suggestion_setPrototypeOf(Wrapper, Class);
  };
  return suggestion_wrapNativeSuper(Class);
}
function suggestion_construct(Parent, args, Class) {
  if (suggestion_isNativeReflectConstruct()) {
    suggestion_construct = Reflect.construct.bind();
  } else {
    suggestion_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) suggestion_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return suggestion_construct.apply(null, arguments);
}
function suggestion_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 suggestion_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function suggestion_setPrototypeOf(o, p) {
  suggestion_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return suggestion_setPrototypeOf(o, p);
}
function suggestion_getPrototypeOf(o) {
  suggestion_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return suggestion_getPrototypeOf(o);
}
/**
 * An autocomplete suggestion
 */
var Suggestion = /*#__PURE__*/function (_String) {
  suggestion_inherits(Suggestion, _String);
  var _super = suggestion_createSuper(Suggestion);
  /**
   * @param { Any } data - The auto-complete data. Ideally an object e.g. { label, value },
   *      which specifies the value and human-presentable label of the suggestion.
   * @param { string } query - The query string being auto-completed
   */
  function Suggestion(data, query) {
    var _this;
    suggestion_classCallCheck(this, Suggestion);
    _this = _super.call(this);
    var o = Array.isArray(data) ? {
      label: data[0],
      value: data[1]
    } : suggestion_typeof(data) === 'object' && 'label' in data && 'value' in data ? data : {
      label: data,
      value: data
    };
    _this.label = o.label || o.value;
    _this.value = o.value;
    _this.query = query;
    return _this;
  }
  suggestion_createClass(Suggestion, [{
    key: "lenth",
    get: function get() {
      return this.label.length;
    }
  }, {
    key: "toString",
    value: function toString() {
      return '' + this.label;
    }
  }, {
    key: "valueOf",
    value: function valueOf() {
      return this.toString();
    }
  }]);
  return Suggestion;
}( /*#__PURE__*/suggestion_wrapNativeSuper(String));
/* harmony default export */ const suggestion = (Suggestion);
;// CONCATENATED MODULE: ./src/shared/autocomplete/autocomplete.js
function autocomplete_typeof(obj) {
  "@babel/helpers - typeof";

  return autocomplete_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;
  }, autocomplete_typeof(obj);
}
function autocomplete_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  autocomplete_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" == autocomplete_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 autocomplete_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 autocomplete_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        autocomplete_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        autocomplete_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function autocomplete_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function autocomplete_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, autocomplete_toPropertyKey(descriptor.key), descriptor);
  }
}
function autocomplete_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) autocomplete_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) autocomplete_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function autocomplete_toPropertyKey(arg) {
  var key = autocomplete_toPrimitive(arg, "string");
  return autocomplete_typeof(key) === "symbol" ? key : String(key);
}
function autocomplete_toPrimitive(input, hint) {
  if (autocomplete_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (autocomplete_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/**
 * @copyright Lea Verou and the Converse.js contributors
 * @description
 *  Started as a fork of Lea Verou's "Awesomplete"
 *  https://leaverou.github.io/awesomplete/
 * @license Mozilla Public License (MPLv2)
 */





var autocomplete_u = public_converse.env.utils;
var AutoComplete = /*#__PURE__*/function () {
  function AutoComplete(el) {
    var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    autocomplete_classCallCheck(this, AutoComplete);
    this.suggestions = [];
    this.is_opened = false;
    if (autocomplete_u.hasClass('suggestion-box', el)) {
      this.container = el;
    } else {
      this.container = el.querySelector('.suggestion-box');
    }
    this.input = this.container.querySelector('.suggestion-box__input');
    this.input.setAttribute("aria-autocomplete", "list");
    this.ul = this.container.querySelector('.suggestion-box__results');
    this.status = this.container.querySelector('.suggestion-box__additions');
    Object.assign(this, {
      'match_current_word': false,
      // Match only the current word, otherwise all input is matched
      'ac_triggers': [],
      // Array of keys (`ev.key`) values that will trigger auto-complete
      'include_triggers': [],
      // Array of trigger keys which should be included in the returned value
      'min_chars': 2,
      'max_items': 10,
      'auto_evaluate': true,
      // Should evaluation happen automatically without any particular key as trigger?
      'auto_first': false,
      // Should the first element be automatically selected?
      'data': function data(a) {
        return a;
      },
      'filter': FILTER_CONTAINS,
      'sort': config.sort === false ? false : SORT_BY_QUERY_POSITION,
      'item': ITEM
    }, config);
    this.index = -1;
    this.bindEvents();
    if (this.input.hasAttribute("list")) {
      this.list = "#" + this.input.getAttribute("list");
      this.input.removeAttribute("list");
    } else {
      this.list = this.input.getAttribute("data-list") || config.list || [];
    }
  }
  autocomplete_createClass(AutoComplete, [{
    key: "bindEvents",
    value: function bindEvents() {
      var _this = this;
      var input = {
        "blur": function blur() {
          return _this.close({
            'reason': 'blur'
          });
        }
      };
      if (this.auto_evaluate) {
        input["input"] = function (e) {
          return _this.evaluate(e);
        };
      }
      this._events = {
        'input': input,
        'form': {
          "submit": function submit() {
            return _this.close({
              'reason': 'submit'
            });
          }
        },
        'ul': {
          "mousedown": function mousedown(ev) {
            return _this.onMouseDown(ev);
          },
          "mouseover": function mouseover(ev) {
            return _this.onMouseOver(ev);
          }
        }
      };
      utils_helpers.bind(this.input, this._events.input);
      utils_helpers.bind(this.input.form, this._events.form);
      utils_helpers.bind(this.ul, this._events.ul);
    }
  }, {
    key: "list",
    get: function get() {
      return this._list;
    },
    set: function set(list) {
      if (Array.isArray(list) || typeof list === "function") {
        this._list = list;
      } else if (typeof list === "string" && list.includes(",")) {
        this._list = list.split(/\s*,\s*/);
      } else {
        var _helpers$getElement;
        // Element or CSS selector
        var children = ((_helpers$getElement = utils_helpers.getElement(list)) === null || _helpers$getElement === void 0 ? void 0 : _helpers$getElement.children) || [];
        this._list = Array.from(children).filter(function (el) {
          return !el.disabled;
        }).map(function (el) {
          var text = el.textContent.trim();
          var value = el.value || text;
          var label = el.label || text;
          return value !== "" ? {
            label: label,
            value: value
          } : null;
        }).filter(function (i) {
          return i;
        });
      }
      if (document.activeElement === this.input) {
        this.evaluate();
      }
    }
  }, {
    key: "selected",
    get: function get() {
      return this.index > -1;
    }
  }, {
    key: "opened",
    get: function get() {
      return this.is_opened;
    }
  }, {
    key: "close",
    value: function close(o) {
      if (!this.opened) {
        return;
      }
      this.ul.setAttribute("hidden", "");
      this.is_opened = false;
      this.index = -1;
      this.trigger("suggestion-box-close", o || {});
    }
  }, {
    key: "insertValue",
    value: function insertValue(suggestion) {
      if (this.match_current_word) {
        autocomplete_u.replaceCurrentWord(this.input, suggestion.value);
      } else {
        this.input.value = suggestion.value;
      }
    }
  }, {
    key: "open",
    value: function open() {
      this.ul.removeAttribute("hidden");
      this.is_opened = true;
      if (this.auto_first && this.index === -1) {
        this.goto(0);
      }
      this.trigger("suggestion-box-open");
    }
  }, {
    key: "destroy",
    value: function destroy() {
      //remove events from the input and its form
      utils_helpers.unbind(this.input, this._events.input);
      utils_helpers.unbind(this.input.form, this._events.form);
      this.input.removeAttribute("aria-autocomplete");
    }
  }, {
    key: "next",
    value: function next() {
      var count = this.ul.children.length;
      this.goto(this.index < count - 1 ? this.index + 1 : count ? 0 : -1);
    }
  }, {
    key: "previous",
    value: function previous() {
      var count = this.ul.children.length,
        pos = this.index - 1;
      this.goto(this.selected && pos !== -1 ? pos : count - 1);
    }
  }, {
    key: "goto",
    value: function goto(i) {
      var scroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      // Should not be used directly, highlights specific item without any checks!
      var list = this.ul.children;
      if (this.selected) {
        list[this.index].setAttribute("aria-selected", "false");
      }
      this.index = i;
      if (i > -1 && list.length > 0) {
        list[i].setAttribute("aria-selected", "true");
        list[i].focus();
        this.status.textContent = list[i].textContent;
        if (scroll) {
          // scroll to highlighted element in case parent's height is fixed
          this.ul.scrollTop = list[i].offsetTop - this.ul.clientHeight + list[i].clientHeight;
        }
        this.trigger("suggestion-box-highlight", {
          'text': this.suggestions[this.index]
        });
      }
    }
  }, {
    key: "select",
    value: function select(selected) {
      if (selected) {
        this.index = autocomplete_u.siblingIndex(selected);
      } else {
        selected = this.ul.children[this.index];
      }
      if (selected) {
        var suggestion = this.suggestions[this.index];
        this.insertValue(suggestion);
        this.close({
          'reason': 'select'
        });
        this.auto_completing = false;
        this.trigger("suggestion-box-selectcomplete", {
          'text': suggestion
        });
      }
    }
  }, {
    key: "onMouseOver",
    value: function onMouseOver(ev) {
      var li = autocomplete_u.ancestor(ev.target, 'li');
      if (li) {
        var index = Array.prototype.slice.call(this.ul.children).indexOf(li);
        this.goto(index, false);
      }
    }
  }, {
    key: "onMouseDown",
    value: function onMouseDown(ev) {
      if (ev.button !== 0) {
        return; // Only select on left click
      }

      var li = autocomplete_u.ancestor(ev.target, 'li');
      if (li) {
        ev.preventDefault();
        this.select(li, ev.target);
      }
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(ev) {
      if (this.opened) {
        if ([public_converse.keycodes.ENTER, public_converse.keycodes.TAB].includes(ev.keyCode) && this.selected) {
          ev.preventDefault();
          ev.stopPropagation();
          this.select();
          return true;
        } else if (ev.keyCode === public_converse.keycodes.ESCAPE) {
          this.close({
            'reason': 'esc'
          });
          return true;
        } else if ([public_converse.keycodes.UP_ARROW, public_converse.keycodes.DOWN_ARROW].includes(ev.keyCode)) {
          ev.preventDefault();
          ev.stopPropagation();
          this[ev.keyCode === public_converse.keycodes.UP_ARROW ? "previous" : "next"]();
          return true;
        }
      }
      if ([public_converse.keycodes.SHIFT, public_converse.keycodes.META, public_converse.keycodes.META_RIGHT, public_converse.keycodes.ESCAPE, public_converse.keycodes.ALT].includes(ev.keyCode)) {
        return;
      }
      if (this.ac_triggers.includes(ev.key)) {
        if (ev.key === "Tab") {
          ev.preventDefault();
        }
        this.auto_completing = true;
      } else if (ev.key === "Backspace") {
        var word = autocomplete_u.getCurrentWord(ev.target, ev.target.selectionEnd - 1);
        if (utils_helpers.isMention(word, this.ac_triggers)) {
          this.auto_completing = true;
        }
      }
    }
  }, {
    key: "evaluate",
    value: function () {
      var _evaluate = autocomplete_asyncToGenerator( /*#__PURE__*/autocomplete_regeneratorRuntime().mark(function _callee(ev) {
        var _this2 = this;
        var selecting, value, contains_trigger, is_long_enough, list;
        return autocomplete_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              selecting = this.selected && ev && (ev.keyCode === public_converse.keycodes.UP_ARROW || ev.keyCode === public_converse.keycodes.DOWN_ARROW);
              if (!(!this.auto_evaluate && !this.auto_completing || selecting)) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return");
            case 3:
              value = this.match_current_word ? autocomplete_u.getCurrentWord(this.input) : this.input.value;
              contains_trigger = utils_helpers.isMention(value, this.ac_triggers);
              if (contains_trigger && !this.include_triggers.includes(ev.key)) {
                value = autocomplete_u.isMentionBoundary(value[0]) ? value.slice('2') : value.slice('1');
              }
              is_long_enough = value.length && value.length >= this.min_chars;
              if (!(contains_trigger || is_long_enough)) {
                _context.next = 29;
                break;
              }
              this.auto_completing = true;
              if (!(typeof this._list === "function")) {
                _context.next = 15;
                break;
              }
              _context.next = 12;
              return this._list(value);
            case 12:
              _context.t0 = _context.sent;
              _context.next = 16;
              break;
            case 15:
              _context.t0 = this._list;
            case 16:
              list = _context.t0;
              if (!(list.length === 0 || !this.auto_completing)) {
                _context.next = 20;
                break;
              }
              this.close({
                'reason': 'nomatches'
              });
              return _context.abrupt("return");
            case 20:
              this.index = -1;
              this.ul.innerHTML = "";
              this.suggestions = list.map(function (item) {
                return new suggestion(_this2.data(item, value), value);
              }).filter(function (item) {
                return _this2.filter(item, value);
              });
              if (this.sort !== false) {
                this.suggestions = this.suggestions.sort(this.sort);
              }
              this.suggestions = this.suggestions.slice(0, this.max_items);
              this.suggestions.forEach(function (text) {
                return _this2.ul.appendChild(_this2.item(text, value));
              });
              if (this.ul.children.length === 0) {
                this.close({
                  'reason': 'nomatches'
                });
              } else {
                this.open();
              }
              _context.next = 31;
              break;
            case 29:
              this.close({
                'reason': 'nomatches'
              });
              if (!contains_trigger) {
                this.auto_completing = false;
              }
            case 31:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function evaluate(_x) {
        return _evaluate.apply(this, arguments);
      }
      return evaluate;
    }()
  }]);
  return AutoComplete;
}();

// Make it an event emitter
Object.assign(AutoComplete.prototype, Events);
/* harmony default export */ const autocomplete = (AutoComplete);
;// CONCATENATED MODULE: ./src/shared/autocomplete/component.js
function component_typeof(obj) {
  "@babel/helpers - typeof";

  return component_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;
  }, component_typeof(obj);
}
var component_templateObject;
function component_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function component_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function component_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, component_toPropertyKey(descriptor.key), descriptor);
  }
}
function component_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) component_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) component_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function component_toPropertyKey(arg) {
  var key = component_toPrimitive(arg, "string");
  return component_typeof(key) === "symbol" ? key : String(key);
}
function component_toPrimitive(input, hint) {
  if (component_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (component_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function component_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) component_setPrototypeOf(subClass, superClass);
}
function component_setPrototypeOf(o, p) {
  component_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return component_setPrototypeOf(o, p);
}
function component_createSuper(Derived) {
  var hasNativeReflectConstruct = component_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = component_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = component_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return component_possibleConstructorReturn(this, result);
  };
}
function component_possibleConstructorReturn(self, call) {
  if (call && (component_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 component_assertThisInitialized(self);
}
function component_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function component_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 component_getPrototypeOf(o) {
  component_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return component_getPrototypeOf(o);
}






/**
 * A custom element that can be used to add auto-completion suggestions to a form input.
 * @class AutoCompleteComponent
 *
 * @property { "above" | "below" } [position="above"]
 *  Should the autocomplete list show above or below the input element?
 * @property { Boolean } [autofocus=false]
 *  Should the `focus` attribute be set on the input element?
 * @property { Function } getAutoCompleteList
 *  A function that returns the list of autocomplete suggestions
 * @property { Array } list
 *  An array of suggestions, to be used instead of the `getAutoCompleteList` *  function
 * @property { Boolean } [auto_evaluate=true]
 *  Should evaluation happen automatically without any particular key as trigger?
 * @property { Boolean } [auto_first=false]
 *  Should the first element automatically be selected?
 * @property { "contains" | "startswith" } [filter="contains"]
 *  Provide matches which contain the entered text, or which starts with the entered text
 * @property { String } [include_triggers=""]
 *  Space separated characters which should be included in the returned value
 * @property { Number } [min_chars=1]
 *  The minimum number of characters to be entered into the input before autocomplete starts.
 * @property { String } [name]
 *  The `name` attribute of the `input` element
 * @property { String } [placeholder]
 *  The `placeholder` attribute of the `input` element
 * @property { String } [triggers]
 *  String of space separated characters which trigger autocomplete
 *
 * @example
 *     <converse-autocomplete
 *         .getAutoCompleteList="${getAutoCompleteList}"
 *         placeholder="${placeholder_text}"
 *         name="foo">
 *     </converse-autocomplete>
 */
var AutoCompleteComponent = /*#__PURE__*/function (_CustomElement) {
  component_inherits(AutoCompleteComponent, _CustomElement);
  var _super = component_createSuper(AutoCompleteComponent);
  function AutoCompleteComponent() {
    var _this;
    component_classCallCheck(this, AutoCompleteComponent);
    _this = _super.call(this);
    _this.position = 'above';
    _this.auto_evaluate = true;
    _this.auto_first = false;
    _this.filter = 'contains';
    _this.include_triggers = '';
    _this.match_current_word = false; // Match only the current word, otherwise all input is matched
    _this.max_items = 10;
    _this.min_chars = 1;
    _this.triggers = '';
    return _this;
  }
  component_createClass(AutoCompleteComponent, [{
    key: "render",
    value: function render() {
      var position_class = "suggestion-box__results--".concat(this.position);
      return (0,external_lit_namespaceObject.html)(component_templateObject || (component_templateObject = component_taggedTemplateLiteral(["\n            <div class=\"suggestion-box suggestion-box__name\">\n                <ul class=\"suggestion-box__results ", "\" hidden=\"\"></ul>\n                <input\n                    ?autofocus=", "\n                    ?required=", "\n                    type=\"text\"\n                    name=\"", "\"\n                    autocomplete=\"off\"\n                    @keydown=", "\n                    @keyup=", "\n                    class=\"form-control suggestion-box__input\"\n                    placeholder=\"", "\"\n                />\n                <span\n                    class=\"suggestion-box__additions visually-hidden\"\n                    role=\"status\"\n                    aria-live=\"assertive\"\n                    aria-relevant=\"additions\"\n                ></span>\n            </div>\n        "])), position_class, this.autofocus, this.required, this.name, this.onKeyDown, this.onKeyUp, this.placeholder);
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      var _this$list,
        _this2 = this;
      this.auto_complete = new autocomplete(this.firstElementChild, {
        'ac_triggers': this.triggers.split(' '),
        'auto_evaluate': this.auto_evaluate,
        'auto_first': this.auto_first,
        'filter': this.filter == 'contains' ? FILTER_CONTAINS : FILTER_STARTSWITH,
        'include_triggers': [],
        'list': (_this$list = this.list) !== null && _this$list !== void 0 ? _this$list : function (q) {
          return _this2.getAutoCompleteList(q);
        },
        'match_current_word': true,
        'max_items': this.max_items,
        'min_chars': this.min_chars
      });
      this.auto_complete.on('suggestion-box-selectcomplete', function () {
        return _this2.auto_completing = false;
      });
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(ev) {
      this.auto_complete.onKeyDown(ev);
    }
  }, {
    key: "onKeyUp",
    value: function onKeyUp(ev) {
      this.auto_complete.evaluate(ev);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'position': {
          type: String
        },
        'autofocus': {
          type: Boolean
        },
        'getAutoCompleteList': {
          type: Function
        },
        'list': {
          type: Array
        },
        'auto_evaluate': {
          type: Boolean
        },
        'auto_first': {
          type: Boolean
        },
        'filter': {
          type: String
        },
        'include_triggers': {
          type: String
        },
        'min_chars': {
          type: Number
        },
        'name': {
          type: String
        },
        'placeholder': {
          type: String
        },
        'triggers': {
          type: String
        },
        'required': {
          type: Boolean
        }
      };
    }
  }]);
  return AutoCompleteComponent;
}(CustomElement);

shared_api.elements.define('converse-autocomplete', AutoCompleteComponent);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/autocomplete/styles/_autocomplete.scss
var _autocomplete = __webpack_require__(8799);
;// CONCATENATED MODULE: ./src/shared/autocomplete/styles/_autocomplete.scss

      
      
      
      
      
      
      
      
      

var _autocomplete_options = {};

_autocomplete_options.styleTagTransform = (styleTagTransform_default());
_autocomplete_options.setAttributes = (setAttributesWithoutAttributes_default());

      _autocomplete_options.insert = insertBySelector_default().bind(null, "head");
    
_autocomplete_options.domAPI = (styleDomAPI_default());
_autocomplete_options.insertStyleElement = (insertStyleElement_default());

var _autocomplete_update = injectStylesIntoStyleTag_default()(_autocomplete/* default */.Z, _autocomplete_options);




       /* harmony default export */ const styles_autocomplete = (_autocomplete/* default */.Z && _autocomplete/* default */.Z.locals ? _autocomplete/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/autocomplete/index.js





shared_converse.FILTER_CONTAINS = FILTER_CONTAINS;
shared_converse.FILTER_STARTSWITH = FILTER_STARTSWITH;
shared_converse.AutoComplete = autocomplete;
;// CONCATENATED MODULE: ./src/plugins/adhoc-views/templates/ad-hoc-command-form.js
var ad_hoc_command_form_templateObject, ad_hoc_command_form_templateObject2, ad_hoc_command_form_templateObject3;
function ad_hoc_command_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var action_map = {
  execute: __('Execute'),
  prev: __('Previous'),
  next: __('Next'),
  complete: __('Complete')
};
/* harmony default export */ const ad_hoc_command_form = (function (el, command) {
  var i18n_cancel = __('Cancel');
  return (0,external_lit_namespaceObject.html)(ad_hoc_command_form_templateObject || (ad_hoc_command_form_templateObject = ad_hoc_command_form_taggedTemplateLiteral(["\n        <span> <!-- Don't remove this <span>,\n                    this is a workaround for a lit bug where a <form> cannot be removed\n                    if it contains an <input> with name \"remove\" -->\n            <form>\n            ", "\n            <fieldset class=\"form-group\">\n                <input type=\"hidden\" name=\"command_node\" value=\"", "\"/>\n                <input type=\"hidden\" name=\"command_jid\" value=\"", "\"/>\n\n                <p class=\"form-instructions\">", "</p>\n                ", "\n            </fieldset>\n            <fieldset>\n                ", "<input type=\"button\"\n                       class=\"btn btn-secondary button-cancel\"\n                       value=\"", "\"\n                       @click=", ">\n            </fieldset>\n        </form>\n        </span>\n    "])), command.alert ? (0,external_lit_namespaceObject.html)(ad_hoc_command_form_templateObject2 || (ad_hoc_command_form_templateObject2 = ad_hoc_command_form_taggedTemplateLiteral(["<div class=\"alert alert-", "\" role=\"alert\">", "</div>"])), command.alert_type, command.alert) : '', command.node, command.jid, command.instructions, command.fields, command.actions.map(function (action) {
    return (0,external_lit_namespaceObject.html)(ad_hoc_command_form_templateObject3 || (ad_hoc_command_form_templateObject3 = ad_hoc_command_form_taggedTemplateLiteral(["<input data-action=\"", "\"\n                        @click=", "\n                        type=\"button\"\n                        class=\"btn btn-primary\"\n                        value=\"", "\">"])), action, function (ev) {
      return el.executeAction(ev);
    }, action_map[action]);
  }), i18n_cancel, function (ev) {
    return el.cancel(ev);
  });
});
;// CONCATENATED MODULE: ./src/plugins/adhoc-views/templates/ad-hoc-command.js
var ad_hoc_command_templateObject;
function ad_hoc_command_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const ad_hoc_command = (function (el, command) {
  return (0,external_lit_namespaceObject.html)(ad_hoc_command_templateObject || (ad_hoc_command_templateObject = ad_hoc_command_taggedTemplateLiteral(["\n    <li class=\"room-item list-group-item\">\n        <div class=\"available-chatroom d-flex flex-row\">\n            <a class=\"open-room available-room w-100\"\n               @click=", "\n               data-command-node=\"", "\"\n               data-command-jid=\"", "\"\n               data-command-name=\"", "\"\n               title=\"", "\"\n               href=\"#\">", "</a>\n        </div>\n        ", "\n    </li>\n"])), function (ev) {
    return el.toggleCommandForm(ev);
  }, command.node, command.jid, command.name, command.name, command.name || command.jid, command.node === el.showform ? ad_hoc_command_form(el, command) : '');
});
;// CONCATENATED MODULE: ./src/templates/spinner.js
var spinner_templateObject, spinner_templateObject2;
function spinner_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const spinner = (function () {
  var _o$classes;
  var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  if ((_o$classes = o.classes) !== null && _o$classes !== void 0 && _o$classes.includes('hor_centered')) {
    return (0,external_lit_namespaceObject.html)(spinner_templateObject || (spinner_templateObject = spinner_taggedTemplateLiteral(["<div class=\"spinner__container\"><converse-icon size=\"1em\" class=\"fa fa-spinner spinner centered ", "\"></converse-icon></div>"])), o.classes || '');
  } else {
    return (0,external_lit_namespaceObject.html)(spinner_templateObject2 || (spinner_templateObject2 = spinner_taggedTemplateLiteral(["<converse-icon size=\"1em\" class=\"fa fa-spinner spinner centered ", "\"></converse-icon>"])), o.classes || '');
  }
});
;// CONCATENATED MODULE: ./src/shared/avatar/templates/avatar.js
var avatar_templateObject;
function avatar_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

var getImgHref = function getImgHref(image, image_type) {
  return image.startsWith('data:') ? image : "data:".concat(image_type, ";base64,").concat(image);
};
/* harmony default export */ const avatar = (function (o) {
  if (o.image) {
    return (0,external_lit_namespaceObject.html)(avatar_templateObject || (avatar_templateObject = avatar_taggedTemplateLiteral(["\n            <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"avatar ", "\" width=\"", "\" height=\"", "\">\n                <image width=\"", "\" height=\"", "\" preserveAspectRatio=\"xMidYMid meet\" href=\"", "\"/>\n            </svg>"])), o.classes, o.width, o.height, o.width, o.height, getImgHref(o.image, o.image_type));
  } else {
    return '';
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/avatar/avatar.scss
var avatar_avatar = __webpack_require__(6486);
;// CONCATENATED MODULE: ./src/shared/avatar/avatar.scss

      
      
      
      
      
      
      
      
      

var avatar_options = {};

avatar_options.styleTagTransform = (styleTagTransform_default());
avatar_options.setAttributes = (setAttributesWithoutAttributes_default());

      avatar_options.insert = insertBySelector_default().bind(null, "head");
    
avatar_options.domAPI = (styleDomAPI_default());
avatar_options.insertStyleElement = (insertStyleElement_default());

var avatar_update = injectStylesIntoStyleTag_default()(avatar_avatar/* default */.Z, avatar_options);




       /* harmony default export */ const shared_avatar_avatar = (avatar_avatar/* default */.Z && avatar_avatar/* default */.Z.locals ? avatar_avatar/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/avatar/avatar.js
function avatar_typeof(obj) {
  "@babel/helpers - typeof";

  return avatar_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;
  }, avatar_typeof(obj);
}
function avatar_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function avatar_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, avatar_toPropertyKey(descriptor.key), descriptor);
  }
}
function avatar_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) avatar_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) avatar_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function avatar_toPropertyKey(arg) {
  var key = avatar_toPrimitive(arg, "string");
  return avatar_typeof(key) === "symbol" ? key : String(key);
}
function avatar_toPrimitive(input, hint) {
  if (avatar_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (avatar_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function avatar_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) avatar_setPrototypeOf(subClass, superClass);
}
function avatar_setPrototypeOf(o, p) {
  avatar_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return avatar_setPrototypeOf(o, p);
}
function avatar_createSuper(Derived) {
  var hasNativeReflectConstruct = avatar_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = avatar_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = avatar_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return avatar_possibleConstructorReturn(this, result);
  };
}
function avatar_possibleConstructorReturn(self, call) {
  if (call && (avatar_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 avatar_assertThisInitialized(self);
}
function avatar_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function avatar_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 avatar_getPrototypeOf(o) {
  avatar_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return avatar_getPrototypeOf(o);
}




var Avatar = /*#__PURE__*/function (_CustomElement) {
  avatar_inherits(Avatar, _CustomElement);
  var _super = avatar_createSuper(Avatar);
  function Avatar() {
    var _this;
    avatar_classCallCheck(this, Avatar);
    _this = _super.call(this);
    _this.width = 36;
    _this.height = 36;
    return _this;
  }
  avatar_createClass(Avatar, [{
    key: "render",
    value: function render() {
      var _this$data, _this$data2;
      var image_type = ((_this$data = this.data) === null || _this$data === void 0 ? void 0 : _this$data.image_type) || shared_converse.DEFAULT_IMAGE_TYPE;
      var image;
      if ((_this$data2 = this.data) !== null && _this$data2 !== void 0 && _this$data2.data_uri) {
        var _this$data3;
        image = (_this$data3 = this.data) === null || _this$data3 === void 0 ? void 0 : _this$data3.data_uri;
      } else {
        var _this$data4;
        var image_data = ((_this$data4 = this.data) === null || _this$data4 === void 0 ? void 0 : _this$data4.image) || shared_converse.DEFAULT_IMAGE;
        image = "data:" + image_type + ";base64," + image_data;
      }
      return avatar({
        'classes': this.getAttribute('class'),
        'height': this.height,
        'width': this.width,
        image: image,
        image_type: image_type
      });
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        data: {
          type: Object
        },
        width: {
          type: String
        },
        height: {
          type: String
        },
        nonce: {
          type: String
        } // Used to trigger rerenders
      };
    }
  }]);

  return Avatar;
}(CustomElement);

shared_api.elements.define('converse-avatar', Avatar);
;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/lit-html.js
var _t$litHtmlVersions;
function lit_html_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) lit_html_setPrototypeOf(subClass, superClass);
}
function lit_html_setPrototypeOf(o, p) {
  lit_html_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return lit_html_setPrototypeOf(o, p);
}
function lit_html_createSuper(Derived) {
  var hasNativeReflectConstruct = lit_html_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = lit_html_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = lit_html_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return lit_html_possibleConstructorReturn(this, result);
  };
}
function lit_html_possibleConstructorReturn(self, call) {
  if (call && (lit_html_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 lit_html_assertThisInitialized(self);
}
function lit_html_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function lit_html_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 lit_html_getPrototypeOf(o) {
  lit_html_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return lit_html_getPrototypeOf(o);
}
function _createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = lit_html_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(_e4) {
          throw _e4;
        },
        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(_e5) {
      didErr = true;
      err = _e5;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}
function lit_html_toConsumableArray(arr) {
  return lit_html_arrayWithoutHoles(arr) || lit_html_iterableToArray(arr) || lit_html_unsupportedIterableToArray(arr) || lit_html_nonIterableSpread();
}
function lit_html_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function lit_html_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function lit_html_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return lit_html_arrayLikeToArray(arr);
}
function lit_html_slicedToArray(arr, i) {
  return lit_html_arrayWithHoles(arr) || lit_html_iterableToArrayLimit(arr, i) || lit_html_unsupportedIterableToArray(arr, i) || lit_html_nonIterableRest();
}
function lit_html_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function lit_html_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return lit_html_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 lit_html_arrayLikeToArray(o, minLen);
}
function lit_html_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 lit_html_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function lit_html_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function lit_html_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function lit_html_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, lit_html_toPropertyKey(descriptor.key), descriptor);
  }
}
function lit_html_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) lit_html_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) lit_html_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function lit_html_toPropertyKey(arg) {
  var key = lit_html_toPrimitive(arg, "string");
  return lit_html_typeof(key) === "symbol" ? key : String(key);
}
function lit_html_toPrimitive(input, hint) {
  if (lit_html_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (lit_html_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function lit_html_typeof(obj) {
  "@babel/helpers - typeof";

  return lit_html_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;
  }, lit_html_typeof(obj);
}
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var t = globalThis,
  lit_html_i = t.trustedTypes,
  s = lit_html_i ? lit_html_i.createPolicy("lit-html", {
    createHTML: function createHTML(t) {
      return t;
    }
  }) : void 0,
  e = "$lit$",
  h = "lit$".concat(Math.random().toFixed(9).slice(2), "$"),
  o = "?" + h,
  n = "<".concat(o, ">"),
  r = document,
  l = function l() {
    return r.createComment("");
  },
  c = function c(t) {
    return null === t || "object" != lit_html_typeof(t) && "function" != typeof t;
  },
  a = Array.isArray,
  lit_html_u = function u(t) {
    return a(t) || "function" == typeof (t === null || t === void 0 ? void 0 : t[Symbol.iterator]);
  },
  d = "[ \t\n\f\r]",
  f = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
  v = /-->/g,
  _ = />/g,
  m = RegExp(">|".concat(d, "(?:([^\\s\"'>=/]+)(").concat(d, "*=").concat(d, "*(?:[^ \t\n\f\r\"'`<>=]|(\"|')|))|$)"), "g"),
  p = /'/g,
  g = /"/g,
  $ = /^(?:script|style|textarea|title)$/i,
  y = function y(t) {
    return function (i) {
      for (var _len = arguments.length, s = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        s[_key - 1] = arguments[_key];
      }
      return {
        _$litType$: t,
        strings: i,
        values: s
      };
    };
  },
  x = y(1),
  b = y(2),
  w = y(3),
  T = Symbol.for("lit-noChange"),
  E = Symbol.for("lit-nothing"),
  A = new WeakMap(),
  C = r.createTreeWalker(r, 129);
function P(t, i) {
  if (!a(t) || !t.hasOwnProperty("raw")) throw Error("invalid template strings array");
  return void 0 !== s ? s.createHTML(i) : i;
}
var V = function V(t, i) {
  var s = t.length - 1,
    o = [];
  var r,
    l = 2 === i ? "<svg>" : 3 === i ? "<math>" : "",
    c = f;
  for (var _i = 0; _i < s; _i++) {
    var _s = t[_i];
    var _a = void 0,
      _u = void 0,
      _d = -1,
      _y = 0;
    for (; _y < _s.length && (c.lastIndex = _y, _u = c.exec(_s), null !== _u);) {
      var _r;
      _y = c.lastIndex, c === f ? "!--" === _u[1] ? c = v : void 0 !== _u[1] ? c = _ : void 0 !== _u[2] ? ($.test(_u[2]) && (r = RegExp("</" + _u[2], "g")), c = m) : void 0 !== _u[3] && (c = m) : c === m ? ">" === _u[0] ? (c = (_r = r) !== null && _r !== void 0 ? _r : f, _d = -1) : void 0 === _u[1] ? _d = -2 : (_d = c.lastIndex - _u[2].length, _a = _u[1], c = void 0 === _u[3] ? m : '"' === _u[3] ? g : p) : c === g || c === p ? c = m : c === v || c === _ ? c = f : (c = m, r = void 0);
    }
    var _x = c === m && t[_i + 1].startsWith("/>") ? " " : "";
    l += c === f ? _s + n : _d >= 0 ? (o.push(_a), _s.slice(0, _d) + e + _s.slice(_d) + h + _x) : _s + h + (-2 === _d ? _i : _x);
  }
  return [P(t, l + (t[s] || "<?>") + (2 === i ? "</svg>" : 3 === i ? "</math>" : "")), o];
};
var N = /*#__PURE__*/function () {
  function N(_ref, n) {
    var t = _ref.strings,
      s = _ref._$litType$;
    lit_html_classCallCheck(this, N);
    var r;
    this.parts = [];
    var c = 0,
      a = 0;
    var u = t.length - 1,
      d = this.parts,
      _V = V(t, s),
      _V2 = lit_html_slicedToArray(_V, 2),
      f = _V2[0],
      v = _V2[1];
    if (this.el = N.createElement(f, n), C.currentNode = this.el.content, 2 === s || 3 === s) {
      var _t = this.el.content.firstChild;
      _t.replaceWith.apply(_t, lit_html_toConsumableArray(_t.childNodes));
    }
    for (; null !== (r = C.nextNode()) && d.length < u;) {
      if (1 === r.nodeType) {
        if (r.hasAttributes()) {
          var _iterator = _createForOfIteratorHelper(r.getAttributeNames()),
            _step;
          try {
            for (_iterator.s(); !(_step = _iterator.n()).done;) {
              var _t2 = _step.value;
              if (_t2.endsWith(e)) {
                var _i2 = v[a++],
                  _s2 = r.getAttribute(_t2).split(h),
                  _e2 = /([.?@])?(.*)/.exec(_i2);
                d.push({
                  type: 1,
                  index: c,
                  name: _e2[2],
                  strings: _s2,
                  ctor: "." === _e2[1] ? H : "?" === _e2[1] ? I : "@" === _e2[1] ? L : k
                }), r.removeAttribute(_t2);
              } else _t2.startsWith(h) && (d.push({
                type: 6,
                index: c
              }), r.removeAttribute(_t2));
            }
          } catch (err) {
            _iterator.e(err);
          } finally {
            _iterator.f();
          }
        }
        if ($.test(r.tagName)) {
          var _t3 = r.textContent.split(h),
            _s3 = _t3.length - 1;
          if (_s3 > 0) {
            r.textContent = lit_html_i ? lit_html_i.emptyScript : "";
            for (var _i3 = 0; _i3 < _s3; _i3++) r.append(_t3[_i3], l()), C.nextNode(), d.push({
              type: 2,
              index: ++c
            });
            r.append(_t3[_s3], l());
          }
        }
      } else if (8 === r.nodeType) if (r.data === o) d.push({
        type: 2,
        index: c
      });else {
        var _t4 = -1;
        for (; -1 !== (_t4 = r.data.indexOf(h, _t4 + 1));) d.push({
          type: 7,
          index: c
        }), _t4 += h.length - 1;
      }
      c++;
    }
  }
  lit_html_createClass(N, null, [{
    key: "createElement",
    value: function createElement(t, i) {
      var s = r.createElement("template");
      return s.innerHTML = t, s;
    }
  }]);
  return N;
}();
function S(t, i) {
  var _s$_$Co, _h, _h2, _h2$_$AO, _s$_$Co2;
  var s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : t;
  var e = arguments.length > 3 ? arguments[3] : undefined;
  if (i === T) return i;
  var h = void 0 !== e ? (_s$_$Co = s._$Co) === null || _s$_$Co === void 0 ? void 0 : _s$_$Co[e] : s._$Cl;
  var o = c(i) ? void 0 : i._$litDirective$;
  return ((_h = h) === null || _h === void 0 ? void 0 : _h.constructor) !== o && ((_h2 = h) !== null && _h2 !== void 0 && (_h2$_$AO = _h2._$AO) !== null && _h2$_$AO !== void 0 && _h2$_$AO.call(_h2, !1), void 0 === o ? h = void 0 : (h = new o(t), h._$AT(t, s, e)), void 0 !== e ? ((_s$_$Co2 = s._$Co) !== null && _s$_$Co2 !== void 0 ? _s$_$Co2 : s._$Co = [])[e] = h : s._$Cl = h), void 0 !== h && (i = S(t, h._$AS(t, i.values), h, e)), i;
}
var M = /*#__PURE__*/function () {
  function M(t, i) {
    lit_html_classCallCheck(this, M);
    this._$AV = [], this._$AN = void 0, this._$AD = t, this._$AM = i;
  }
  lit_html_createClass(M, [{
    key: "parentNode",
    get: function get() {
      return this._$AM.parentNode;
    }
  }, {
    key: "_$AU",
    get: function get() {
      return this._$AM._$AU;
    }
  }, {
    key: "u",
    value: function u(t) {
      var _t$creationScope;
      var _this$_$AD = this._$AD,
        i = _this$_$AD.el.content,
        s = _this$_$AD.parts,
        e = ((_t$creationScope = t === null || t === void 0 ? void 0 : t.creationScope) !== null && _t$creationScope !== void 0 ? _t$creationScope : r).importNode(i, !0);
      C.currentNode = e;
      var h = C.nextNode(),
        o = 0,
        n = 0,
        l = s[0];
      for (; void 0 !== l;) {
        var _l;
        if (o === l.index) {
          var _i4 = void 0;
          2 === l.type ? _i4 = new R(h, h.nextSibling, this, t) : 1 === l.type ? _i4 = new l.ctor(h, l.name, l.strings, this, t) : 6 === l.type && (_i4 = new z(h, this, t)), this._$AV.push(_i4), l = s[++n];
        }
        o !== ((_l = l) === null || _l === void 0 ? void 0 : _l.index) && (h = C.nextNode(), o++);
      }
      return C.currentNode = r, e;
    }
  }, {
    key: "p",
    value: function p(t) {
      var i = 0;
      var _iterator2 = _createForOfIteratorHelper(this._$AV),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var _s4 = _step2.value;
          void 0 !== _s4 && (void 0 !== _s4.strings ? (_s4._$AI(t, _s4, i), i += _s4.strings.length - 2) : _s4._$AI(t[i])), i++;
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
  }]);
  return M;
}();
var R = /*#__PURE__*/function () {
  function R(t, i, s, e) {
    var _e$isConnected;
    lit_html_classCallCheck(this, R);
    this.type = 2, this._$AH = E, this._$AN = void 0, this._$AA = t, this._$AB = i, this._$AM = s, this.options = e, this._$Cv = (_e$isConnected = e === null || e === void 0 ? void 0 : e.isConnected) !== null && _e$isConnected !== void 0 ? _e$isConnected : !0;
  }
  lit_html_createClass(R, [{
    key: "_$AU",
    get: function get() {
      var _this$_$AM$_$AU, _this$_$AM;
      return (_this$_$AM$_$AU = (_this$_$AM = this._$AM) === null || _this$_$AM === void 0 ? void 0 : _this$_$AM._$AU) !== null && _this$_$AM$_$AU !== void 0 ? _this$_$AM$_$AU : this._$Cv;
    }
  }, {
    key: "parentNode",
    get: function get() {
      var _t5;
      var t = this._$AA.parentNode;
      var i = this._$AM;
      return void 0 !== i && 11 === ((_t5 = t) === null || _t5 === void 0 ? void 0 : _t5.nodeType) && (t = i.parentNode), t;
    }
  }, {
    key: "startNode",
    get: function get() {
      return this._$AA;
    }
  }, {
    key: "endNode",
    get: function get() {
      return this._$AB;
    }
  }, {
    key: "_$AI",
    value: function _$AI(t) {
      var i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
      t = S(this, t, i), c(t) ? t === E || null == t || "" === t ? (this._$AH !== E && this._$AR(), this._$AH = E) : t !== this._$AH && t !== T && this._(t) : void 0 !== t._$litType$ ? this.$(t) : void 0 !== t.nodeType ? this.T(t) : lit_html_u(t) ? this.k(t) : this._(t);
    }
  }, {
    key: "O",
    value: function O(t) {
      return this._$AA.parentNode.insertBefore(t, this._$AB);
    }
  }, {
    key: "T",
    value: function T(t) {
      this._$AH !== t && (this._$AR(), this._$AH = this.O(t));
    }
  }, {
    key: "_",
    value: function _(t) {
      this._$AH !== E && c(this._$AH) ? this._$AA.nextSibling.data = t : this.T(r.createTextNode(t)), this._$AH = t;
    }
  }, {
    key: "$",
    value: function $(t) {
      var _this$_$AH;
      var i = t.values,
        s = t._$litType$,
        e = "number" == typeof s ? this._$AC(t) : (void 0 === s.el && (s.el = N.createElement(P(s.h, s.h[0]), this.options)), s);
      if (((_this$_$AH = this._$AH) === null || _this$_$AH === void 0 ? void 0 : _this$_$AH._$AD) === e) this._$AH.p(i);else {
        var _t6 = new M(e, this),
          _s5 = _t6.u(this.options);
        _t6.p(i), this.T(_s5), this._$AH = _t6;
      }
    }
  }, {
    key: "_$AC",
    value: function _$AC(t) {
      var i = A.get(t.strings);
      return void 0 === i && A.set(t.strings, i = new N(t)), i;
    }
  }, {
    key: "k",
    value: function k(t) {
      a(this._$AH) || (this._$AH = [], this._$AR());
      var i = this._$AH;
      var s,
        e = 0;
      var _iterator3 = _createForOfIteratorHelper(t),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var _h3 = _step3.value;
          e === i.length ? i.push(s = new R(this.O(l()), this.O(l()), this, this.options)) : s = i[e], s._$AI(_h3), e++;
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      e < i.length && (this._$AR(s && s._$AB.nextSibling, e), i.length = e);
    }
  }, {
    key: "_$AR",
    value: function _$AR() {
      var t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._$AA.nextSibling;
      var i = arguments.length > 1 ? arguments[1] : undefined;
      for ((_this$_$AP = this._$AP) === null || _this$_$AP === void 0 ? void 0 : _this$_$AP.call(this, !1, !0, i); t && t !== this._$AB;) {
        var _this$_$AP;
        var _i5 = t.nextSibling;
        t.remove(), t = _i5;
      }
    }
  }, {
    key: "setConnected",
    value: function setConnected(t) {
      var _this$_$AP2;
      void 0 === this._$AM && (this._$Cv = t, (_this$_$AP2 = this._$AP) === null || _this$_$AP2 === void 0 ? void 0 : _this$_$AP2.call(this, t));
    }
  }]);
  return R;
}();
var k = /*#__PURE__*/function () {
  function k(t, i, s, e, h) {
    lit_html_classCallCheck(this, k);
    this.type = 1, this._$AH = E, this._$AN = void 0, this.element = t, this.name = i, this._$AM = e, this.options = h, s.length > 2 || "" !== s[0] || "" !== s[1] ? (this._$AH = Array(s.length - 1).fill(new String()), this.strings = s) : this._$AH = E;
  }
  lit_html_createClass(k, [{
    key: "tagName",
    get: function get() {
      return this.element.tagName;
    }
  }, {
    key: "_$AU",
    get: function get() {
      return this._$AM._$AU;
    }
  }, {
    key: "_$AI",
    value: function _$AI(t) {
      var i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
      var s = arguments.length > 2 ? arguments[2] : undefined;
      var e = arguments.length > 3 ? arguments[3] : undefined;
      var h = this.strings;
      var o = !1;
      if (void 0 === h) t = S(this, t, i, 0), o = !c(t) || t !== this._$AH && t !== T, o && (this._$AH = t);else {
        var _e3 = t;
        var _n2, _r2;
        for (t = h[0], _n2 = 0; _n2 < h.length - 1; _n2++) {
          var _r3;
          _r2 = S(this, _e3[s + _n2], i, _n2), _r2 === T && (_r2 = this._$AH[_n2]), o || (o = !c(_r2) || _r2 !== this._$AH[_n2]), _r2 === E ? t = E : t !== E && (t += ((_r3 = _r2) !== null && _r3 !== void 0 ? _r3 : "") + h[_n2 + 1]), this._$AH[_n2] = _r2;
        }
      }
      o && !e && this.j(t);
    }
  }, {
    key: "j",
    value: function j(t) {
      t === E ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t !== null && t !== void 0 ? t : "");
    }
  }]);
  return k;
}();
var H = /*#__PURE__*/function (_k) {
  lit_html_inherits(H, _k);
  var _super = lit_html_createSuper(H);
  function H() {
    var _this;
    lit_html_classCallCheck(this, H);
    _this = _super.apply(this, arguments), _this.type = 3;
    return _this;
  }
  lit_html_createClass(H, [{
    key: "j",
    value: function j(t) {
      this.element[this.name] = t === E ? void 0 : t;
    }
  }]);
  return H;
}(k);
var I = /*#__PURE__*/function (_k2) {
  lit_html_inherits(I, _k2);
  var _super2 = lit_html_createSuper(I);
  function I() {
    var _this2;
    lit_html_classCallCheck(this, I);
    _this2 = _super2.apply(this, arguments), _this2.type = 4;
    return _this2;
  }
  lit_html_createClass(I, [{
    key: "j",
    value: function j(t) {
      this.element.toggleAttribute(this.name, !!t && t !== E);
    }
  }]);
  return I;
}(k);
var L = /*#__PURE__*/function (_k3) {
  lit_html_inherits(L, _k3);
  var _super3 = lit_html_createSuper(L);
  function L(t, i, s, e, h) {
    var _this3;
    lit_html_classCallCheck(this, L);
    _this3 = _super3.call(this, t, i, s, e, h), _this3.type = 5;
    return _this3;
  }
  lit_html_createClass(L, [{
    key: "_$AI",
    value: function _$AI(t) {
      var _S;
      var i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
      if ((t = (_S = S(this, t, i, 0)) !== null && _S !== void 0 ? _S : E) === T) return;
      var s = this._$AH,
        e = t === E && s !== E || t.capture !== s.capture || t.once !== s.once || t.passive !== s.passive,
        h = t !== E && (s === E || e);
      e && this.element.removeEventListener(this.name, this, s), h && this.element.addEventListener(this.name, this, t), this._$AH = t;
    }
  }, {
    key: "handleEvent",
    value: function handleEvent(t) {
      var _this$options$host, _this$options;
      "function" == typeof this._$AH ? this._$AH.call((_this$options$host = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.host) !== null && _this$options$host !== void 0 ? _this$options$host : this.element, t) : this._$AH.handleEvent(t);
    }
  }]);
  return L;
}(k);
var z = /*#__PURE__*/function () {
  function z(t, i, s) {
    lit_html_classCallCheck(this, z);
    this.element = t, this.type = 6, this._$AN = void 0, this._$AM = i, this.options = s;
  }
  lit_html_createClass(z, [{
    key: "_$AU",
    get: function get() {
      return this._$AM._$AU;
    }
  }, {
    key: "_$AI",
    value: function _$AI(t) {
      S(this, t);
    }
  }]);
  return z;
}();
var Z = {
    M: e,
    P: h,
    A: o,
    C: 1,
    L: V,
    R: M,
    D: lit_html_u,
    V: S,
    I: R,
    H: k,
    N: I,
    U: L,
    B: H,
    F: z
  },
  j = t.litHtmlPolyfillSupport;
j !== null && j !== void 0 && j(N, R), ((_t$litHtmlVersions = t.litHtmlVersions) !== null && _t$litHtmlVersions !== void 0 ? _t$litHtmlVersions : t.litHtmlVersions = []).push("3.2.1");
var B = function B(t, i, s) {
  var _s$renderBefore;
  var e = (_s$renderBefore = s === null || s === void 0 ? void 0 : s.renderBefore) !== null && _s$renderBefore !== void 0 ? _s$renderBefore : i;
  var h = e._$litPart$;
  if (void 0 === h) {
    var _s$renderBefore2;
    var _t7 = (_s$renderBefore2 = s === null || s === void 0 ? void 0 : s.renderBefore) !== null && _s$renderBefore2 !== void 0 ? _s$renderBefore2 : null;
    e._$litPart$ = h = new R(i.insertBefore(l(), _t7), _t7, void 0, s !== null && s !== void 0 ? s : {});
  }
  return h._$AI(t), h;
};

;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directive-helpers.js
function directive_helpers_typeof(obj) {
  "@babel/helpers - typeof";

  return directive_helpers_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;
  }, directive_helpers_typeof(obj);
}

/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var directive_helpers_t = Z.I,
  directive_helpers_i = function i(o) {
    return null === o || "object" != directive_helpers_typeof(o) && "function" != typeof o;
  },
  directive_helpers_n = {
    HTML: 1,
    SVG: 2,
    MATHML: 3
  },
  directive_helpers_e = function e(o, t) {
    return void 0 === t ? void 0 !== (o === null || o === void 0 ? void 0 : o._$litType$) : (o === null || o === void 0 ? void 0 : o._$litType$) === t;
  },
  directive_helpers_l = function l(o) {
    var _o$_$litType$;
    return null != (o === null || o === void 0 ? void 0 : (_o$_$litType$ = o._$litType$) === null || _o$_$litType$ === void 0 ? void 0 : _o$_$litType$.h);
  },
  directive_helpers_c = function c(o) {
    return void 0 !== (o === null || o === void 0 ? void 0 : o._$litDirective$);
  },
  directive_helpers_d = function d(o) {
    return o === null || o === void 0 ? void 0 : o._$litDirective$;
  },
  directive_helpers_f = function f(o) {
    return void 0 === o.strings;
  },
  directive_helpers_s = function s() {
    return document.createComment("");
  },
  directive_helpers_r = function r(o, i, n) {
    var e = o._$AA.parentNode,
      l = void 0 === i ? o._$AB : i._$AA;
    if (void 0 === n) {
      var _i = e.insertBefore(directive_helpers_s(), l),
        _c = e.insertBefore(directive_helpers_s(), l);
      n = new directive_helpers_t(_i, _c, o, o.options);
    } else {
      var _t = n._$AB.nextSibling,
        _i2 = n._$AM,
        _c2 = _i2 !== o;
      if (_c2) {
        var _n$_$AQ, _n;
        var _t2;
        (_n$_$AQ = (_n = n)._$AQ) !== null && _n$_$AQ !== void 0 && _n$_$AQ.call(_n, o), n._$AM = o, void 0 !== n._$AP && (_t2 = o._$AU) !== _i2._$AU && n._$AP(_t2);
      }
      if (_t !== l || _c2) {
        var _o = n._$AA;
        for (; _o !== _t;) {
          var _t3 = _o.nextSibling;
          e.insertBefore(_o, l), _o = _t3;
        }
      }
    }
    return n;
  },
  directive_helpers_v = function v(o, t) {
    var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : o;
    return o._$AI(t, i), o;
  },
  directive_helpers_u = {},
  directive_helpers_m = function m(o) {
    var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : directive_helpers_u;
    return o._$AH = t;
  },
  directive_helpers_p = function p(o) {
    return o._$AH;
  },
  directive_helpers_M = function M(o) {
    var _o$_$AP;
    (_o$_$AP = o._$AP) === null || _o$_$AP === void 0 ? void 0 : _o$_$AP.call(o, !1, !0);
    var t = o._$AA;
    var i = o._$AB.nextSibling;
    for (; t !== i;) {
      var _o2 = t.nextSibling;
      t.remove(), t = _o2;
    }
  },
  directive_helpers_h = function h(o) {
    o._$AR();
  };

;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directive.js
function directive_typeof(obj) {
  "@babel/helpers - typeof";

  return directive_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;
  }, directive_typeof(obj);
}
function directive_toConsumableArray(arr) {
  return directive_arrayWithoutHoles(arr) || directive_iterableToArray(arr) || directive_unsupportedIterableToArray(arr) || directive_nonIterableSpread();
}
function directive_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function directive_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return directive_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 directive_arrayLikeToArray(o, minLen);
}
function directive_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function directive_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return directive_arrayLikeToArray(arr);
}
function directive_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 directive_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function directive_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, directive_toPropertyKey(descriptor.key), descriptor);
  }
}
function directive_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) directive_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) directive_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function directive_toPropertyKey(arg) {
  var key = directive_toPrimitive(arg, "string");
  return directive_typeof(key) === "symbol" ? key : String(key);
}
function directive_toPrimitive(input, hint) {
  if (directive_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (directive_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var directive_t = {
    ATTRIBUTE: 1,
    CHILD: 2,
    PROPERTY: 3,
    BOOLEAN_ATTRIBUTE: 4,
    EVENT: 5,
    ELEMENT: 6
  },
  directive_e = function e(t) {
    return function () {
      for (var _len = arguments.length, e = new Array(_len), _key = 0; _key < _len; _key++) {
        e[_key] = arguments[_key];
      }
      return {
        _$litDirective$: t,
        values: e
      };
    };
  };
var directive_i = /*#__PURE__*/function () {
  function i(t) {
    directive_classCallCheck(this, i);
  }
  directive_createClass(i, [{
    key: "_$AU",
    get: function get() {
      return this._$AM._$AU;
    }
  }, {
    key: "_$AT",
    value: function _$AT(t, e, _i) {
      this._$Ct = t, this._$AM = e, this._$Ci = _i;
    }
  }, {
    key: "_$AS",
    value: function _$AS(t, e) {
      return this.update(t, e);
    }
  }, {
    key: "update",
    value: function update(t, e) {
      return this.render.apply(this, directive_toConsumableArray(e));
    }
  }]);
  return i;
}();

;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/async-directive.js
function async_directive_typeof(obj) {
  "@babel/helpers - typeof";

  return async_directive_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;
  }, async_directive_typeof(obj);
}
function async_directive_toConsumableArray(arr) {
  return async_directive_arrayWithoutHoles(arr) || async_directive_iterableToArray(arr) || async_directive_unsupportedIterableToArray(arr) || async_directive_nonIterableSpread();
}
function async_directive_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function async_directive_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function async_directive_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return async_directive_arrayLikeToArray(arr);
}
function async_directive_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function async_directive_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, async_directive_toPropertyKey(descriptor.key), descriptor);
  }
}
function async_directive_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) async_directive_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) async_directive_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function async_directive_toPropertyKey(arg) {
  var key = async_directive_toPrimitive(arg, "string");
  return async_directive_typeof(key) === "symbol" ? key : String(key);
}
function async_directive_toPrimitive(input, hint) {
  if (async_directive_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (async_directive_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function async_directive_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    async_directive_get = Reflect.get.bind();
  } else {
    async_directive_get = function _get(target, property, receiver) {
      var base = async_directive_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return async_directive_get.apply(this, arguments);
}
function async_directive_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = async_directive_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function async_directive_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) async_directive_setPrototypeOf(subClass, superClass);
}
function async_directive_setPrototypeOf(o, p) {
  async_directive_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return async_directive_setPrototypeOf(o, p);
}
function async_directive_createSuper(Derived) {
  var hasNativeReflectConstruct = async_directive_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = async_directive_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = async_directive_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return async_directive_possibleConstructorReturn(this, result);
  };
}
function async_directive_possibleConstructorReturn(self, call) {
  if (call && (async_directive_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 async_directive_assertThisInitialized(self);
}
function async_directive_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function async_directive_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 async_directive_getPrototypeOf(o) {
  async_directive_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return async_directive_getPrototypeOf(o);
}
function async_directive_createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = async_directive_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(_e3) {
          throw _e3;
        },
        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(_e4) {
      didErr = true;
      err = _e4;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}
function async_directive_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return async_directive_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 async_directive_arrayLikeToArray(o, minLen);
}
function async_directive_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;
}



/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var async_directive_s = function s(i, t) {
    var e = i._$AN;
    if (void 0 === e) return !1;
    var _iterator = async_directive_createForOfIteratorHelper(e),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _i$_$AO;
        var _i = _step.value;
        (_i$_$AO = _i._$AO) !== null && _i$_$AO !== void 0 && _i$_$AO.call(_i, t, !1), s(_i, t);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return !0;
  },
  async_directive_o = function o(i) {
    var t, e;
    do {
      var _e;
      if (void 0 === (t = i._$AM)) break;
      e = t._$AN, e.delete(i), i = t;
    } while (0 === ((_e = e) === null || _e === void 0 ? void 0 : _e.size));
  },
  async_directive_r = function r(i) {
    for (var _t; _t = i._$AM; i = _t) {
      var _e2 = _t._$AN;
      if (void 0 === _e2) _t._$AN = _e2 = new Set();else if (_e2.has(i)) break;
      _e2.add(i), async_directive_c(_t);
    }
  };
function async_directive_h(i) {
  void 0 !== this._$AN ? (async_directive_o(this), this._$AM = i, async_directive_r(this)) : this._$AM = i;
}
function async_directive_n(i) {
  var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !1;
  var e = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var r = this._$AH,
    h = this._$AN;
  if (void 0 !== h && 0 !== h.size) if (t) {
    if (Array.isArray(r)) for (var _i2 = e; _i2 < r.length; _i2++) async_directive_s(r[_i2], !1), async_directive_o(r[_i2]);else null != r && (async_directive_s(r, !1), async_directive_o(r));
  } else async_directive_s(this, i);
}
var async_directive_c = function c(i) {
  var _i$_$AP, _i$_$AQ;
  i.type == directive_t.CHILD && ((_i$_$AP = i._$AP) !== null && _i$_$AP !== void 0 ? _i$_$AP : i._$AP = async_directive_n, (_i$_$AQ = i._$AQ) !== null && _i$_$AQ !== void 0 ? _i$_$AQ : i._$AQ = async_directive_h);
};
var async_directive_f = /*#__PURE__*/function (_t2) {
  async_directive_inherits(f, _t2);
  var _super = async_directive_createSuper(f);
  function f() {
    var _this;
    async_directive_classCallCheck(this, f);
    _this = _super.apply(this, arguments), _this._$AN = void 0;
    return _this;
  }
  async_directive_createClass(f, [{
    key: "_$AT",
    value: function _$AT(i, t, e) {
      async_directive_get(async_directive_getPrototypeOf(f.prototype), "_$AT", this).call(this, i, t, e), async_directive_r(this), this.isConnected = i._$AU;
    }
  }, {
    key: "_$AO",
    value: function _$AO(i) {
      var _this$reconnected, _this$disconnected;
      var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !0;
      i !== this.isConnected && (this.isConnected = i, i ? (_this$reconnected = this.reconnected) === null || _this$reconnected === void 0 ? void 0 : _this$reconnected.call(this) : (_this$disconnected = this.disconnected) === null || _this$disconnected === void 0 ? void 0 : _this$disconnected.call(this)), t && (async_directive_s(this, i), async_directive_o(this));
    }
  }, {
    key: "setValue",
    value: function setValue(t) {
      if (directive_helpers_f(this._$Ct)) this._$Ct._$AI(t, this);else {
        var _i3 = async_directive_toConsumableArray(this._$Ct._$AH);
        _i3[this._$Ci] = t, this._$Ct._$AI(_i3, this, 0);
      }
    }
  }, {
    key: "disconnected",
    value: function disconnected() {}
  }, {
    key: "reconnected",
    value: function reconnected() {}
  }]);
  return f;
}(directive_i);

;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directives/private-async-helpers.js
function private_async_helpers_typeof(obj) {
  "@babel/helpers - typeof";

  return private_async_helpers_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;
  }, private_async_helpers_typeof(obj);
}
function private_async_helpers_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function private_async_helpers_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, private_async_helpers_toPropertyKey(descriptor.key), descriptor);
  }
}
function private_async_helpers_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) private_async_helpers_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) private_async_helpers_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function private_async_helpers_toPropertyKey(arg) {
  var key = private_async_helpers_toPrimitive(arg, "string");
  return private_async_helpers_typeof(key) === "symbol" ? key : String(key);
}
function private_async_helpers_toPrimitive(input, hint) {
  if (private_async_helpers_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (private_async_helpers_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function private_async_helpers_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  private_async_helpers_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" == private_async_helpers_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 private_async_helpers_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 private_async_helpers_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        private_async_helpers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        private_async_helpers_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
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);
}
/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var private_async_helpers_t = /*#__PURE__*/(/* unused pure expression or super */ null && (function () {
  var _ref = private_async_helpers_asyncToGenerator( /*#__PURE__*/private_async_helpers_regeneratorRuntime().mark(function _callee(_t, s) {
    var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _i;
    return private_async_helpers_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _iteratorAbruptCompletion = false;
          _didIteratorError = false;
          _context.prev = 2;
          _iterator = _asyncIterator(_t);
        case 4:
          _context.next = 6;
          return _iterator.next();
        case 6:
          if (!(_iteratorAbruptCompletion = !(_step = _context.sent).done)) {
            _context.next = 17;
            break;
          }
          _i = _step.value;
          _context.t0 = !1;
          _context.next = 11;
          return s(_i);
        case 11:
          _context.t1 = _context.sent;
          if (!(_context.t0 === _context.t1)) {
            _context.next = 14;
            break;
          }
          return _context.abrupt("return");
        case 14:
          _iteratorAbruptCompletion = false;
          _context.next = 4;
          break;
        case 17:
          _context.next = 23;
          break;
        case 19:
          _context.prev = 19;
          _context.t2 = _context["catch"](2);
          _didIteratorError = true;
          _iteratorError = _context.t2;
        case 23:
          _context.prev = 23;
          _context.prev = 24;
          if (!(_iteratorAbruptCompletion && _iterator.return != null)) {
            _context.next = 28;
            break;
          }
          _context.next = 28;
          return _iterator.return();
        case 28:
          _context.prev = 28;
          if (!_didIteratorError) {
            _context.next = 31;
            break;
          }
          throw _iteratorError;
        case 31:
          return _context.finish(28);
        case 32:
          return _context.finish(23);
        case 33:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[2, 19, 23, 33], [24,, 28, 32]]);
  }));
  return function t(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}()));
var private_async_helpers_s = /*#__PURE__*/function () {
  function s(t) {
    private_async_helpers_classCallCheck(this, s);
    this.Y = t;
  }
  private_async_helpers_createClass(s, [{
    key: "disconnect",
    value: function disconnect() {
      this.Y = void 0;
    }
  }, {
    key: "reconnect",
    value: function reconnect(t) {
      this.Y = t;
    }
  }, {
    key: "deref",
    value: function deref() {
      return this.Y;
    }
  }]);
  return s;
}();
var private_async_helpers_i = /*#__PURE__*/function () {
  function i() {
    private_async_helpers_classCallCheck(this, i);
    this.Z = void 0, this.q = void 0;
  }
  private_async_helpers_createClass(i, [{
    key: "get",
    value: function get() {
      return this.Z;
    }
  }, {
    key: "pause",
    value: function pause() {
      var _this$Z,
        _this = this;
      (_this$Z = this.Z) !== null && _this$Z !== void 0 ? _this$Z : this.Z = new Promise(function (t) {
        return _this.q = t;
      });
    }
  }, {
    key: "resume",
    value: function resume() {
      var _this$q;
      (_this$q = this.q) !== null && _this$q !== void 0 && _this$q.call(this), this.Z = this.q = void 0;
    }
  }]);
  return i;
}();

;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directives/until.js
function until_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  until_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" == until_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 until_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 until_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        until_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        until_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function until_typeof(obj) {
  "@babel/helpers - typeof";

  return until_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;
  }, until_typeof(obj);
}
function until_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function until_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, until_toPropertyKey(descriptor.key), descriptor);
  }
}
function until_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) until_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) until_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function until_toPropertyKey(arg) {
  var key = until_toPrimitive(arg, "string");
  return until_typeof(key) === "symbol" ? key : String(key);
}
function until_toPrimitive(input, hint) {
  if (until_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (until_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function until_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) until_setPrototypeOf(subClass, superClass);
}
function until_setPrototypeOf(o, p) {
  until_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return until_setPrototypeOf(o, p);
}
function until_createSuper(Derived) {
  var hasNativeReflectConstruct = until_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = until_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = until_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return until_possibleConstructorReturn(this, result);
  };
}
function until_possibleConstructorReturn(self, call) {
  if (call && (until_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 until_assertThisInitialized(self);
}
function until_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function until_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 until_getPrototypeOf(o) {
  until_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return until_getPrototypeOf(o);
}





/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var until_n = function n(t) {
    return !directive_helpers_i(t) && "function" == typeof t.then;
  },
  until_h = 1073741823;
var until_c = /*#__PURE__*/function (_i) {
  until_inherits(c, _i);
  var _super = until_createSuper(c);
  function c() {
    var _this;
    until_classCallCheck(this, c);
    _this = _super.apply(this, arguments), _this._$Cwt = until_h, _this._$Cbt = [], _this._$CK = new private_async_helpers_s(until_assertThisInitialized(_this)), _this._$CX = new private_async_helpers_i();
    return _this;
  }
  until_createClass(c, [{
    key: "render",
    value: function render() {
      var _s$find;
      for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
        s[_key] = arguments[_key];
      }
      return (_s$find = s.find(function (t) {
        return !until_n(t);
      })) !== null && _s$find !== void 0 ? _s$find : T;
    }
  }, {
    key: "update",
    value: function update(s, i) {
      var _this2 = this;
      var e = this._$Cbt;
      var r = e.length;
      this._$Cbt = i;
      var o = this._$CK,
        _c = this._$CX;
      this.isConnected || this.disconnected();
      var _loop = function _loop() {
        var s = i[_t];
        if (!until_n(s)) return {
          v: (_this2._$Cwt = _t, s)
        };
        _t < r && s === e[_t] || (_this2._$Cwt = until_h, r = 0, Promise.resolve(s).then( /*#__PURE__*/function () {
          var _ref = until_asyncToGenerator( /*#__PURE__*/until_regeneratorRuntime().mark(function _callee(t) {
            var i, _e;
            return until_regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  if (!_c.get()) {
                    _context.next = 5;
                    break;
                  }
                  _context.next = 3;
                  return _c.get();
                case 3:
                  _context.next = 0;
                  break;
                case 5:
                  i = o.deref();
                  if (void 0 !== i) {
                    _e = i._$Cbt.indexOf(s);
                    _e > -1 && _e < i._$Cwt && (i._$Cwt = _e, i.setValue(t));
                  }
                case 7:
                case "end":
                  return _context.stop();
              }
            }, _callee);
          }));
          return function (_x) {
            return _ref.apply(this, arguments);
          };
        }()));
      };
      for (var _t = 0; _t < i.length && !(_t > this._$Cwt); _t++) {
        var _ret = _loop();
        if (until_typeof(_ret) === "object") return _ret.v;
      }
      return T;
    }
  }, {
    key: "disconnected",
    value: function disconnected() {
      this._$CK.disconnect(), this._$CX.pause();
    }
  }, {
    key: "reconnected",
    value: function reconnected() {
      this._$CK.reconnect(this), this._$CX.resume();
    }
  }]);
  return c;
}(async_directive_f);
var until_m = directive_e(until_c);

;// CONCATENATED MODULE: ./node_modules/lit/directives/until.js

;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/templates/occupant.js
var occupant_templateObject, occupant_templateObject2, occupant_templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10;
function occupant_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





/* harmony default export */ const templates_occupant = (function (el) {
  var _el$model, _el$model2, _el$model3, _el$model4, _el$model4$get;
  var model = (_el$model = el.model) !== null && _el$model !== void 0 ? _el$model : el.message;
  var jid = model === null || model === void 0 ? void 0 : model.get('jid');
  var vcard = el.getVcard();
  var nick = model.get('nick');
  var occupant_id = model.get('occupant_id');
  var role = (_el$model2 = el.model) === null || _el$model2 === void 0 ? void 0 : _el$model2.get('role');
  var affiliation = (_el$model3 = el.model) === null || _el$model3 === void 0 ? void 0 : _el$model3.get('affiliation');
  var hats = (_el$model4 = el.model) !== null && _el$model4 !== void 0 && (_el$model4$get = _el$model4.get('hats')) !== null && _el$model4$get !== void 0 && _el$model4$get.length ? el.model.get('hats') : null;
  var muc = el.model.collection.chatroom;
  var allowed_commands = muc.getAllowedCommands();
  var may_moderate = allowed_commands.includes('modtools');
  var i18n_add_to_contacts = __('Add to Contacts');
  var can_see_real_jids = muc.features.get('nonanonymous') || muc.getOwnRole() === 'moderator';
  var not_me = jid != shared_converse.bare_jid;
  var add_to_contacts = shared_api.contacts.get(jid).then(function (contact) {
    return !contact && not_me && can_see_real_jids;
  }).then(function (add) {
    return add ? (0,external_lit_namespaceObject.html)(occupant_templateObject || (occupant_templateObject = occupant_taggedTemplateLiteral(["<li><button class=\"btn btn-primary\" type=\"button\" @click=", ">", "</button></li>"])), function () {
      return el.addToContacts();
    }, i18n_add_to_contacts) : '';
  });
  return (0,external_lit_namespaceObject.html)(occupant_templateObject2 || (occupant_templateObject2 = occupant_taggedTemplateLiteral(["\n        <div class=\"row\">\n            <div class=\"col-auto\">\n                <converse-avatar\n                    class=\"avatar modal-avatar\"\n                    .data=", "\n                    nonce=", "\n                    height=\"120\" width=\"120\"></converse-avatar>\n            </div>\n            <div class=\"col\">\n                <ul class=\"occupant-details\">\n                    <li>\n                        ", "\n                    </li>\n                    <li>\n                        ", "\n                    </li>\n                    <li>\n                        <div class=\"row\"><strong>", ":</strong></div>\n                        <div class=\"row\">", "&nbsp;\n                            ", "\n                        </div>\n                    </li>\n                    <li>\n                        <div class=\"row\"><strong>", ":</strong></div>\n                        <div class=\"row\">", "&nbsp;\n                            ", "\n                        </div>\n                    </li>\n                    <li>\n                        ", "\n                    </li>\n                    <li>\n                        ", "\n                    </li>\n                    ", "\n                </ul>\n            </div>\n        </div>\n    "])), vcard === null || vcard === void 0 ? void 0 : vcard.attributes, vcard === null || vcard === void 0 ? void 0 : vcard.get('vcard_updated'), nick ? (0,external_lit_namespaceObject.html)(occupant_templateObject3 || (occupant_templateObject3 = occupant_taggedTemplateLiteral(["<div class=\"row\"><strong>", ":</strong></div><div class=\"row\">", "</div>"])), __('Nickname'), nick) : '', jid ? (0,external_lit_namespaceObject.html)(_templateObject4 || (_templateObject4 = occupant_taggedTemplateLiteral(["<div class=\"row\"><strong>", ":</strong></div><div class=\"row\">", "</div>"])), __('XMPP Address'), jid) : '', __('Affiliation'), affiliation, may_moderate ? (0,external_lit_namespaceObject.html)(_templateObject5 || (_templateObject5 = occupant_taggedTemplateLiteral(["\n                                <a href=\"#\"\n                                data-form=\"affiliation-form\"\n                                class=\"toggle-form right\"\n                                color=\"var(--subdued-color)\"\n                                @click=", "><converse-icon class=\"fa fa-wrench\" size=\"1em\"></converse-icon>\n                                </a>\n                                ", ""])), function (ev) {
    return el.toggleForm(ev);
  }, el.show_affiliation_form ? (0,external_lit_namespaceObject.html)(_templateObject6 || (_templateObject6 = occupant_taggedTemplateLiteral(["<converse-muc-affiliation-form jid=", " .muc=", " affiliation=", "></converse-muc-affiliation-form>"])), jid, muc, affiliation) : '') : '', __('Role'), role, may_moderate && role ? (0,external_lit_namespaceObject.html)(_templateObject7 || (_templateObject7 = occupant_taggedTemplateLiteral(["\n                                <a href=\"#\"\n                                   data-form=\"row-form\"\n                                   class=\"toggle-form right\"\n                                   color=\"var(--subdued-color)\"\n                                   @click=", "><converse-icon class=\"fa fa-wrench\" size=\"1em\"></converse-icon>\n                                </a>\n                                ", ""])), function (ev) {
    return el.toggleForm(ev);
  }, el.show_role_form ? (0,external_lit_namespaceObject.html)(_templateObject8 || (_templateObject8 = occupant_taggedTemplateLiteral(["<converse-muc-role-form jid=", " .muc=", " role=", "></converse-muc-role-form>"])), jid, muc, role) : '') : '', hats ? (0,external_lit_namespaceObject.html)(_templateObject9 || (_templateObject9 = occupant_taggedTemplateLiteral(["<div class=\"row\"><strong>", ":</strong></div><div class=\"row\">", "</div>"])), __('Hats'), hats) : '', occupant_id ? (0,external_lit_namespaceObject.html)(_templateObject10 || (_templateObject10 = occupant_taggedTemplateLiteral(["<div class=\"row\"><strong>", ":</strong></div><div class=\"row\">", "</div>"])), __('Occupant Id'), occupant_id) : '', until_m(add_to_contacts, ''));
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/occupant.js
function modals_occupant_typeof(obj) {
  "@babel/helpers - typeof";

  return modals_occupant_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;
  }, modals_occupant_typeof(obj);
}
function modals_occupant_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function modals_occupant_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, modals_occupant_toPropertyKey(descriptor.key), descriptor);
  }
}
function modals_occupant_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) modals_occupant_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) modals_occupant_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modals_occupant_toPropertyKey(arg) {
  var key = modals_occupant_toPrimitive(arg, "string");
  return modals_occupant_typeof(key) === "symbol" ? key : String(key);
}
function modals_occupant_toPrimitive(input, hint) {
  if (modals_occupant_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modals_occupant_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function modals_occupant_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    modals_occupant_get = Reflect.get.bind();
  } else {
    modals_occupant_get = function _get(target, property, receiver) {
      var base = modals_occupant_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return modals_occupant_get.apply(this, arguments);
}
function modals_occupant_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = modals_occupant_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function modals_occupant_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) modals_occupant_setPrototypeOf(subClass, superClass);
}
function modals_occupant_setPrototypeOf(o, p) {
  modals_occupant_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return modals_occupant_setPrototypeOf(o, p);
}
function modals_occupant_createSuper(Derived) {
  var hasNativeReflectConstruct = modals_occupant_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = modals_occupant_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = modals_occupant_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return modals_occupant_possibleConstructorReturn(this, result);
  };
}
function modals_occupant_possibleConstructorReturn(self, call) {
  if (call && (modals_occupant_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 modals_occupant_assertThisInitialized(self);
}
function modals_occupant_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function modals_occupant_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 modals_occupant_getPrototypeOf(o) {
  modals_occupant_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return modals_occupant_getPrototypeOf(o);
}





var occupant_u = public_converse.env.u;
var OccupantModal = /*#__PURE__*/function (_BaseModal) {
  modals_occupant_inherits(OccupantModal, _BaseModal);
  var _super = modals_occupant_createSuper(OccupantModal);
  function OccupantModal() {
    var _this;
    modals_occupant_classCallCheck(this, OccupantModal);
    _this = _super.call(this);
    _this.addEventListener("affiliationChanged", function () {
      return _this.alert(__('Affiliation changed'));
    });
    _this.addEventListener("roleChanged", function () {
      return _this.alert(__('role changed'));
    });
    return _this;
  }
  modals_occupant_createClass(OccupantModal, [{
    key: "initialize",
    value: function initialize() {
      var _this$model,
        _this2 = this;
      modals_occupant_get(modals_occupant_getPrototypeOf(OccupantModal.prototype), "initialize", this).call(this);
      var model = (_this$model = this.model) !== null && _this$model !== void 0 ? _this$model : this.message;
      this.listenTo(model, 'change', function () {
        return _this2.render();
      });
      /**
       * Triggered once the OccupantModal has been initialized
       * @event _converse#occupantModalInitialized
       * @type { Object }
       * @example _converse.api.listen.on('occupantModalInitialized', data);
       */
      shared_api.trigger('occupantModalInitialized', {
        'model': this.model,
        'message': this.message
      });
    }
  }, {
    key: "getVcard",
    value: function getVcard() {
      var _this$model2;
      var model = (_this$model2 = this.model) !== null && _this$model2 !== void 0 ? _this$model2 : this.message;
      if (model.vcard) {
        return model.vcard;
      }
      var jid = (model === null || model === void 0 ? void 0 : model.get('jid')) || (model === null || model === void 0 ? void 0 : model.get('from'));
      return jid ? shared_converse.vcards.get(jid) : null;
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return templates_occupant(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      var _this$model3;
      var model = (_this$model3 = this.model) !== null && _this$model3 !== void 0 ? _this$model3 : this.message;
      return model === null || model === void 0 ? void 0 : model.getDisplayName();
    }
  }, {
    key: "addToContacts",
    value: function addToContacts() {
      var _this$model4;
      var model = (_this$model4 = this.model) !== null && _this$model4 !== void 0 ? _this$model4 : this.message;
      var jid = model.get('jid');
      if (jid) shared_api.modal.show('converse-add-contact-modal', {
        'model': new Model({
          jid: jid
        })
      });
    }
  }, {
    key: "toggleForm",
    value: function toggleForm(ev) {
      var toggle = occupant_u.ancestor(ev.target, '.toggle-form');
      var form = toggle.getAttribute('data-form');
      if (form === 'row-form') {
        this.show_role_form = !this.show_role_form;
      } else {
        this.show_affiliation_form = !this.show_affiliation_form;
      }
      this.render();
    }
  }]);
  return OccupantModal;
}(modal_modal);

shared_api.elements.define('converse-muc-occupant-modal', OccupantModal);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/moderator-tools.js
var moderator_tools_templateObject, moderator_tools_templateObject2, moderator_tools_templateObject3, moderator_tools_templateObject4, moderator_tools_templateObject5, moderator_tools_templateObject6, moderator_tools_templateObject7, moderator_tools_templateObject8, moderator_tools_templateObject9, moderator_tools_templateObject10, _templateObject11, _templateObject12, _templateObject13, _templateObject14, _templateObject15, _templateObject16, _templateObject17, _templateObject18, _templateObject19, _templateObject20, _templateObject21, _templateObject22;
function moderator_tools_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



function getRoleHelpText(role) {
  if (role === 'moderator') {
    return __("Moderators are privileged users who can change the roles of other users (except those with admin or owner affiliations.");
  } else if (role === 'participant') {
    return __("The default role, implies that you can read and write messages.");
  } else if (role == 'visitor') {
    return __("Visitors aren't allowed to write messages in a moderated multi-user chat.");
  }
}
function getAffiliationHelpText(aff) {
  if (aff === 'owner') {
    return __("Owner is the highest affiliation. Owners can modify roles and affiliations of all other users.");
  } else if (aff === 'admin') {
    return __("Admin is the 2nd highest affiliation. Admins can modify roles and affiliations of all other users except owners.");
  } else if (aff === 'outcast') {
    return __("To ban a user, you give them the affiliation of \"outcast\".");
  }
}
var role_option = function role_option(o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject || (moderator_tools_templateObject = moderator_tools_taggedTemplateLiteral(["\n    <option value=\"", "\"\n            ?selected=", "\n            title=\"", "\">", "</option>\n"])), o.item || '', o.item === o.role, getRoleHelpText(o.item), o.item);
};
var affiliation_option = function affiliation_option(o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject2 || (moderator_tools_templateObject2 = moderator_tools_taggedTemplateLiteral(["\n    <option value=\"", "\"\n            ?selected=", "\n            title=\"", "\">", "</option>\n"])), o.item || '', o.item === o.affiliation, getAffiliationHelpText(o.item), o.item);
};
var tplRoleFormToggle = function tplRoleFormToggle(o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject3 || (moderator_tools_templateObject3 = moderator_tools_taggedTemplateLiteral(["\n    <a href=\"#\" data-form=\"converse-muc-role-form\" class=\"toggle-form right\" color=\"var(--subdued-color)\" @click=", ">\n        <converse-icon class=\"fa fa-wrench\" size=\"1em\"></converse-icon>\n    </a>"])), o.toggleForm);
};
var tplRoleListItem = function tplRoleListItem(el, o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject4 || (moderator_tools_templateObject4 = moderator_tools_taggedTemplateLiteral(["\n    <li class=\"list-group-item\" data-nick=\"", "\">\n        <ul class=\"list-group\">\n            <li class=\"list-group-item active\">\n                <div><strong>JID:</strong> ", "</div>\n            </li>\n            <li class=\"list-group-item\">\n                <div><strong>Nickname:</strong> ", "</div>\n            </li>\n            <li class=\"list-group-item\">\n                <div><strong>Role:</strong> ", " ", "</div>\n                ", "\n            </li>\n        </ul>\n    </li>\n"])), o.item.nick, o.item.jid, o.item.nick, o.item.role, o.assignable_roles.length ? tplRoleFormToggle(o) : '', o.assignable_roles.length ? (0,external_lit_namespaceObject.html)(moderator_tools_templateObject5 || (moderator_tools_templateObject5 = moderator_tools_taggedTemplateLiteral(["<converse-muc-role-form class=\"hidden\" .muc=", " jid=", " role=", "></converse-muc-role-form>"])), el.muc, o.item.jid, o.item.role) : '');
};
var affiliation_form_toggle = function affiliation_form_toggle(o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject6 || (moderator_tools_templateObject6 = moderator_tools_taggedTemplateLiteral(["\n    <a href=\"#\" data-form=\"converse-muc-affiliation-form\" class=\"toggle-form right\" color=\"var(--subdued-color)\" @click=", ">\n        <converse-icon class=\"fa fa-wrench\" size=\"1em\"></converse-icon>\n    </a>"])), o.toggleForm);
};
var affiliation_list_item = function affiliation_list_item(el, o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject7 || (moderator_tools_templateObject7 = moderator_tools_taggedTemplateLiteral(["\n    <li class=\"list-group-item\" data-nick=\"", "\">\n        <ul class=\"list-group\">\n            <li class=\"list-group-item active\">\n                <div><strong>JID:</strong> ", "</div>\n            </li>\n            <li class=\"list-group-item\">\n                <div><strong>Nickname:</strong> ", "</div>\n            </li>\n            <li class=\"list-group-item\">\n                <div><strong>Affiliation:</strong> ", " ", "</div>\n                ", "\n            </li>\n        </ul>\n    </li>\n"])), o.item.nick, o.item.jid, o.item.nick, o.item.affiliation, o.assignable_affiliations.length ? affiliation_form_toggle(o) : '', o.assignable_affiliations.length ? (0,external_lit_namespaceObject.html)(moderator_tools_templateObject8 || (moderator_tools_templateObject8 = moderator_tools_taggedTemplateLiteral(["<converse-muc-affiliation-form class=\"hidden\" .muc=", " jid=", " affiliation=", "></converse-muc-affiliation-form>"])), el.muc, o.item.jid, o.item.affiliation) : '');
};
var tplNavigation = function tplNavigation(o) {
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject9 || (moderator_tools_templateObject9 = moderator_tools_taggedTemplateLiteral(["\n    <ul class=\"nav nav-pills justify-content-center\">\n        <li role=\"presentation\" class=\"nav-item\">\n            <a class=\"nav-link ", "\"\n               id=\"affiliations-tab\"\n               href=\"#affiliations-tabpanel\"\n               aria-controls=\"affiliations-tabpanel\"\n               role=\"tab\"\n               data-name=\"affiliations\"\n               @click=", ">Affiliations</a>\n        </li>\n        <li role=\"presentation\" class=\"nav-item\">\n            <a class=\"nav-link ", "\"\n               id=\"roles-tab\"\n               href=\"#roles-tabpanel\"\n               aria-controls=\"roles-tabpanel\"\n               role=\"tab\"\n               data-name=\"roles\"\n               @click=", ">Roles</a>\n        </li>\n    </ul>\n"])), o.tab === "affiliations" ? "active" : "", o.switchTab, o.tab === "roles" ? "active" : "", o.switchTab);
};
/* harmony default export */ const moderator_tools = (function (el, o) {
  var i18n_affiliation = __('Affiliation');
  var i18n_no_users_with_aff = __('No users with that affiliation found.');
  var i18n_no_users_with_role = __('No users with that role found.');
  var i18n_filter = __('Type here to filter the search results');
  var i18n_role = __('Role');
  var i18n_show_users = __('Show users');
  var i18n_helptext_role = __("Roles are assigned to users to grant or deny them certain abilities in a multi-user chat. " + "They're assigned either explicitly or implicitly as part of an affiliation. " + "A role that's not due to an affiliation, is only valid for the duration of the user's session.");
  var i18n_helptext_affiliation = __("An affiliation is a long-lived entitlement which typically implies a certain role and which " + "grants privileges and responsibilities. For example admins and owners automatically have the " + "moderator role.");
  var show_both_tabs = o.queryable_roles.length && o.queryable_affiliations.length;
  return (0,external_lit_namespaceObject.html)(moderator_tools_templateObject10 || (moderator_tools_templateObject10 = moderator_tools_taggedTemplateLiteral(["\n        ", "\n        ", "\n\n        <div class=\"tab-content\">\n\n            ", "\n\n            ", "\n        </div>"])), o.alert_message ? (0,external_lit_namespaceObject.html)(_templateObject11 || (_templateObject11 = moderator_tools_taggedTemplateLiteral(["<div class=\"alert alert-", "\" role=\"alert\">", "</div>"])), o.alert_type, o.alert_message) : '', show_both_tabs ? tplNavigation(o) : '', o.queryable_affiliations.length ? (0,external_lit_namespaceObject.html)(_templateObject12 || (_templateObject12 = moderator_tools_taggedTemplateLiteral(["\n            <div class=\"tab-pane tab-pane--columns ", "\" id=\"affiliations-tabpanel\" role=\"tabpanel\" aria-labelledby=\"affiliations-tab\">\n                <form class=\"converse-form query-affiliation\" @submit=", ">\n                    <p class=\"helptext pb-3\">", "</p>\n                    <div class=\"form-group\">\n                        <label for=\"affiliation\">\n                            <strong>", ":</strong>\n                        </label>\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                <select class=\"custom-select select-affiliation\" name=\"affiliation\">\n                                    ", "\n                                </select>\n                            </div>\n                            <div class=\"col\">\n                                <input type=\"submit\" class=\"btn btn-primary\" name=\"users_with_affiliation\" value=\"", "\"/>\n                            </div>\n                        </div>\n                        <div class=\"row\">\n                            <div class=\"col mt-3\">\n                                ", "\n                            </div>\n                        </div>\n\n                        ", "\n                    </div>\n                </form>\n                <div class=\"scrollable-container\">\n                    <ul class=\"list-group list-group--users\">\n                        ", "\n                        ", "\n\n                        ", "\n                    </ul>\n                </div>\n            </div>"])), o.tab === 'affiliations' ? 'active' : '', o.queryAffiliation, i18n_helptext_affiliation, i18n_affiliation, o.queryable_affiliations.map(function (item) {
    return affiliation_option(Object.assign({
      item: item
    }, o));
  }), i18n_show_users, Array.isArray(o.users_with_affiliation) && o.users_with_affiliation.length > 5 ? (0,external_lit_namespaceObject.html)(_templateObject13 || (_templateObject13 = moderator_tools_taggedTemplateLiteral(["<input class=\"form-control\" .value=\"", "\" @keyup=", " type=\"text\" name=\"filter\" placeholder=\"", "\"/>"])), o.affiliations_filter, o.filterAffiliationResults, i18n_filter) : '', getAffiliationHelpText(o.affiliation) ? (0,external_lit_namespaceObject.html)(_templateObject14 || (_templateObject14 = moderator_tools_taggedTemplateLiteral(["<div class=\"row\"><div class=\"col pt-2\"><p class=\"helptext pb-3\">", "</p></div></div>"])), getAffiliationHelpText(o.affiliation)) : '', o.loading_users_with_affiliation ? (0,external_lit_namespaceObject.html)(_templateObject15 || (_templateObject15 = moderator_tools_taggedTemplateLiteral(["<li class=\"list-group-item\"> ", " </li>"])), spinner()) : '', Array.isArray(o.users_with_affiliation) && o.users_with_affiliation.length === 0 ? (0,external_lit_namespaceObject.html)(_templateObject16 || (_templateObject16 = moderator_tools_taggedTemplateLiteral(["<li class=\"list-group-item\">", "</li>"])), i18n_no_users_with_aff) : '', o.users_with_affiliation instanceof Error ? (0,external_lit_namespaceObject.html)(_templateObject17 || (_templateObject17 = moderator_tools_taggedTemplateLiteral(["<li class=\"list-group-item\">", "</li>"])), o.users_with_affiliation.message) : (o.users_with_affiliation || []).map(function (item) {
    return (item.nick || item.jid).match(new RegExp(o.affiliations_filter, 'i')) ? affiliation_list_item(el, Object.assign({
      item: item
    }, o)) : '';
  })) : '', o.queryable_roles.length ? (0,external_lit_namespaceObject.html)(_templateObject18 || (_templateObject18 = moderator_tools_taggedTemplateLiteral(["\n            <div class=\"tab-pane tab-pane--columns ", "\" id=\"roles-tabpanel\" role=\"tabpanel\" aria-labelledby=\"roles-tab\">\n                <form class=\"converse-form query-role\" @submit=", ">\n                    <p class=\"helptext pb-3\">", "</p>\n                    <div class=\"form-group\">\n                        <label for=\"role\"><strong>", ":</strong></label>\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                <select class=\"custom-select select-role\" name=\"role\">\n                                    ", "\n                                </select>\n                            </div>\n                            <div class=\"col\">\n                                <input type=\"submit\" class=\"btn btn-primary\" name=\"users_with_role\" value=\"", "\"/>\n                            </div>\n                        </div>\n                        <div class=\"row\">\n                            <div class=\"col mt-3\">\n                                ", "\n                            </div>\n                        </div>\n\n                        ", "\n                    </div>\n                </form>\n                <div class=\"scrollable-container\">\n                    <ul class=\"list-group list-group--users\">\n                        ", "\n                        ", "\n                        ", "\n                    </ul>\n                </div>\n            </div>"])), o.tab === 'roles' ? 'active' : '', o.queryRole, i18n_helptext_role, i18n_role, o.queryable_roles.map(function (item) {
    return role_option(Object.assign({
      item: item
    }, o));
  }), i18n_show_users, Array.isArray(o.users_with_role) && o.users_with_role.length > 5 ? (0,external_lit_namespaceObject.html)(_templateObject19 || (_templateObject19 = moderator_tools_taggedTemplateLiteral(["<input class=\"form-control\" .value=\"", "\" @keyup=", " type=\"text\" name=\"filter\" placeholder=\"", "\"/>"])), o.roles_filter, o.filterRoleResults, i18n_filter) : '', getRoleHelpText(o.role) ? (0,external_lit_namespaceObject.html)(_templateObject20 || (_templateObject20 = moderator_tools_taggedTemplateLiteral(["<div class=\"row\"><div class=\"col pt-2\"><p class=\"helptext pb-3\">", "</p></div></div>"])), getRoleHelpText(o.role)) : '', o.loading_users_with_role ? (0,external_lit_namespaceObject.html)(_templateObject21 || (_templateObject21 = moderator_tools_taggedTemplateLiteral(["<li class=\"list-group-item\"> ", " </li>"])), spinner()) : '', o.users_with_role && o.users_with_role.length === 0 ? (0,external_lit_namespaceObject.html)(_templateObject22 || (_templateObject22 = moderator_tools_taggedTemplateLiteral(["<li class=\"list-group-item\">", "</li>"])), i18n_no_users_with_role) : '', (o.users_with_role || []).map(function (item) {
    return item.nick.match(o.roles_filter) ? tplRoleListItem(el, Object.assign({
      item: item
    }, o)) : '';
  })) : '');
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/moderator-tools.scss
var styles_moderator_tools = __webpack_require__(119);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/moderator-tools.scss

      
      
      
      
      
      
      
      
      

var moderator_tools_options = {};

moderator_tools_options.styleTagTransform = (styleTagTransform_default());
moderator_tools_options.setAttributes = (setAttributesWithoutAttributes_default());

      moderator_tools_options.insert = insertBySelector_default().bind(null, "head");
    
moderator_tools_options.domAPI = (styleDomAPI_default());
moderator_tools_options.insertStyleElement = (insertStyleElement_default());

var moderator_tools_update = injectStylesIntoStyleTag_default()(styles_moderator_tools/* default */.Z, moderator_tools_options);




       /* harmony default export */ const muc_views_styles_moderator_tools = (styles_moderator_tools/* default */.Z && styles_moderator_tools/* default */.Z.locals ? styles_moderator_tools/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/modtools.js
function modtools_typeof(obj) {
  "@babel/helpers - typeof";

  return modtools_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;
  }, modtools_typeof(obj);
}
function modtools_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  modtools_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" == modtools_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 modtools_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 modtools_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        modtools_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        modtools_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function modtools_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function modtools_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, modtools_toPropertyKey(descriptor.key), descriptor);
  }
}
function modtools_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) modtools_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) modtools_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modtools_toPropertyKey(arg) {
  var key = modtools_toPrimitive(arg, "string");
  return modtools_typeof(key) === "symbol" ? key : String(key);
}
function modtools_toPrimitive(input, hint) {
  if (modtools_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modtools_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function modtools_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) modtools_setPrototypeOf(subClass, superClass);
}
function modtools_setPrototypeOf(o, p) {
  modtools_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return modtools_setPrototypeOf(o, p);
}
function modtools_createSuper(Derived) {
  var hasNativeReflectConstruct = modtools_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = modtools_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = modtools_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return modtools_possibleConstructorReturn(this, result);
  };
}
function modtools_possibleConstructorReturn(self, call) {
  if (call && (modtools_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 modtools_assertThisInitialized(self);
}
function modtools_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function modtools_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 modtools_getPrototypeOf(o) {
  modtools_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return modtools_getPrototypeOf(o);
}









var modtools_u = public_converse.env.u;
var ModeratorTools = /*#__PURE__*/function (_CustomElement) {
  modtools_inherits(ModeratorTools, _CustomElement);
  var _super = modtools_createSuper(ModeratorTools);
  function ModeratorTools() {
    var _this;
    modtools_classCallCheck(this, ModeratorTools);
    _this = _super.call(this);
    _this.tab = 'affiliations';
    _this.affiliation = '';
    _this.affiliations_filter = '';
    _this.role = '';
    _this.roles_filter = '';
    _this.addEventListener("affiliationChanged", function () {
      _this.alert(__('Affiliation changed'), 'primary');
      _this.onSearchAffiliationChange();
      _this.requestUpdate();
    });
    _this.addEventListener("roleChanged", function () {
      _this.alert(__('Role changed'), 'primary');
      _this.requestUpdate();
    });
    return _this;
  }
  modtools_createClass(ModeratorTools, [{
    key: "updated",
    value: function updated(changed) {
      changed.has('role') && this.onSearchRoleChange();
      changed.has('affiliation') && this.onSearchAffiliationChange();
      changed.has('jid') && changed.get('jid') && this.initialize();
    }
  }, {
    key: "initialize",
    value: function () {
      var _initialize = modtools_asyncToGenerator( /*#__PURE__*/modtools_regeneratorRuntime().mark(function _callee() {
        var muc;
        return modtools_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.initialized = getOpenPromise();
              _context.next = 3;
              return shared_api.rooms.get(this.jid);
            case 3:
              muc = _context.sent;
              _context.next = 6;
              return muc.initialized;
            case 6:
              this.muc = muc;
              this.initialized.resolve();
            case 8:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this$muc,
        _this2 = this;
      if ((_this$muc = this.muc) !== null && _this$muc !== void 0 && _this$muc.occupants) {
        var occupant = this.muc.occupants.getOwnOccupant();
        return moderator_tools(this, {
          'affiliations_filter': this.affiliations_filter,
          'alert_message': this.alert_message,
          'alert_type': this.alert_type,
          'assignRole': function assignRole(ev) {
            return _this2.assignRole(ev);
          },
          'assignable_affiliations': getAssignableAffiliations(occupant),
          'assignable_roles': getAssignableRoles(occupant),
          'filterAffiliationResults': function filterAffiliationResults(ev) {
            return _this2.filterAffiliationResults(ev);
          },
          'filterRoleResults': function filterRoleResults(ev) {
            return _this2.filterRoleResults(ev);
          },
          'loading_users_with_affiliation': this.loading_users_with_affiliation,
          'queryAffiliation': function queryAffiliation(ev) {
            return _this2.queryAffiliation(ev);
          },
          'queryRole': function queryRole(ev) {
            return _this2.queryRole(ev);
          },
          'queryable_affiliations': AFFILIATIONS.filter(function (a) {
            return !shared_api.settings.get('modtools_disable_query').includes(a);
          }),
          'queryable_roles': ROLES.filter(function (a) {
            return !shared_api.settings.get('modtools_disable_query').includes(a);
          }),
          'roles_filter': this.roles_filter,
          'switchTab': function switchTab(ev) {
            return _this2.switchTab(ev);
          },
          'tab': this.tab,
          'toggleForm': function toggleForm(ev) {
            return _this2.toggleForm(ev);
          },
          'users_with_affiliation': this.users_with_affiliation,
          'users_with_role': this.users_with_role
        });
      } else {
        return '';
      }
    }
  }, {
    key: "switchTab",
    value: function switchTab(ev) {
      ev.stopPropagation();
      ev.preventDefault();
      this.tab = ev.target.getAttribute('data-name');
      this.requestUpdate();
    }
  }, {
    key: "onSearchAffiliationChange",
    value: function () {
      var _onSearchAffiliationChange = modtools_asyncToGenerator( /*#__PURE__*/modtools_regeneratorRuntime().mark(function _callee2() {
        var result;
        return modtools_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (this.affiliation) {
                _context2.next = 2;
                break;
              }
              return _context2.abrupt("return");
            case 2:
              _context2.next = 4;
              return this.initialized;
            case 4:
              this.clearAlert();
              this.loading_users_with_affiliation = true;
              this.users_with_affiliation = null;
              if (!this.shouldFetchAffiliationsList()) {
                _context2.next = 14;
                break;
              }
              _context2.next = 10;
              return getAffiliationList(this.affiliation, this.jid);
            case 10:
              result = _context2.sent;
              if (result instanceof Error) {
                this.alert(result.message, 'danger');
                this.users_with_affiliation = [];
              } else {
                this.users_with_affiliation = result;
              }
              _context2.next = 15;
              break;
            case 14:
              this.users_with_affiliation = this.muc.getOccupantsWithAffiliation(this.affiliation);
            case 15:
              this.loading_users_with_affiliation = false;
            case 16:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function onSearchAffiliationChange() {
        return _onSearchAffiliationChange.apply(this, arguments);
      }
      return onSearchAffiliationChange;
    }()
  }, {
    key: "onSearchRoleChange",
    value: function () {
      var _onSearchRoleChange = modtools_asyncToGenerator( /*#__PURE__*/modtools_regeneratorRuntime().mark(function _callee3() {
        return modtools_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (this.role) {
                _context3.next = 2;
                break;
              }
              return _context3.abrupt("return");
            case 2:
              _context3.next = 4;
              return this.initialized;
            case 4:
              this.clearAlert();
              this.users_with_role = this.muc.getOccupantsWithRole(this.role);
            case 6:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function onSearchRoleChange() {
        return _onSearchRoleChange.apply(this, arguments);
      }
      return onSearchRoleChange;
    }()
  }, {
    key: "shouldFetchAffiliationsList",
    value: function shouldFetchAffiliationsList() {
      var affiliation = this.affiliation;
      if (affiliation === 'none') {
        return false;
      }
      var auto_fetched_affs = getAutoFetchedAffiliationLists();
      if (auto_fetched_affs.includes(affiliation)) {
        return false;
      } else {
        return true;
      }
    }

    // eslint-disable-next-line class-methods-use-this
  }, {
    key: "toggleForm",
    value: function toggleForm(ev) {
      ev.stopPropagation();
      ev.preventDefault();
      var toggle = modtools_u.ancestor(ev.target, '.toggle-form');
      var sel = toggle.getAttribute('data-form');
      var form = modtools_u.ancestor(toggle, '.list-group-item').querySelector(sel);
      if (modtools_u.hasClass('hidden', form)) {
        modtools_u.removeClass('hidden', form);
      } else {
        modtools_u.addClass('hidden', form);
      }
    }
  }, {
    key: "filterRoleResults",
    value: function filterRoleResults(ev) {
      this.roles_filter = ev.target.value;
      this.render();
    }
  }, {
    key: "filterAffiliationResults",
    value: function filterAffiliationResults(ev) {
      this.affiliations_filter = ev.target.value;
    }
  }, {
    key: "queryRole",
    value: function queryRole(ev) {
      ev.stopPropagation();
      ev.preventDefault();
      var data = new FormData(ev.target);
      var role = data.get('role');
      this.role = null;
      this.role = role;
    }
  }, {
    key: "queryAffiliation",
    value: function queryAffiliation(ev) {
      ev.stopPropagation();
      ev.preventDefault();
      var data = new FormData(ev.target);
      var affiliation = data.get('affiliation');
      this.affiliation = null;
      this.affiliation = affiliation;
    }
  }, {
    key: "alert",
    value: function alert(message, type) {
      this.alert_message = message;
      this.alert_type = type;
    }
  }, {
    key: "clearAlert",
    value: function clearAlert() {
      this.alert_message = undefined;
      this.alert_type = undefined;
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        affiliation: {
          type: String
        },
        affiliations_filter: {
          type: String,
          attribute: false
        },
        alert_message: {
          type: String,
          attribute: false
        },
        alert_type: {
          type: String,
          attribute: false
        },
        jid: {
          type: String
        },
        muc: {
          type: Object,
          attribute: false
        },
        role: {
          type: String
        },
        roles_filter: {
          type: String,
          attribute: false
        },
        tab: {
          type: String
        },
        users_with_affiliation: {
          type: Array,
          attribute: false
        },
        users_with_role: {
          type: Array,
          attribute: false
        }
      };
    }
  }]);
  return ModeratorTools;
}(CustomElement);

shared_api.elements.define('converse-modtools', ModeratorTools);
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/moderator-tools.js
function moderator_tools_typeof(obj) {
  "@babel/helpers - typeof";

  return moderator_tools_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;
  }, moderator_tools_typeof(obj);
}
var modals_moderator_tools_templateObject;
function modals_moderator_tools_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function moderator_tools_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function moderator_tools_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, moderator_tools_toPropertyKey(descriptor.key), descriptor);
  }
}
function moderator_tools_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) moderator_tools_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) moderator_tools_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function moderator_tools_toPropertyKey(arg) {
  var key = moderator_tools_toPrimitive(arg, "string");
  return moderator_tools_typeof(key) === "symbol" ? key : String(key);
}
function moderator_tools_toPrimitive(input, hint) {
  if (moderator_tools_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (moderator_tools_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function moderator_tools_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) moderator_tools_setPrototypeOf(subClass, superClass);
}
function moderator_tools_setPrototypeOf(o, p) {
  moderator_tools_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return moderator_tools_setPrototypeOf(o, p);
}
function moderator_tools_createSuper(Derived) {
  var hasNativeReflectConstruct = moderator_tools_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = moderator_tools_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = moderator_tools_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return moderator_tools_possibleConstructorReturn(this, result);
  };
}
function moderator_tools_possibleConstructorReturn(self, call) {
  if (call && (moderator_tools_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 moderator_tools_assertThisInitialized(self);
}
function moderator_tools_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function moderator_tools_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 moderator_tools_getPrototypeOf(o) {
  moderator_tools_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return moderator_tools_getPrototypeOf(o);
}





var ModeratorToolsModal = /*#__PURE__*/function (_BaseModal) {
  moderator_tools_inherits(ModeratorToolsModal, _BaseModal);
  var _super = moderator_tools_createSuper(ModeratorToolsModal);
  function ModeratorToolsModal(options) {
    var _this;
    moderator_tools_classCallCheck(this, ModeratorToolsModal);
    _this = _super.call(this, options);
    _this.id = "converse-modtools-modal";
    return _this;
  }
  moderator_tools_createClass(ModeratorToolsModal, [{
    key: "renderModal",
    value: function renderModal() {
      return (0,external_lit_namespaceObject.html)(modals_moderator_tools_templateObject || (modals_moderator_tools_templateObject = modals_moderator_tools_taggedTemplateLiteral(["<converse-modtools jid=", " affiliation=", "></converse-modtools>"])), this.jid, this.affiliation);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Moderator Tools');
    }
  }]);
  return ModeratorToolsModal;
}(modal_modal);

shared_api.elements.define('converse-modtools-modal', ModeratorToolsModal);
;// CONCATENATED MODULE: ./src/plugins/muc-views/utils.js
function muc_views_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_utils_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;
  }, muc_views_utils_typeof(obj);
}
var utils_templateObject, utils_templateObject2, utils_templateObject3, utils_templateObject4, utils_templateObject5, utils_templateObject6, utils_templateObject7, utils_templateObject8, utils_templateObject9;
function muc_views_utils_toConsumableArray(arr) {
  return muc_views_utils_arrayWithoutHoles(arr) || muc_views_utils_iterableToArray(arr) || muc_views_utils_unsupportedIterableToArray(arr) || muc_views_utils_nonIterableSpread();
}
function muc_views_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function muc_views_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return muc_views_utils_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 muc_views_utils_arrayLikeToArray(o, minLen);
}
function muc_views_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function muc_views_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return muc_views_utils_arrayLikeToArray(arr);
}
function muc_views_utils_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 muc_views_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_utils_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" == muc_views_utils_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 utils_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function muc_views_utils_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 muc_views_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}








var muc_views_utils_converse$env = public_converse.env,
  muc_views_utils_Strophe = muc_views_utils_converse$env.Strophe,
  muc_views_utils_u = muc_views_utils_converse$env.u;
var COMMAND_TO_AFFILIATION = {
  'admin': 'admin',
  'ban': 'outcast',
  'member': 'member',
  'owner': 'owner',
  'revoke': 'none'
};
var COMMAND_TO_ROLE = {
  'deop': 'participant',
  'kick': 'none',
  'mute': 'visitor',
  'op': 'moderator',
  'voice': 'participant'
};

/**
 * Presents a confirmation modal to the user asking them to accept or decline a
 * MUC invitation.
 * @async
 */
function confirmDirectMUCInvitation(_ref) {
  var contact = _ref.contact,
    jid = _ref.jid,
    reason = _ref.reason;
  if (!reason) {
    return shared_api.confirm(__('%1$s has invited you to join a groupchat: %2$s', contact, jid));
  } else {
    return shared_api.confirm(__('%1$s has invited you to join a groupchat: %2$s, and left the following reason: "%3$s"', contact, jid, reason));
  }
}
function clearHistory(jid) {
  if (shared_converse.router.history.getFragment() === "converse/room?jid=".concat(jid)) {
    shared_converse.router.navigate('');
  }
}
function destroyMUC(_x) {
  return _destroyMUC.apply(this, arguments);
}
function _destroyMUC() {
  _destroyMUC = muc_views_utils_asyncToGenerator( /*#__PURE__*/muc_views_utils_regeneratorRuntime().mark(function _callee(model) {
    var messages, fields, _fields$filter$pop, _fields$filter$pop2, reason, newjid;
    return muc_views_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          messages = [__('Are you sure you want to destroy this groupchat?')];
          fields = [{
            'name': 'challenge',
            'label': __('Please enter the XMPP address of this groupchat to confirm'),
            'challenge': model.get('jid'),
            'placeholder': __('name@example.org'),
            'required': true
          }, {
            'name': 'reason',
            'label': __('Optional reason for destroying this groupchat'),
            'placeholder': __('Reason')
          }, {
            'name': 'newjid',
            'label': __('Optional XMPP address for a new groupchat that replaces this one'),
            'placeholder': __('replacement@example.org')
          }];
          _context.prev = 2;
          _context.next = 5;
          return shared_api.confirm(__('Confirm'), messages, fields);
        case 5:
          fields = _context.sent;
          reason = (_fields$filter$pop = fields.filter(function (f) {
            return f.name === 'reason';
          }).pop()) === null || _fields$filter$pop === void 0 ? void 0 : _fields$filter$pop.value;
          newjid = (_fields$filter$pop2 = fields.filter(function (f) {
            return f.name === 'newjid';
          }).pop()) === null || _fields$filter$pop2 === void 0 ? void 0 : _fields$filter$pop2.value;
          return _context.abrupt("return", model.sendDestroyIQ(reason, newjid).then(function () {
            return model.close();
          }));
        case 11:
          _context.prev = 11;
          _context.t0 = _context["catch"](2);
          log.error(_context.t0);
        case 14:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[2, 11]]);
  }));
  return _destroyMUC.apply(this, arguments);
}
function getNicknameRequiredTemplate(model) {
  var jid = model.get('jid');
  if (shared_api.settings.get('muc_show_logs_before_join')) {
    return (0,external_lit_namespaceObject.html)(utils_templateObject || (utils_templateObject = utils_taggedTemplateLiteral(["<converse-muc-chatarea jid=\"", "\"></converse-muc-chatarea>"])), jid);
  } else {
    return (0,external_lit_namespaceObject.html)(utils_templateObject2 || (utils_templateObject2 = utils_taggedTemplateLiteral(["<converse-muc-nickname-form jid=\"", "\"></converse-muc-nickname-form>"])), jid);
  }
}
function getChatRoomBodyTemplate(o) {
  var view = o.model.session.get('view');
  var jid = o.model.get('jid');
  var RS = public_converse.ROOMSTATUS;
  var conn_status = o.model.session.get('connection_status');
  if (view === public_converse.MUC.VIEWS.CONFIG) {
    return (0,external_lit_namespaceObject.html)(utils_templateObject3 || (utils_templateObject3 = utils_taggedTemplateLiteral(["<converse-muc-config-form class=\"muc-form-container\" jid=\"", "\"></converse-muc-config-form>"])), jid);
  } else {
    return (0,external_lit_namespaceObject.html)(utils_templateObject4 || (utils_templateObject4 = utils_taggedTemplateLiteral(["\n            ", "\n            ", "\n            ", "\n            ", "\n            ", "\n            ", "\n            ", "\n        "])), conn_status == RS.PASSWORD_REQUIRED ? (0,external_lit_namespaceObject.html)(utils_templateObject5 || (utils_templateObject5 = utils_taggedTemplateLiteral(["<converse-muc-password-form class=\"muc-form-container\" jid=\"", "\"></converse-muc-password-form>"])), jid) : '', conn_status == RS.ENTERED ? (0,external_lit_namespaceObject.html)(utils_templateObject6 || (utils_templateObject6 = utils_taggedTemplateLiteral(["<converse-muc-chatarea jid=\"", "\"></converse-muc-chatarea>"])), jid) : '', conn_status == RS.CONNECTING ? spinner() : '', conn_status == RS.NICKNAME_REQUIRED ? getNicknameRequiredTemplate(o.model) : '', conn_status == RS.DISCONNECTED ? (0,external_lit_namespaceObject.html)(utils_templateObject7 || (utils_templateObject7 = utils_taggedTemplateLiteral(["<converse-muc-disconnected jid=\"", "\"></converse-muc-disconnected>"])), jid) : '', conn_status == RS.BANNED ? (0,external_lit_namespaceObject.html)(utils_templateObject8 || (utils_templateObject8 = utils_taggedTemplateLiteral(["<converse-muc-disconnected jid=\"", "\"></converse-muc-disconnected>"])), jid) : '', conn_status == RS.DESTROYED ? (0,external_lit_namespaceObject.html)(utils_templateObject9 || (utils_templateObject9 = utils_taggedTemplateLiteral(["<converse-muc-destroyed jid=\"", "\"></converse-muc-destroyed>"])), jid) : '');
  }
}
function getAutoCompleteListItem(text, input) {
  input = input.trim();
  var element = document.createElement('li');
  element.setAttribute('aria-selected', 'false');
  if (shared_api.settings.get('muc_mention_autocomplete_show_avatar')) {
    var img = document.createElement('img');
    var dataUri = 'data:' + shared_converse.DEFAULT_IMAGE_TYPE + ';base64,' + shared_converse.DEFAULT_IMAGE;
    if (shared_converse.vcards) {
      var vcard = shared_converse.vcards.findWhere({
        'nickname': text
      });
      if (vcard) dataUri = 'data:' + vcard.get('image_type') + ';base64,' + vcard.get('image');
    }
    img.setAttribute('src', dataUri);
    img.setAttribute('width', '22');
    img.setAttribute('class', 'avatar avatar-autocomplete');
    element.appendChild(img);
  }
  var regex = new RegExp('(' + input + ')', 'ig');
  var parts = input ? text.split(regex) : [text];
  parts.forEach(function (txt) {
    if (input && txt.match(regex)) {
      var match = document.createElement('mark');
      match.textContent = txt;
      element.appendChild(match);
    } else {
      element.appendChild(document.createTextNode(txt));
    }
  });
  return element;
}
function getAutoCompleteList() {
  return _getAutoCompleteList.apply(this, arguments);
}
function _getAutoCompleteList() {
  _getAutoCompleteList = muc_views_utils_asyncToGenerator( /*#__PURE__*/muc_views_utils_regeneratorRuntime().mark(function _callee2() {
    var models, jids;
    return muc_views_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.t0 = [];
          _context2.t1 = muc_views_utils_toConsumableArray;
          _context2.next = 4;
          return shared_api.rooms.get();
        case 4:
          _context2.t2 = _context2.sent;
          _context2.t3 = (0, _context2.t1)(_context2.t2);
          _context2.t4 = muc_views_utils_toConsumableArray;
          _context2.next = 9;
          return shared_api.contacts.get();
        case 9:
          _context2.t5 = _context2.sent;
          _context2.t6 = (0, _context2.t4)(_context2.t5);
          models = _context2.t0.concat.call(_context2.t0, _context2.t3, _context2.t6);
          jids = muc_views_utils_toConsumableArray(new Set(models.map(function (o) {
            return muc_views_utils_Strophe.getDomainFromJid(o.get('jid'));
          })));
          return _context2.abrupt("return", jids);
        case 14:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _getAutoCompleteList.apply(this, arguments);
}
function setRole(muc, command, args) {
  var required_affiliations = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  var required_roles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  var role = COMMAND_TO_ROLE[command];
  if (!role) {
    throw Error("ChatRoomView#setRole called with invalid command: ".concat(command));
  }
  if (!muc.verifyAffiliations(required_affiliations) || !muc.verifyRoles(required_roles)) {
    return false;
  }
  if (!muc.validateRoleOrAffiliationChangeArgs(command, args)) {
    return false;
  }
  var nick_or_jid = muc.getNickOrJIDFromCommandArgs(args);
  if (!nick_or_jid) {
    return false;
  }
  var reason = args.split(nick_or_jid, 2)[1].trim();
  // We're guaranteed to have an occupant due to getNickOrJIDFromCommandArgs
  var occupant = muc.getOccupant(nick_or_jid);
  muc.setRole(occupant, role, reason, undefined, function (e) {
    return muc.onCommandError(e);
  });
  return true;
}
function verifyAndSetAffiliation(muc, command, args, required_affiliations) {
  var affiliation = COMMAND_TO_AFFILIATION[command];
  if (!affiliation) {
    throw Error("verifyAffiliations called with invalid command: ".concat(command));
  }
  if (!muc.verifyAffiliations(required_affiliations)) {
    return false;
  }
  if (!muc.validateRoleOrAffiliationChangeArgs(command, args)) {
    return false;
  }
  var nick_or_jid = muc.getNickOrJIDFromCommandArgs(args);
  if (!nick_or_jid) {
    return false;
  }
  var jid;
  var reason = args.split(nick_or_jid, 2)[1].trim();
  var occupant = muc.getOccupant(nick_or_jid);
  if (occupant) {
    jid = occupant.get('jid');
  } else {
    if (muc_views_utils_u.isValidJID(nick_or_jid)) {
      jid = nick_or_jid;
    } else {
      var message = __("Couldn't find a participant with that nickname. " + 'They might have left the groupchat.');
      muc.createMessage({
        message: message,
        'type': 'error'
      });
      return;
    }
  }
  var attrs = {
    jid: jid,
    reason: reason
  };
  if (occupant && shared_api.settings.get('auto_register_muc_nickname')) {
    attrs['nick'] = occupant.get('nick');
  }
  setAffiliation(affiliation, muc.get('jid'), [attrs]).then(function () {
    return muc.occupants.fetchMembers();
  }).catch(function (err) {
    return muc.onCommandError(err);
  });
}
function showModeratorToolsModal(muc, affiliation) {
  if (!muc.verifyRoles(['moderator'])) {
    return;
  }
  var modal = shared_api.modal.get('converse-modtools-modal');
  if (modal) {
    modal.affiliation = affiliation;
    modal.render();
  } else {
    modal = shared_api.modal.create('converse-modtools-modal', {
      affiliation: affiliation,
      'jid': muc.get('jid')
    });
  }
  modal.show();
}
function showOccupantModal(ev, occupant) {
  shared_api.modal.show('converse-muc-occupant-modal', {
    'model': occupant
  }, ev);
}
function parseMessageForMUCCommands(data, handled) {
  var _model$getAllowedComm;
  var model = data.model;
  if (handled || model.get('type') !== shared_converse.CHATROOMS_TYPE || shared_api.settings.get('muc_disable_slash_commands') && !Array.isArray(shared_api.settings.get('muc_disable_slash_commands'))) {
    return handled;
  }
  var text = data.text;
  text = text.replace(/^\s*/, '');
  var command = (text.match(/^\/([a-zA-Z]*) ?/) || ['']).pop().toLowerCase();
  if (!command) {
    return false;
  }
  var args = text.slice(('/' + command).length + 1).trim();
  var allowed_commands = (_model$getAllowedComm = model.getAllowedCommands()) !== null && _model$getAllowedComm !== void 0 ? _model$getAllowedComm : [];
  if (command === 'admin' && allowed_commands.includes(command)) {
    verifyAndSetAffiliation(model, command, args, ['owner']);
    return true;
  } else if (command === 'ban' && allowed_commands.includes(command)) {
    verifyAndSetAffiliation(model, command, args, ['admin', 'owner']);
    return true;
  } else if (command === 'modtools' && allowed_commands.includes(command)) {
    showModeratorToolsModal(model, args);
    return true;
  } else if (command === 'deop' && allowed_commands.includes(command)) {
    // FIXME: /deop only applies to setting a moderators
    // role to "participant" (which only admin/owner can
    // do). Moderators can however set non-moderator's role
    // to participant (e.g. visitor => participant).
    // Currently we don't distinguish between these two
    // cases.
    setRole(model, command, args, ['admin', 'owner']);
    return true;
  } else if (command === 'destroy' && allowed_commands.includes(command)) {
    if (!model.verifyAffiliations(['owner'])) {
      return true;
    }
    destroyMUC(model).catch(function (e) {
      return model.onCommandError(e);
    });
    return true;
  } else if (command === 'help' && allowed_commands.includes(command)) {
    model.set({
      'show_help_messages': false
    }, {
      'silent': true
    });
    model.set({
      'show_help_messages': true
    });
    return true;
  } else if (command === 'kick' && allowed_commands.includes(command)) {
    setRole(model, command, args, [], ['moderator']);
    return true;
  } else if (command === 'mute' && allowed_commands.includes(command)) {
    setRole(model, command, args, [], ['moderator']);
    return true;
  } else if (command === 'member' && allowed_commands.includes(command)) {
    verifyAndSetAffiliation(model, command, args, ['admin', 'owner']);
    return true;
  } else if (command === 'nick' && allowed_commands.includes(command)) {
    if (!model.verifyRoles(['visitor', 'participant', 'moderator'])) {
      return true;
    } else if (args.length === 0) {
      // e.g. Your nickname is "coolguy69"
      var message = __('Your nickname is "%1$s"', model.get('nick'));
      model.createMessage({
        message: message,
        'type': 'error'
      });
    } else {
      model.setNickname(args);
    }
    return true;
  } else if (command === 'owner' && allowed_commands.includes(command)) {
    verifyAndSetAffiliation(model, command, args, ['owner']);
    return true;
  } else if (command === 'op' && allowed_commands.includes(command)) {
    setRole(model, command, args, ['admin', 'owner']);
    return true;
  } else if (command === 'register' && allowed_commands.includes(command)) {
    if (args.length > 1) {
      model.createMessage({
        'message': __('Error: invalid number of arguments'),
        'type': 'error'
      });
    } else {
      model.registerNickname().then(function (err_msg) {
        err_msg && model.createMessage({
          'message': err_msg,
          'type': 'error'
        });
      });
    }
    return true;
  } else if (command === 'revoke' && allowed_commands.includes(command)) {
    verifyAndSetAffiliation(model, command, args, ['admin', 'owner']);
    return true;
  } else if (command === 'topic' && allowed_commands.includes(command) || command === 'subject' && allowed_commands.includes(command)) {
    model.setSubject(args);
    return true;
  } else if (command === 'voice' && allowed_commands.includes(command)) {
    setRole(model, command, args, [], ['moderator']);
    return true;
  } else {
    return false;
  }
}
;// CONCATENATED MODULE: ./src/plugins/adhoc-views/templates/ad-hoc.js
var ad_hoc_templateObject, ad_hoc_templateObject2, ad_hoc_templateObject3, ad_hoc_templateObject4, ad_hoc_templateObject5;
function ad_hoc_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





/* harmony default export */ const ad_hoc = (function (el) {
  var i18n_choose_service = __('On which entity do you want to run commands?');
  var i18n_choose_service_instructions = __('Certain XMPP services and entities allow privileged users to execute ad-hoc commands on them.');
  var i18n_commands_found = __('Commands found');
  var i18n_fetch_commands = __('List available commands');
  var i18n_jid_placeholder = __('XMPP Address');
  var i18n_no_commands_found = __('No commands found');
  return (0,external_lit_namespaceObject.html)(ad_hoc_templateObject || (ad_hoc_templateObject = ad_hoc_taggedTemplateLiteral(["\n        ", "\n        ", "\n\n        <form class=\"converse-form\" @submit=", ">\n            <fieldset class=\"form-group\">\n                <label>\n                    ", "\n                    <p class=\"form-help\">", "</p>\n                    <converse-autocomplete\n                        .getAutoCompleteList=\"", "\"\n                        required\n                        placeholder=\"", "\"\n                        name=\"jid\">\n                    </converse-autocomplete>\n                </label>\n            </fieldset>\n            <fieldset class=\"form-group\">\n                ", "\n            </fieldset>\n            ", "\n\n        </form>\n    "])), el.alert ? (0,external_lit_namespaceObject.html)(ad_hoc_templateObject2 || (ad_hoc_templateObject2 = ad_hoc_taggedTemplateLiteral(["<div class=\"alert alert-", "\" role=\"alert\">", "</div>"])), el.alert_type, el.alert) : '', el.note ? (0,external_lit_namespaceObject.html)(ad_hoc_templateObject3 || (ad_hoc_templateObject3 = ad_hoc_taggedTemplateLiteral(["<p class=\"form-help\">", "</p>"])), el.note) : '', el.fetchCommands, i18n_choose_service, i18n_choose_service_instructions, getAutoCompleteList, i18n_jid_placeholder, el.fetching ? spinner() : (0,external_lit_namespaceObject.html)(ad_hoc_templateObject4 || (ad_hoc_templateObject4 = ad_hoc_taggedTemplateLiteral(["<input type=\"submit\" class=\"btn btn-primary\" value=\"", "\">"])), i18n_fetch_commands), el.view === 'list-commands' ? (0,external_lit_namespaceObject.html)(ad_hoc_templateObject5 || (ad_hoc_templateObject5 = ad_hoc_taggedTemplateLiteral(["\n            <fieldset class=\"form-group\">\n                <ul class=\"list-group\">\n                    <li class=\"list-group-item active\">", ":</li>\n                    ", "\n                </ul>\n            </fieldset>"])), el.commands.length ? i18n_commands_found : i18n_no_commands_found, el.commands.map(function (cmd) {
    return ad_hoc_command(el, cmd);
  })) : '');
});
;// CONCATENATED MODULE: ./src/plugins/adhoc-views/adhoc-commands.js
function adhoc_commands_typeof(obj) {
  "@babel/helpers - typeof";

  return adhoc_commands_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;
  }, adhoc_commands_typeof(obj);
}
function adhoc_commands_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  adhoc_commands_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" == adhoc_commands_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 adhoc_commands_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 adhoc_commands_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        adhoc_commands_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        adhoc_commands_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function adhoc_commands_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function adhoc_commands_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, adhoc_commands_toPropertyKey(descriptor.key), descriptor);
  }
}
function adhoc_commands_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) adhoc_commands_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) adhoc_commands_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function adhoc_commands_toPropertyKey(arg) {
  var key = adhoc_commands_toPrimitive(arg, "string");
  return adhoc_commands_typeof(key) === "symbol" ? key : String(key);
}
function adhoc_commands_toPrimitive(input, hint) {
  if (adhoc_commands_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (adhoc_commands_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function adhoc_commands_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) adhoc_commands_setPrototypeOf(subClass, superClass);
}
function adhoc_commands_setPrototypeOf(o, p) {
  adhoc_commands_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return adhoc_commands_setPrototypeOf(o, p);
}
function adhoc_commands_createSuper(Derived) {
  var hasNativeReflectConstruct = adhoc_commands_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = adhoc_commands_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = adhoc_commands_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return adhoc_commands_possibleConstructorReturn(this, result);
  };
}
function adhoc_commands_possibleConstructorReturn(self, call) {
  if (call && (adhoc_commands_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 adhoc_commands_assertThisInitialized(self);
}
function adhoc_commands_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function adhoc_commands_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 adhoc_commands_getPrototypeOf(o) {
  adhoc_commands_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return adhoc_commands_getPrototypeOf(o);
}







var adhoc_commands_converse$env = public_converse.env,
  adhoc_commands_Strophe = adhoc_commands_converse$env.Strophe,
  adhoc_commands_sizzle = adhoc_commands_converse$env.sizzle;
var AdHocCommands = /*#__PURE__*/function (_CustomElement) {
  adhoc_commands_inherits(AdHocCommands, _CustomElement);
  var _super = adhoc_commands_createSuper(AdHocCommands);
  function AdHocCommands() {
    var _this;
    adhoc_commands_classCallCheck(this, AdHocCommands);
    _this = _super.call(this);
    _this.view = 'choose-service';
    _this.fetching = false;
    _this.showform = '';
    _this.commands = [];
    return _this;
  }
  adhoc_commands_createClass(AdHocCommands, [{
    key: "render",
    value: function render() {
      return ad_hoc(this);
    }
  }, {
    key: "fetchCommands",
    value: function () {
      var _fetchCommands = adhoc_commands_asyncToGenerator( /*#__PURE__*/adhoc_commands_regeneratorRuntime().mark(function _callee(ev) {
        var form_data, jid, supported;
        return adhoc_commands_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev.preventDefault();
              delete this.alert_type;
              delete this.alert;
              this.fetching = true;
              form_data = new FormData(ev.target);
              jid = form_data.get('jid').trim();
              _context.prev = 6;
              _context.next = 9;
              return shared_api.disco.supports(adhoc_commands_Strophe.NS.ADHOC, jid);
            case 9:
              supported = _context.sent;
              _context.next = 15;
              break;
            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](6);
              log.error(_context.t0);
            case 15:
              _context.prev = 15;
              this.fetching = false;
              return _context.finish(15);
            case 18:
              if (!supported) {
                _context.next = 36;
                break;
              }
              _context.prev = 19;
              _context.next = 22;
              return shared_api.adhoc.getCommands(jid);
            case 22:
              this.commands = _context.sent;
              this.view = 'list-commands';
              _context.next = 34;
              break;
            case 26:
              _context.prev = 26;
              _context.t1 = _context["catch"](19);
              log.error(_context.t1);
              this.alert_type = 'danger';
              this.alert = __('Sorry, an error occurred while looking for commands on that entity.');
              this.commands = [];
              log.error(_context.t1);
              return _context.abrupt("return");
            case 34:
              _context.next = 38;
              break;
            case 36:
              this.alert_type = 'danger';
              this.alert = __("The specified entity doesn't support ad-hoc commands");
            case 38:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[6, 12, 15, 18], [19, 26]]);
      }));
      function fetchCommands(_x) {
        return _fetchCommands.apply(this, arguments);
      }
      return fetchCommands;
    }()
  }, {
    key: "toggleCommandForm",
    value: function () {
      var _toggleCommandForm = adhoc_commands_asyncToGenerator( /*#__PURE__*/adhoc_commands_regeneratorRuntime().mark(function _callee2(ev) {
        var node, cmd, form;
        return adhoc_commands_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev.preventDefault();
              node = ev.target.getAttribute('data-command-node');
              cmd = this.commands.filter(function (c) {
                return c.node === node;
              })[0];
              if (!(this.showform === node)) {
                _context2.next = 8;
                break;
              }
              this.showform = '';
              this.requestUpdate();
              _context2.next = 16;
              break;
            case 8:
              _context2.next = 10;
              return shared_api.adhoc.fetchCommandForm(cmd);
            case 10:
              form = _context2.sent;
              cmd.sessionid = form.sessionid;
              cmd.instructions = form.instructions;
              cmd.fields = form.fields;
              cmd.actions = form.actions;
              this.showform = node;
            case 16:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function toggleCommandForm(_x2) {
        return _toggleCommandForm.apply(this, arguments);
      }
      return toggleCommandForm;
    }()
  }, {
    key: "executeAction",
    value: function executeAction(ev) {
      ev.preventDefault();
      var action = ev.target.getAttribute('data-action');
      if (['execute', 'next', 'prev', 'complete'].includes(action)) {
        this.runCommand(ev.target.form, action);
      } else {
        log.error("Unknown action: ".concat(action));
      }
    }
  }, {
    key: "clearCommand",
    value: function clearCommand(cmd) {
      delete cmd.alert;
      delete cmd.instructions;
      delete cmd.sessionid;
      delete cmd.alert_type;
      cmd.fields = [];
      cmd.acions = [];
      this.showform = '';
    }
  }, {
    key: "runCommand",
    value: function () {
      var _runCommand = adhoc_commands_asyncToGenerator( /*#__PURE__*/adhoc_commands_regeneratorRuntime().mark(function _callee3(form, action) {
        var form_data, jid, node, cmd, inputs, response, fields, status, note, instructions, actions;
        return adhoc_commands_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              form_data = new FormData(form);
              jid = form_data.get('command_jid').trim();
              node = form_data.get('command_node').trim();
              cmd = this.commands.filter(function (c) {
                return c.node === node;
              })[0];
              delete cmd.alert;
              this.requestUpdate();
              inputs = action === 'prev' ? [] : adhoc_commands_sizzle(':input:not([type=button]):not([type=submit])', form).filter(function (i) {
                return !['command_jid', 'command_node'].includes(i.getAttribute('name'));
              }).map(getNameAndValue).filter(function (n) {
                return n;
              });
              _context3.next = 9;
              return shared_api.adhoc.runCommand(jid, cmd.sessionid, cmd.node, action, inputs);
            case 9:
              response = _context3.sent;
              fields = response.fields, status = response.status, note = response.note, instructions = response.instructions, actions = response.actions;
              if (!(status === 'error')) {
                _context3.next = 15;
                break;
              }
              cmd.alert_type = 'danger';
              cmd.alert = __('Sorry, an error occurred while trying to execute the command. See the developer console for details');
              return _context3.abrupt("return", this.requestUpdate());
            case 15:
              if (status === 'executing') {
                cmd.alert = __('Executing');
                cmd.fields = fields;
                cmd.instructions = instructions;
                cmd.alert_type = 'primary';
                cmd.actions = actions;
              } else if (status === 'completed') {
                this.alert_type = 'primary';
                this.alert = __('Completed');
                this.note = note;
                this.clearCommand(cmd);
              } else {
                log.error("Unexpected status for ad-hoc command: ".concat(status));
                cmd.alert = __('Completed');
                cmd.alert_type = 'primary';
              }
              this.requestUpdate();
            case 17:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function runCommand(_x3, _x4) {
        return _runCommand.apply(this, arguments);
      }
      return runCommand;
    }()
  }, {
    key: "cancel",
    value: function () {
      var _cancel = adhoc_commands_asyncToGenerator( /*#__PURE__*/adhoc_commands_regeneratorRuntime().mark(function _callee4(ev) {
        var form_data, jid, node, cmd, _yield$api$adhoc$runC, status;
        return adhoc_commands_regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              ev.preventDefault();
              this.showform = '';
              this.requestUpdate();
              form_data = new FormData(ev.target.form);
              jid = form_data.get('command_jid').trim();
              node = form_data.get('command_node').trim();
              cmd = this.commands.filter(function (c) {
                return c.node === node;
              })[0];
              delete cmd.alert;
              this.requestUpdate();
              _context4.next = 11;
              return shared_api.adhoc.runCommand(jid, cmd.sessionid, cmd.node, 'cancel', []);
            case 11:
              _yield$api$adhoc$runC = _context4.sent;
              status = _yield$api$adhoc$runC.status;
              if (status === 'error') {
                cmd.alert_type = 'danger';
                cmd.alert = __('An error occurred while trying to cancel the command. See the developer console for details');
              } else if (status === 'canceled') {
                this.alert_type = '';
                this.alert = '';
                this.clearCommand(cmd);
              } else {
                log.error("Unexpected status for ad-hoc command: ".concat(status));
                cmd.alert = __('Error: unexpected result');
                cmd.alert_type = 'danger';
              }
              this.requestUpdate();
            case 15:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function cancel(_x5) {
        return _cancel.apply(this, arguments);
      }
      return cancel;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        'alert': {
          type: String
        },
        'alert_type': {
          type: String
        },
        'commands': {
          type: Array
        },
        'fetching': {
          type: Boolean
        },
        'showform': {
          type: String
        },
        'view': {
          type: String
        }
      };
    }
  }]);
  return AdHocCommands;
}(CustomElement);

shared_api.elements.define('converse-adhoc-commands', AdHocCommands);
;// CONCATENATED MODULE: ./src/plugins/adhoc-views/index.js
/**
 * @description
 *  Converse.js plugin which provides the UI for XEP-0050 Ad-Hoc commands
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


public_converse.plugins.add('converse-adhoc-views', {
  dependencies: ["converse-controlbox", "converse-muc"],
  initialize: function initialize() {
    shared_api.settings.extend({
      'allow_adhoc_commands': true
    });
  }
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInvoke.js






/**
 * The base implementation of `_.invoke` without support for individual
 * method arguments.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the method to invoke.
 * @param {Array} args The arguments to invoke the method with.
 * @returns {*} Returns the result of the invoked method.
 */
function baseInvoke(object, path, args) {
  path = _castPath(path, object);
  object = _parent(object, path);
  var func = object == null ? object : object[_toKey(lodash_es_last(path))];
  return func == null ? undefined : _apply(func, object, args);
}
/* harmony default export */ const _baseInvoke = (baseInvoke);
;// CONCATENATED MODULE: ./node_modules/lodash-es/invokeMap.js






/**
 * Invokes the method at `path` of each element in `collection`, returning
 * an array of the results of each invoked method. Any additional arguments
 * are provided to each invoked method. If `path` is a function, it's invoked
 * for, and `this` bound to, each element in `collection`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Array|Function|string} path The path of the method to invoke or
 *  the function invoked per iteration.
 * @param {...*} [args] The arguments to invoke each method with.
 * @returns {Array} Returns the array of results.
 * @example
 *
 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
 * // => [[1, 5, 7], [1, 2, 3]]
 *
 * _.invokeMap([123, 456], String.prototype.split, '');
 * // => [['1', '2', '3'], ['4', '5', '6']]
 */
var invokeMap = _baseRest(function (collection, path, args) {
  var index = -1,
    isFunc = typeof path == 'function',
    result = lodash_es_isArrayLike(collection) ? Array(collection.length) : [];
  _baseEach(collection, function (value) {
    result[++index] = isFunc ? _apply(path, value, args) : _baseInvoke(value, path, args);
  });
  return result;
});
/* harmony default export */ const lodash_es_invokeMap = (invokeMap);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/utils.js
function bookmark_views_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmark_views_utils_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;
  }, bookmark_views_utils_typeof(obj);
}
function bookmark_views_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bookmark_views_utils_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" == bookmark_views_utils_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 bookmark_views_utils_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 bookmark_views_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bookmark_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bookmark_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function bookmark_views_utils_toConsumableArray(arr) {
  return bookmark_views_utils_arrayWithoutHoles(arr) || bookmark_views_utils_iterableToArray(arr) || bookmark_views_utils_unsupportedIterableToArray(arr) || bookmark_views_utils_nonIterableSpread();
}
function bookmark_views_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function bookmark_views_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return bookmark_views_utils_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 bookmark_views_utils_arrayLikeToArray(o, minLen);
}
function bookmark_views_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function bookmark_views_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return bookmark_views_utils_arrayLikeToArray(arr);
}
function bookmark_views_utils_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 getHeadingButtons(view, buttons) {
  if (shared_api.settings.get('allow_bookmarks') && view.model.get('type') === shared_converse.CHATROOMS_TYPE) {
    var data = {
      'i18n_title': __('Bookmark this groupchat'),
      'i18n_text': __('Bookmark'),
      'handler': function handler(ev) {
        return view.showBookmarkModal(ev);
      },
      'a_class': 'toggle-bookmark',
      'icon_class': 'fa-bookmark',
      'name': 'bookmark'
    };
    var names = buttons.map(function (t) {
      return t.name;
    });
    var idx = names.indexOf('details');
    var data_promise = checkBookmarksSupport().then(function (s) {
      return s ? data : null;
    });
    return idx > -1 ? [].concat(bookmark_views_utils_toConsumableArray(buttons.slice(0, idx)), [data_promise], bookmark_views_utils_toConsumableArray(buttons.slice(idx))) : [data_promise].concat(bookmark_views_utils_toConsumableArray(buttons));
  }
  return buttons;
}
function removeBookmarkViaEvent(_x) {
  return _removeBookmarkViaEvent.apply(this, arguments);
}
function _removeBookmarkViaEvent() {
  _removeBookmarkViaEvent = bookmark_views_utils_asyncToGenerator( /*#__PURE__*/bookmark_views_utils_regeneratorRuntime().mark(function _callee(ev) {
    var name, jid, result;
    return bookmark_views_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          ev.preventDefault();
          name = ev.currentTarget.getAttribute('data-bookmark-name');
          jid = ev.currentTarget.getAttribute('data-room-jid');
          _context.next = 5;
          return shared_api.confirm(__('Are you sure you want to remove the bookmark "%1$s"?', name));
        case 5:
          result = _context.sent;
          if (result) {
            lodash_es_invokeMap(shared_converse.bookmarks.where({
              jid: jid
            }), Model.prototype.destroy);
          }
        case 7:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _removeBookmarkViaEvent.apply(this, arguments);
}
function addBookmarkViaEvent(ev) {
  ev.preventDefault();
  var jid = ev.currentTarget.getAttribute('data-room-jid');
  shared_api.modal.show('converse-bookmark-form-modal', {
    jid: jid
  }, ev);
}
function openRoomViaEvent(ev) {
  ev.preventDefault();
  var Strophe = public_converse.env.Strophe;
  var name = ev.target.textContent;
  var jid = ev.target.getAttribute('data-room-jid');
  var data = {
    'name': name || Strophe.unescapeNode(Strophe.getNodeFromJid(jid)) || jid
  };
  shared_api.rooms.open(jid, data, true);
}
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/components/templates/item.js
var item_templateObject;
function item_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const item = (function (bm) {
  var jid = bm.get('jid');
  var info_remove_bookmark = __('Unbookmark this groupchat');
  var open_title = __('Click to open this groupchat');
  return (0,external_lit_namespaceObject.html)(item_templateObject || (item_templateObject = item_taggedTemplateLiteral(["\n        <div class=\"list-item room-item available-chatroom d-flex flex-row\" data-room-jid=\"", "\">\n            <a class=\"list-item-link open-room w-100\" data-room-jid=\"", "\"\n                title=\"", "\"\n                @click=", ">", "</a>\n\n            <a class=\"list-item-action remove-bookmark align-self-center ", "\"\n                data-room-jid=\"", "\"\n                data-bookmark-name=\"", "\"\n                title=\"", "\"\n                @click=", ">\n            <converse-icon class=\"fa fa-bookmark\" size=\"1em\"></converse-icon>\n            </a>\n        </div>\n    "])), jid, jid, open_title, openRoomViaEvent, bm.getDisplayName(), bm.get('bookmarked') ? 'button-on' : '', jid, bm.getDisplayName(), info_remove_bookmark, removeBookmarkViaEvent);
});
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/components/templates/list.js
var list_templateObject;
function list_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var filterBookmark = function filterBookmark(b, text) {
  var _b$get, _b$get2;
  return ((_b$get = b.get('name')) === null || _b$get === void 0 ? void 0 : _b$get.includes(text)) || ((_b$get2 = b.get('jid')) === null || _b$get2 === void 0 ? void 0 : _b$get2.includes(text));
};
/* harmony default export */ const list = (function (el) {
  var i18n_placeholder = __('Filter');
  var filter_text = el.model.get('filter_text');
  var bookmarks = shared_converse.bookmarks;
  var shown_bookmarks = filter_text ? bookmarks.filter(function (b) {
    return filterBookmark(b, filter_text);
  }) : bookmarks;
  return (0,external_lit_namespaceObject.html)(list_templateObject || (list_templateObject = list_taggedTemplateLiteral(["\n        <form class=\"converse-form bookmarks-filter\">\n            <div class=\"btn-group w-100\">\n                <input\n                    .value=", "\n                    @keydown=\"", "\"\n                    class=\"form-control\"\n                    placeholder=\"", "\"/>\n\n                <converse-icon size=\"1em\" class=\"fa fa-times clear-input ", "\"\n                    @click=", ">\n                </converse-icon>\n            </div>\n        </form>\n\n        <div class=\"list-container list-container--bookmarks\">\n            <div class=\"items-list bookmarks rooms-list\">\n                ", "\n            </div>\n        </div>\n    "])), filter_text !== null && filter_text !== void 0 ? filter_text : '', function (ev) {
    return el.liveFilter(ev);
  }, i18n_placeholder, !filter_text ? 'hidden' : '', el.clearFilter, shown_bookmarks.map(function (bm) {
    return item(bm);
  }));
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/bookmark-views/styles/bookmarks.scss
var bookmarks = __webpack_require__(5399);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/styles/bookmarks.scss

      
      
      
      
      
      
      
      
      

var bookmarks_options = {};

bookmarks_options.styleTagTransform = (styleTagTransform_default());
bookmarks_options.setAttributes = (setAttributesWithoutAttributes_default());

      bookmarks_options.insert = insertBySelector_default().bind(null, "head");
    
bookmarks_options.domAPI = (styleDomAPI_default());
bookmarks_options.insertStyleElement = (insertStyleElement_default());

var bookmarks_update = injectStylesIntoStyleTag_default()(bookmarks/* default */.Z, bookmarks_options);




       /* harmony default export */ const styles_bookmarks = (bookmarks/* default */.Z && bookmarks/* default */.Z.locals ? bookmarks/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/bookmark-views/components/bookmarks-list.js
function bookmarks_list_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmarks_list_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;
  }, bookmarks_list_typeof(obj);
}
function bookmarks_list_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bookmarks_list_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" == bookmarks_list_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 bookmarks_list_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 bookmarks_list_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bookmarks_list_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bookmarks_list_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function bookmarks_list_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function bookmarks_list_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, bookmarks_list_toPropertyKey(descriptor.key), descriptor);
  }
}
function bookmarks_list_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) bookmarks_list_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) bookmarks_list_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function bookmarks_list_toPropertyKey(arg) {
  var key = bookmarks_list_toPrimitive(arg, "string");
  return bookmarks_list_typeof(key) === "symbol" ? key : String(key);
}
function bookmarks_list_toPrimitive(input, hint) {
  if (bookmarks_list_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (bookmarks_list_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function bookmarks_list_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) bookmarks_list_setPrototypeOf(subClass, superClass);
}
function bookmarks_list_setPrototypeOf(o, p) {
  bookmarks_list_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return bookmarks_list_setPrototypeOf(o, p);
}
function bookmarks_list_createSuper(Derived) {
  var hasNativeReflectConstruct = bookmarks_list_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = bookmarks_list_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = bookmarks_list_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return bookmarks_list_possibleConstructorReturn(this, result);
  };
}
function bookmarks_list_possibleConstructorReturn(self, call) {
  if (call && (bookmarks_list_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 bookmarks_list_assertThisInitialized(self);
}
function bookmarks_list_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function bookmarks_list_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 bookmarks_list_getPrototypeOf(o) {
  bookmarks_list_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return bookmarks_list_getPrototypeOf(o);
}








var BookmarksView = /*#__PURE__*/function (_CustomElement) {
  bookmarks_list_inherits(BookmarksView, _CustomElement);
  var _super = bookmarks_list_createSuper(BookmarksView);
  function BookmarksView() {
    bookmarks_list_classCallCheck(this, BookmarksView);
    return _super.apply(this, arguments);
  }
  bookmarks_list_createClass(BookmarksView, [{
    key: "initialize",
    value: function () {
      var _initialize = bookmarks_list_asyncToGenerator( /*#__PURE__*/bookmarks_list_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        var bookmarks, chatboxes, id;
        return bookmarks_list_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('bookmarksInitialized');
            case 2:
              bookmarks = shared_converse.bookmarks, chatboxes = shared_converse.chatboxes;
              this.liveFilter = lodash_es_debounce(function (ev) {
                return _this.model.set({
                  'filter_text': ev.target.value
                });
              }, 100);
              this.listenTo(bookmarks, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(bookmarks, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(chatboxes, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(chatboxes, 'remove', function () {
                return _this.requestUpdate();
              });
              id = "converse.bookmarks-list-model-".concat(shared_converse.bare_jid);
              this.model = new Model({
                id: id
              });
              initStorage(this.model, id);
              this.listenTo(this.model, 'change', function () {
                return _this.requestUpdate();
              });
              this.model.fetch({
                'success': function success() {
                  return _this.requestUpdate();
                },
                'error': function error() {
                  return _this.requestUpdate();
                }
              });
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return shared_converse.bookmarks && this.model ? list(this) : spinner();
    }
  }, {
    key: "clearFilter",
    value: function clearFilter(ev) {
      var _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      this.model.set('filter_text', '');
    }
  }]);
  return BookmarksView;
}(CustomElement);

shared_api.elements.define('converse-bookmarks', BookmarksView);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/modals/bookmark-list.js
function bookmark_list_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmark_list_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;
  }, bookmark_list_typeof(obj);
}
var bookmark_list_templateObject;
function bookmark_list_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function bookmark_list_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function bookmark_list_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, bookmark_list_toPropertyKey(descriptor.key), descriptor);
  }
}
function bookmark_list_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) bookmark_list_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) bookmark_list_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function bookmark_list_toPropertyKey(arg) {
  var key = bookmark_list_toPrimitive(arg, "string");
  return bookmark_list_typeof(key) === "symbol" ? key : String(key);
}
function bookmark_list_toPrimitive(input, hint) {
  if (bookmark_list_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (bookmark_list_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function bookmark_list_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) bookmark_list_setPrototypeOf(subClass, superClass);
}
function bookmark_list_setPrototypeOf(o, p) {
  bookmark_list_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return bookmark_list_setPrototypeOf(o, p);
}
function bookmark_list_createSuper(Derived) {
  var hasNativeReflectConstruct = bookmark_list_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = bookmark_list_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = bookmark_list_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return bookmark_list_possibleConstructorReturn(this, result);
  };
}
function bookmark_list_possibleConstructorReturn(self, call) {
  if (call && (bookmark_list_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 bookmark_list_assertThisInitialized(self);
}
function bookmark_list_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function bookmark_list_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 bookmark_list_getPrototypeOf(o) {
  bookmark_list_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return bookmark_list_getPrototypeOf(o);
}





var BookmarkListModal = /*#__PURE__*/function (_BaseModal) {
  bookmark_list_inherits(BookmarkListModal, _BaseModal);
  var _super = bookmark_list_createSuper(BookmarkListModal);
  function BookmarkListModal() {
    bookmark_list_classCallCheck(this, BookmarkListModal);
    return _super.apply(this, arguments);
  }
  bookmark_list_createClass(BookmarkListModal, [{
    key: "renderModal",
    value: function renderModal() {
      // eslint-disable-line class-methods-use-this
      return (0,external_lit_namespaceObject.html)(bookmark_list_templateObject || (bookmark_list_templateObject = bookmark_list_taggedTemplateLiteral(["<converse-bookmarks></converse-bookmarks>"])));
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Bookmarks');
    }
  }]);
  return BookmarkListModal;
}(modal_modal);

shared_api.elements.define('converse-bookmark-list-modal', BookmarkListModal);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/components/templates/form.js
var form_templateObject, form_templateObject2;
function form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const templates_form = (function (el) {
  var _el$bookmark$get, _el$bookmark, _el$bookmark2;
  var name = el.model.getDisplayName();
  var nick = (_el$bookmark$get = (_el$bookmark = el.bookmark) === null || _el$bookmark === void 0 ? void 0 : _el$bookmark.get('nick')) !== null && _el$bookmark$get !== void 0 ? _el$bookmark$get : el.model.get('nick');
  var i18n_heading = __('Bookmark for "%1$s"', name);
  var i18n_autojoin = __('Would you like this groupchat to be automatically joined upon startup?');
  var i18n_remove = __('Remove');
  var i18n_name = __('The name for this bookmark:');
  var i18n_nick = __('What should your nickname for this groupchat be?');
  var i18n_submit = el.bookmark ? __('Update') : __('Save');
  return (0,external_lit_namespaceObject.html)(form_templateObject || (form_templateObject = form_taggedTemplateLiteral(["\n        <form class=\"converse-form chatroom-form\" @submit=", ">\n            <legend>", "</legend>\n            <fieldset class=\"form-group\">\n                <label for=\"converse_muc_bookmark_name\">", "</label>\n                <input class=\"form-control\" type=\"text\" value=\"", "\" name=\"name\" required=\"required\" id=\"converse_muc_bookmark_name\"/>\n            </fieldset>\n            <fieldset class=\"form-group\">\n                <label for=\"converse_muc_bookmark_nick\">", "</label>\n                <input class=\"form-control\" type=\"text\" name=\"nick\" value=\"", "\" id=\"converse_muc_bookmark_nick\"/>\n            </fieldset>\n            <fieldset class=\"form-group form-check\">\n                <input class=\"form-check-input\" id=\"converse_muc_bookmark_autojoin\" type=\"checkbox\" ?checked=", " name=\"autojoin\"/>\n                <label class=\"form-check-label\" for=\"converse_muc_bookmark_autojoin\">", "</label>\n            </fieldset>\n            <fieldset class=\"form-group\">\n                <input class=\"btn btn-primary\" type=\"submit\" value=\"", "\">\n                    ", "\n            </fieldset>\n        </form>\n    "])), function (ev) {
    return el.onBookmarkFormSubmitted(ev);
  }, i18n_heading, i18n_name, name, i18n_nick, nick || '', (_el$bookmark2 = el.bookmark) === null || _el$bookmark2 === void 0 ? void 0 : _el$bookmark2.get('autojoin'), i18n_autojoin, i18n_submit, el.bookmark ? (0,external_lit_namespaceObject.html)(form_templateObject2 || (form_templateObject2 = form_taggedTemplateLiteral(["<input class=\"btn btn-secondary button-remove\" type=\"button\" value=\"", "\" @click=", ">"])), i18n_remove, function (ev) {
    return el.removeBookmark(ev);
  }) : '');
});
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/components/bookmark-form.js
function bookmark_form_typeof(obj) {
  "@babel/helpers - typeof";

  return bookmark_form_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;
  }, bookmark_form_typeof(obj);
}
function bookmark_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function bookmark_form_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, bookmark_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function bookmark_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) bookmark_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) bookmark_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function bookmark_form_toPropertyKey(arg) {
  var key = bookmark_form_toPrimitive(arg, "string");
  return bookmark_form_typeof(key) === "symbol" ? key : String(key);
}
function bookmark_form_toPrimitive(input, hint) {
  if (bookmark_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (bookmark_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function bookmark_form_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) bookmark_form_setPrototypeOf(subClass, superClass);
}
function bookmark_form_setPrototypeOf(o, p) {
  bookmark_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return bookmark_form_setPrototypeOf(o, p);
}
function bookmark_form_createSuper(Derived) {
  var hasNativeReflectConstruct = bookmark_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = bookmark_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = bookmark_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return bookmark_form_possibleConstructorReturn(this, result);
  };
}
function bookmark_form_possibleConstructorReturn(self, call) {
  if (call && (bookmark_form_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 bookmark_form_assertThisInitialized(self);
}
function bookmark_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function bookmark_form_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 bookmark_form_getPrototypeOf(o) {
  bookmark_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return bookmark_form_getPrototypeOf(o);
}



var MUCBookmarkForm = /*#__PURE__*/function (_CustomElement) {
  bookmark_form_inherits(MUCBookmarkForm, _CustomElement);
  var _super = bookmark_form_createSuper(MUCBookmarkForm);
  function MUCBookmarkForm() {
    bookmark_form_classCallCheck(this, MUCBookmarkForm);
    return _super.apply(this, arguments);
  }
  bookmark_form_createClass(MUCBookmarkForm, [{
    key: "willUpdate",
    value: function willUpdate(changed_properties) {
      if (changed_properties.has('jid')) {
        this.model = shared_converse.chatboxes.get(this.jid);
        this.bookmark = shared_converse.bookmarks.get(this.jid);
      }
    }
  }, {
    key: "render",
    value: function render() {
      return templates_form(this);
    }
  }, {
    key: "onBookmarkFormSubmitted",
    value: function onBookmarkFormSubmitted(ev) {
      var _ev$target$querySelec, _ev$target$querySelec2, _ev$target$querySelec3;
      ev.preventDefault();
      shared_converse.bookmarks.createBookmark({
        'jid': this.jid,
        'autojoin': ((_ev$target$querySelec = ev.target.querySelector('input[name="autojoin"]')) === null || _ev$target$querySelec === void 0 ? void 0 : _ev$target$querySelec.checked) || false,
        'name': (_ev$target$querySelec2 = ev.target.querySelector('input[name=name]')) === null || _ev$target$querySelec2 === void 0 ? void 0 : _ev$target$querySelec2.value,
        'nick': (_ev$target$querySelec3 = ev.target.querySelector('input[name=nick]')) === null || _ev$target$querySelec3 === void 0 ? void 0 : _ev$target$querySelec3.value
      });
      this.closeBookmarkForm(ev);
    }
  }, {
    key: "removeBookmark",
    value: function removeBookmark(ev) {
      var _this$bookmark;
      (_this$bookmark = this.bookmark) === null || _this$bookmark === void 0 ? void 0 : _this$bookmark.destroy();
      this.closeBookmarkForm(ev);
    }
  }, {
    key: "closeBookmarkForm",
    value: function closeBookmarkForm(ev) {
      ev.preventDefault();
      var evt = document.createEvent('Event');
      evt.initEvent('hide.bs.modal', true, true);
      this.dispatchEvent(evt);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCBookmarkForm;
}(CustomElement);
shared_api.elements.define('converse-muc-bookmark-form', MUCBookmarkForm);
/* harmony default export */ const bookmark_form = (MUCBookmarkForm);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/modals/bookmark-form.js
function modals_bookmark_form_typeof(obj) {
  "@babel/helpers - typeof";

  return modals_bookmark_form_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;
  }, modals_bookmark_form_typeof(obj);
}
var bookmark_form_templateObject;
function bookmark_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function modals_bookmark_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function modals_bookmark_form_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, modals_bookmark_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function modals_bookmark_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) modals_bookmark_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) modals_bookmark_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modals_bookmark_form_toPropertyKey(arg) {
  var key = modals_bookmark_form_toPrimitive(arg, "string");
  return modals_bookmark_form_typeof(key) === "symbol" ? key : String(key);
}
function modals_bookmark_form_toPrimitive(input, hint) {
  if (modals_bookmark_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modals_bookmark_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function modals_bookmark_form_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) modals_bookmark_form_setPrototypeOf(subClass, superClass);
}
function modals_bookmark_form_setPrototypeOf(o, p) {
  modals_bookmark_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return modals_bookmark_form_setPrototypeOf(o, p);
}
function modals_bookmark_form_createSuper(Derived) {
  var hasNativeReflectConstruct = modals_bookmark_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = modals_bookmark_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = modals_bookmark_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return modals_bookmark_form_possibleConstructorReturn(this, result);
  };
}
function modals_bookmark_form_possibleConstructorReturn(self, call) {
  if (call && (modals_bookmark_form_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 modals_bookmark_form_assertThisInitialized(self);
}
function modals_bookmark_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function modals_bookmark_form_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 modals_bookmark_form_getPrototypeOf(o) {
  modals_bookmark_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return modals_bookmark_form_getPrototypeOf(o);
}





var BookmarkFormModal = /*#__PURE__*/function (_BaseModal) {
  modals_bookmark_form_inherits(BookmarkFormModal, _BaseModal);
  var _super = modals_bookmark_form_createSuper(BookmarkFormModal);
  function BookmarkFormModal() {
    modals_bookmark_form_classCallCheck(this, BookmarkFormModal);
    return _super.apply(this, arguments);
  }
  modals_bookmark_form_createClass(BookmarkFormModal, [{
    key: "renderModal",
    value: function renderModal() {
      return (0,external_lit_namespaceObject.html)(bookmark_form_templateObject || (bookmark_form_templateObject = bookmark_form_taggedTemplateLiteral(["\n            <converse-muc-bookmark-form class=\"muc-form-container\" jid=\"", "\">\n            </converse-muc-bookmark-form>"])), this.jid);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Bookmark');
    }
  }]);
  return BookmarkFormModal;
}(modal_modal);

shared_api.elements.define('converse-bookmark-form-modal', BookmarkFormModal);
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/mixins.js

var mixins_u = public_converse.env.u;
var bookmarkableChatRoomView = {
  /**
   * Set whether the groupchat is bookmarked or not.
   * @private
   */
  setBookmarkState: function setBookmarkState() {
    if (shared_converse.bookmarks !== undefined) {
      var models = shared_converse.bookmarks.where({
        'jid': this.model.get('jid')
      });
      if (!models.length) {
        this.model.save('bookmarked', false);
      } else {
        this.model.save('bookmarked', true);
      }
    }
  },
  renderBookmarkForm: function renderBookmarkForm() {
    if (!this.bookmark_form) {
      this.bookmark_form = new shared_converse.MUCBookmarkForm({
        'model': this.model,
        'chatroomview': this
      });
      var container_el = this.querySelector('.chatroom-body');
      container_el.insertAdjacentElement('beforeend', this.bookmark_form.el);
    }
    mixins_u.showElement(this.bookmark_form.el);
  },
  showBookmarkModal: function showBookmarkModal(ev) {
    ev === null || ev === void 0 ? void 0 : ev.preventDefault();
    var jid = this.model.get('jid');
    shared_api.modal.show('converse-bookmark-form-modal', {
      jid: jid
    }, ev);
  }
};
;// CONCATENATED MODULE: ./src/plugins/bookmark-views/index.js
/**
 * @description Converse.js plugin which adds views for XEP-0048 bookmarks
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */









public_converse.plugins.add('converse-bookmark-views', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   */
  dependencies: ['converse-chatboxes', 'converse-muc', 'converse-muc-views'],
  initialize: function initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      hide_open_bookmarks: true
    });
    shared_converse.removeBookmarkViaEvent = removeBookmarkViaEvent;
    shared_converse.addBookmarkViaEvent = addBookmarkViaEvent;
    Object.assign(shared_converse.ChatRoomView.prototype, bookmarkableChatRoomView);
    shared_converse.MUCBookmarkForm = bookmark_form;
    shared_converse.BookmarksView = BookmarksView;
    shared_api.listen.on('getHeadingButtons', getHeadingButtons);
    shared_api.listen.on('chatRoomViewInitialized', function (view) {
      return view.setBookmarkState();
    });
  }
});
;// CONCATENATED MODULE: ./src/templates/background_logo.js
var background_logo_templateObject, background_logo_templateObject2;
function background_logo_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const background_logo = (function () {
  return (0,external_lit_namespaceObject.html)(background_logo_templateObject || (background_logo_templateObject = background_logo_taggedTemplateLiteral(["\n    <div class=\"inner-content converse-brand row\">\n        <div class=\"converse-brand__padding\"></div>\n        <div class=\"converse-brand__heading\">\n            <svg height=\"200px\"\n                xmlns=\"http://www.w3.org/2000/svg\"\n                xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n                viewBox=\"0 0 364 364\"\n                version=\"1.1\">\n                <title>Logo Converse</title>\n                <defs>\n                    <linearGradient id=\"gradient\" x1=\"92.14\" y1=\"27.64\" x2=\"267.65\" y2=\"331.62\" gradientUnits=\"userSpaceOnUse\">\n                        <stop offset=\"0\" stop-color=\"#fff1d1\"/>\n                        <stop offset=\"0.05\" stop-color=\"#fae8c1\"/>\n                        <stop offset=\"0.15\" stop-color=\"#f0d5a1\"/>\n                        <stop offset=\"0.27\" stop-color=\"#e7c687\"/>\n                        <stop offset=\"0.4\" stop-color=\"#e1bb72\"/>\n                        <stop offset=\"0.54\" stop-color=\"#dcb264\"/>\n                        <stop offset=\"0.71\" stop-color=\"#daad5c\"/>\n                        <stop offset=\"1\" stop-color=\"#d9ac59\"/>\n                    </linearGradient>\n                    <filter id=\"shadow\">\n                        <feGaussianBlur in=\"SourceAlpha\" stdDeviation=\"2.3\" result=\"blur1\"/>\n                        <feOffset in=\"blur1\" dx=\"3\" dy=\"3\" result=\"blur2\"/>\n                        <feColorMatrix in=\"blur2\" type=\"matrix\" result=\"blur3\"\n                            values=\"1 0 0 0 0.1\n                                    0 1 0 0 0.1\n                                    0 0 1 0 0.1\n                                    0 0 0 1 0\"/>\n                        <feMerge>\n                            <feMergeNode in=\"blur3\"/>\n                            <feMergeNode in=\"SourceGraphic\"/>\n                        </feMerge>\n                    </filter>\n                </defs>\n                <g filter=\"url(#shadow)\">\n                    <path d=\"M221.46,103.71c0,18.83-29.36,18.83-29.12,0C192.1,84.88,221.46,84.88,221.46,103.71Z\" fill=\"#d9ac59\"/>\n                    <path d=\"M179.9,4.15A175.48,175.48,0,1,0,355.38,179.63,175.48,175.48,0,0,0,179.9,4.15Zm-40.79,264.5c-.23-17.82,27.58-17.82,27.58,0S138.88,286.48,139.11,268.65ZM218.6,168.24A79.65,79.65,0,0,1,205.15,174a12.76,12.76,0,0,0-6.29,4.65L167.54,222a1.36,1.36,0,0,1-2.46-.8v-35.8a2.58,2.58,0,0,0-3.06-2.53c-15.43,3-30.23,7.7-42.73,19.94-38.8,38-29.42,105.69,16.09,133.16a162.25,162.25,0,0,1-91.47-67.27C-3.86,182.26,34.5,47.25,138.37,25.66c46.89-9.75,118.25,5.16,123.73,62.83C265.15,120.64,246.56,152.89,218.6,168.24Z\" fill=\"url(#gradient)\"/>\n                </g>\n            </svg>\n            <span class=\"converse-brand__text\">\n                <span>converse<span class=\"subdued\">.js</span></span>\n                <p class=\"byline\">messaging freedom</p>\n            </span>\n        </div>\n        ", "\n    </div>"])), shared_api.settings.get('view_mode') === 'overlayed' ? (0,external_lit_namespaceObject.html)(background_logo_templateObject2 || (background_logo_templateObject2 = background_logo_taggedTemplateLiteral(["<div class=\"converse-brand__padding\"></div>"]))) : '');
});
;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directives/repeat.js
function repeat_typeof(obj) {
  "@babel/helpers - typeof";

  return repeat_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;
  }, repeat_typeof(obj);
}
function repeat_slicedToArray(arr, i) {
  return repeat_arrayWithHoles(arr) || repeat_iterableToArrayLimit(arr, i) || repeat_unsupportedIterableToArray(arr, i) || repeat_nonIterableRest();
}
function repeat_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function repeat_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function repeat_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function repeat_createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = repeat_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(_e6) {
          throw _e6;
        },
        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(_e7) {
      didErr = true;
      err = _e7;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}
function repeat_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return repeat_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 repeat_arrayLikeToArray(o, minLen);
}
function repeat_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 repeat_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function repeat_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, repeat_toPropertyKey(descriptor.key), descriptor);
  }
}
function repeat_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) repeat_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) repeat_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function repeat_toPropertyKey(arg) {
  var key = repeat_toPrimitive(arg, "string");
  return repeat_typeof(key) === "symbol" ? key : String(key);
}
function repeat_toPrimitive(input, hint) {
  if (repeat_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (repeat_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function repeat_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) repeat_setPrototypeOf(subClass, superClass);
}
function repeat_setPrototypeOf(o, p) {
  repeat_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return repeat_setPrototypeOf(o, p);
}
function repeat_createSuper(Derived) {
  var hasNativeReflectConstruct = repeat_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = repeat_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = repeat_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return repeat_possibleConstructorReturn(this, result);
  };
}
function repeat_possibleConstructorReturn(self, call) {
  if (call && (repeat_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 repeat_assertThisInitialized(self);
}
function repeat_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function repeat_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 repeat_getPrototypeOf(o) {
  repeat_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return repeat_getPrototypeOf(o);
}



/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var repeat_u = function u(e, s, t) {
    var r = new Map();
    for (var _l = s; _l <= t; _l++) r.set(e[_l], _l);
    return r;
  },
  repeat_c = directive_e( /*#__PURE__*/function (_t) {
    repeat_inherits(_class, _t);
    var _super = repeat_createSuper(_class);
    function _class(e) {
      var _this;
      repeat_classCallCheck(this, _class);
      if (_this = _super.call(this, e), e.type !== directive_t.CHILD) throw Error("repeat() can only be used in text expressions");
      return repeat_possibleConstructorReturn(_this);
    }
    repeat_createClass(_class, [{
      key: "dt",
      value: function dt(e, s, t) {
        var r;
        void 0 === t ? t = s : void 0 !== s && (r = s);
        var l = [],
          o = [];
        var i = 0;
        var _iterator = repeat_createForOfIteratorHelper(e),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var _s = _step.value;
            l[i] = r ? r(_s, i) : i, o[i] = t(_s, i), i++;
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        return {
          values: o,
          keys: l
        };
      }
    }, {
      key: "render",
      value: function render(e, s, t) {
        return this.dt(e, s, t).values;
      }
    }, {
      key: "update",
      value: function update(s, _ref) {
        var _this$ut;
        var _ref2 = repeat_slicedToArray(_ref, 3),
          t = _ref2[0],
          r = _ref2[1],
          c = _ref2[2];
        var d = directive_helpers_p(s),
          _this$dt = this.dt(t, r, c),
          p = _this$dt.values,
          a = _this$dt.keys;
        if (!Array.isArray(d)) return this.ut = a, p;
        var h = (_this$ut = this.ut) !== null && _this$ut !== void 0 ? _this$ut : this.ut = [],
          v = [];
        var m,
          y,
          x = 0,
          j = d.length - 1,
          k = 0,
          w = p.length - 1;
        for (; x <= j && k <= w;) if (null === d[x]) x++;else if (null === d[j]) j--;else if (h[x] === a[k]) v[k] = directive_helpers_v(d[x], p[k]), x++, k++;else if (h[j] === a[w]) v[w] = directive_helpers_v(d[j], p[w]), j--, w--;else if (h[x] === a[w]) v[w] = directive_helpers_v(d[x], p[w]), directive_helpers_r(s, v[w + 1], d[x]), x++, w--;else if (h[j] === a[k]) v[k] = directive_helpers_v(d[j], p[k]), directive_helpers_r(s, d[x], d[j]), j--, k++;else if (void 0 === m && (m = repeat_u(a, k, w), y = repeat_u(h, x, j)), m.has(h[x])) {
          if (m.has(h[j])) {
            var _e2 = y.get(a[k]),
              _t2 = void 0 !== _e2 ? d[_e2] : null;
            if (null === _t2) {
              var _e3 = directive_helpers_r(s, d[x]);
              directive_helpers_v(_e3, p[k]), v[k] = _e3;
            } else v[k] = directive_helpers_v(_t2, p[k]), directive_helpers_r(s, d[x], _t2), d[_e2] = null;
            k++;
          } else directive_helpers_M(d[j]), j--;
        } else directive_helpers_M(d[x]), x++;
        for (; k <= w;) {
          var _e4 = directive_helpers_r(s, v[w + 1]);
          directive_helpers_v(_e4, p[k]), v[k++] = _e4;
        }
        for (; x <= j;) {
          var _e5 = d[x++];
          null !== _e5 && directive_helpers_M(_e5);
        }
        return this.ut = a, directive_helpers_m(s, v), T;
      }
    }]);
    return _class;
  }(directive_i));

;// CONCATENATED MODULE: ./node_modules/lit/directives/repeat.js

;// CONCATENATED MODULE: ./src/plugins/chatboxviews/templates/chats.js
var chats_templateObject, chats_templateObject2, chats_templateObject3, chats_templateObject4, chats_templateObject5, chats_templateObject6, chats_templateObject7;
function chats_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



function shouldShowChat(c) {
  var CONTROLBOX_TYPE = shared_converse.CONTROLBOX_TYPE;
  var is_minimized = shared_api.settings.get('view_mode') === 'overlayed' && c.get('minimized');
  return c.get('type') === CONTROLBOX_TYPE || !(c.get('hidden') || is_minimized);
}
/* harmony default export */ const chats = (function () {
  var chatboxes = shared_converse.chatboxes,
    CONTROLBOX_TYPE = shared_converse.CONTROLBOX_TYPE,
    CHATROOMS_TYPE = shared_converse.CHATROOMS_TYPE,
    HEADLINES_TYPE = shared_converse.HEADLINES_TYPE;
  var view_mode = shared_api.settings.get('view_mode');
  var connection = shared_converse === null || shared_converse === void 0 ? void 0 : shared_converse.connection;
  var logged_out = !(connection !== null && connection !== void 0 && connection.connected) || !(connection !== null && connection !== void 0 && connection.authenticated) || (connection === null || connection === void 0 ? void 0 : connection.disconnecting);
  return (0,external_lit_namespaceObject.html)(chats_templateObject || (chats_templateObject = chats_taggedTemplateLiteral(["\n        ", "\n        ", "\n    "])), !logged_out && view_mode === 'overlayed' ? (0,external_lit_namespaceObject.html)(chats_templateObject2 || (chats_templateObject2 = chats_taggedTemplateLiteral(["<converse-minimized-chats></converse-minimized-chats>"]))) : '', repeat_c(chatboxes.filter(shouldShowChat), function (m) {
    return m.get('jid');
  }, function (m) {
    if (m.get('type') === CONTROLBOX_TYPE) {
      return (0,external_lit_namespaceObject.html)(chats_templateObject3 || (chats_templateObject3 = chats_taggedTemplateLiteral(["\n                    ", "\n                    <converse-controlbox\n                        id=\"controlbox\"\n                        class=\"chatbox ", " ", "\"\n                        style=\"", "\"></converse-controlbox>\n                "])), view_mode === 'overlayed' ? (0,external_lit_namespaceObject.html)(chats_templateObject4 || (chats_templateObject4 = chats_taggedTemplateLiteral(["<converse-controlbox-toggle class=\"", "\"></converse-controlbox-toggle>"])), !m.get('closed') ? 'hidden' : '') : '', view_mode === 'overlayed' && m.get('closed') ? 'hidden' : '', logged_out ? 'logged-out' : '', m.get('width') ? "width: ".concat(m.get('width')) : '');
    } else if (m.get('type') === CHATROOMS_TYPE) {
      return (0,external_lit_namespaceObject.html)(chats_templateObject5 || (chats_templateObject5 = chats_taggedTemplateLiteral(["\n                    <converse-muc jid=\"", "\" class=\"chatbox chatroom\"></converse-muc>\n                "])), m.get('jid'));
    } else if (m.get('type') === HEADLINES_TYPE) {
      return (0,external_lit_namespaceObject.html)(chats_templateObject6 || (chats_templateObject6 = chats_taggedTemplateLiteral(["\n                    <converse-headlines jid=\"", "\" class=\"chatbox headlines\"></converse-headlines>\n                "])), m.get('jid'));
    } else {
      return (0,external_lit_namespaceObject.html)(chats_templateObject7 || (chats_templateObject7 = chats_taggedTemplateLiteral(["\n                    <converse-chat jid=\"", "\" class=\"chatbox\"></converse-chat>\n                "])), m.get('jid'));
    }
  }));
});
;// CONCATENATED MODULE: ./src/plugins/chatboxviews/view.js
function view_typeof(obj) {
  "@babel/helpers - typeof";

  return view_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;
  }, view_typeof(obj);
}
function view_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function view_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, view_toPropertyKey(descriptor.key), descriptor);
  }
}
function view_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) view_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) view_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function view_toPropertyKey(arg) {
  var key = view_toPrimitive(arg, "string");
  return view_typeof(key) === "symbol" ? key : String(key);
}
function view_toPrimitive(input, hint) {
  if (view_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (view_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function view_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) view_setPrototypeOf(subClass, superClass);
}
function view_setPrototypeOf(o, p) {
  view_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return view_setPrototypeOf(o, p);
}
function view_createSuper(Derived) {
  var hasNativeReflectConstruct = view_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = view_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = view_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return view_possibleConstructorReturn(this, result);
  };
}
function view_possibleConstructorReturn(self, call) {
  if (call && (view_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 view_assertThisInitialized(self);
}
function view_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function view_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 view_getPrototypeOf(o) {
  view_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return view_getPrototypeOf(o);
}






var ConverseChats = /*#__PURE__*/function (_CustomElement) {
  view_inherits(ConverseChats, _CustomElement);
  var _super = view_createSuper(ConverseChats);
  function ConverseChats() {
    view_classCallCheck(this, ConverseChats);
    return _super.apply(this, arguments);
  }
  view_createClass(ConverseChats, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.model = shared_converse.chatboxes;
      this.listenTo(this.model, 'add', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:closed', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:hidden', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:jid', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:minimized', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'destroy', function () {
        return _this.requestUpdate();
      });

      // Use listenTo instead of api.listen.to so that event handlers
      // automatically get deregistered when the component is dismounted
      this.listenTo(shared_converse, 'connected', function () {
        return _this.requestUpdate();
      });
      this.listenTo(shared_converse, 'reconnected', function () {
        return _this.requestUpdate();
      });
      this.listenTo(shared_converse, 'disconnected', function () {
        return _this.requestUpdate();
      });
      var settings = getAppSettings();
      this.listenTo(settings, 'change:view_mode', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:singleton', function () {
        return _this.requestUpdate();
      });
      var bg = document.getElementById('conversejs-bg');
      if (bg && !bg.innerHTML.trim()) {
        (0,external_lit_namespaceObject.render)(background_logo(), bg);
      }
      var body = document.querySelector('body');
      body.classList.add("converse-".concat(shared_api.settings.get('view_mode')));

      /**
       * Triggered once the _converse.ChatBoxViews view-colleciton has been initialized
       * @event _converse#chatBoxViewsInitialized
       * @example _converse.api.listen.on('chatBoxViewsInitialized', () => { ... });
       */
      shared_api.trigger('chatBoxViewsInitialized');
    }
  }, {
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      return chats();
    }
  }]);
  return ConverseChats;
}(CustomElement);
shared_api.elements.define('converse-chats', ConverseChats);
;// CONCATENATED MODULE: ./src/plugins/chatboxviews/container.js
function container_typeof(obj) {
  "@babel/helpers - typeof";

  return container_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;
  }, container_typeof(obj);
}
function container_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function container_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, container_toPropertyKey(descriptor.key), descriptor);
  }
}
function container_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) container_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) container_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function container_toPropertyKey(arg) {
  var key = container_toPrimitive(arg, "string");
  return container_typeof(key) === "symbol" ? key : String(key);
}
function container_toPrimitive(input, hint) {
  if (container_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (container_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var ChatBoxViews = /*#__PURE__*/function () {
  function ChatBoxViews() {
    container_classCallCheck(this, ChatBoxViews);
    this.views = {};
  }
  container_createClass(ChatBoxViews, [{
    key: "add",
    value: function add(key, val) {
      this.views[key] = val;
    }
  }, {
    key: "get",
    value: function get(key) {
      return this.views[key];
    }
  }, {
    key: "xget",
    value: function xget(id) {
      var _this = this;
      return this.keys().filter(function (k) {
        return k !== id;
      }).reduce(function (acc, k) {
        acc[k] = _this.views[k];
        return acc;
      }, {});
    }
  }, {
    key: "getAll",
    value: function getAll() {
      return Object.values(this.views);
    }
  }, {
    key: "keys",
    value: function keys() {
      return Object.keys(this.views);
    }
  }, {
    key: "remove",
    value: function remove(key) {
      delete this.views[key];
    }
  }, {
    key: "map",
    value: function map(f) {
      return Object.values(this.views).map(f);
    }
  }, {
    key: "forEach",
    value: function forEach(f) {
      return Object.values(this.views).forEach(f);
    }
  }, {
    key: "filter",
    value: function filter(f) {
      return Object.values(this.views).filter(f);
    }
  }, {
    key: "closeAllChatBoxes",
    value: function closeAllChatBoxes() {
      return Promise.all(Object.values(this.views).map(function (v) {
        return v.close({
          'name': 'closeAllChatBoxes'
        });
      }));
    }
  }]);
  return ChatBoxViews;
}();
/* harmony default export */ const container = (ChatBoxViews);
;// CONCATENATED MODULE: ./src/plugins/chatboxviews/utils.js
function calculateViewportHeightUnit() {
  var vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', "".concat(vh, "px"));
}
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/chatboxviews/styles/chats.scss
var styles_chats = __webpack_require__(5282);
;// CONCATENATED MODULE: ./src/plugins/chatboxviews/styles/chats.scss

      
      
      
      
      
      
      
      
      

var chats_options = {};

chats_options.styleTagTransform = (styleTagTransform_default());
chats_options.setAttributes = (setAttributesWithoutAttributes_default());

      chats_options.insert = insertBySelector_default().bind(null, "head");
    
chats_options.domAPI = (styleDomAPI_default());
chats_options.insertStyleElement = (insertStyleElement_default());

var chats_update = injectStylesIntoStyleTag_default()(styles_chats/* default */.Z, chats_options);




       /* harmony default export */ const chatboxviews_styles_chats = (styles_chats/* default */.Z && styles_chats/* default */.Z.locals ? styles_chats/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/chatboxviews/index.js
/**
 * @module converse-chatboxviews
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






public_converse.plugins.add('converse-chatboxviews', {
  dependencies: ['converse-chatboxes', 'converse-vcard'],
  initialize: function initialize() {
    shared_api.promises.add(['chatBoxViewsInitialized']);

    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'animate': true
    });
    shared_converse.chatboxviews = new container();

    /************************ BEGIN Event Handlers ************************/
    shared_api.listen.on('chatBoxesInitialized', function () {
      shared_converse.chatboxes.on('destroy', function (m) {
        return shared_converse.chatboxviews.remove(m.get('jid'));
      });
    });
    shared_api.listen.on('cleanup', function () {
      return delete shared_converse.chatboxviews;
    });
    shared_api.listen.on('clearSession', function () {
      return shared_converse.chatboxviews.closeAllChatBoxes();
    });
    shared_api.listen.on('chatBoxViewsInitialized', calculateViewportHeightUnit);
    window.addEventListener('resize', calculateViewportHeightUnit);
    /************************ END Event Handlers ************************/

    Object.assign(public_converse, {
      /**
       * Public API method which will ensure that the #conversejs element
       * is inserted into a container element.
       *
       * This method is useful when the #conversejs element has been
       * detached from the DOM somehow.
       * @async
       * @memberOf converse
       * @method insertInto
       * @example
       * converse.insertInto(document.querySelector('#converse-container'));
       */
      insertInto: function insertInto(container) {
        var _converse$chatboxview;
        var el = (_converse$chatboxview = shared_converse.chatboxviews) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.el;
        if (el && !container.contains(el)) {
          container.insertAdjacentElement('afterBegin', el);
        } else if (!el) {
          throw new Error('Cannot insert non-existing #conversejs element into the DOM');
        }
      }
    });
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/message-actions.scss
var message_actions = __webpack_require__(782);
;// CONCATENATED MODULE: ./src/shared/chat/styles/message-actions.scss

      
      
      
      
      
      
      
      
      

var message_actions_options = {};

message_actions_options.styleTagTransform = (styleTagTransform_default());
message_actions_options.setAttributes = (setAttributesWithoutAttributes_default());

      message_actions_options.insert = insertBySelector_default().bind(null, "head");
    
message_actions_options.domAPI = (styleDomAPI_default());
message_actions_options.insertStyleElement = (insertStyleElement_default());

var message_actions_update = injectStylesIntoStyleTag_default()(message_actions/* default */.Z, message_actions_options);




       /* harmony default export */ const styles_message_actions = (message_actions/* default */.Z && message_actions/* default */.Z.locals ? message_actions/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/message-actions.js
function message_actions_typeof(obj) {
  "@babel/helpers - typeof";

  return message_actions_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;
  }, message_actions_typeof(obj);
}
var message_actions_templateObject, message_actions_templateObject2, message_actions_templateObject3;
function message_actions_toConsumableArray(arr) {
  return message_actions_arrayWithoutHoles(arr) || message_actions_iterableToArray(arr) || message_actions_unsupportedIterableToArray(arr) || message_actions_nonIterableSpread();
}
function message_actions_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function message_actions_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return message_actions_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 message_actions_arrayLikeToArray(o, minLen);
}
function message_actions_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function message_actions_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return message_actions_arrayLikeToArray(arr);
}
function message_actions_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 message_actions_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  message_actions_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" == message_actions_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 message_actions_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 message_actions_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        message_actions_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        message_actions_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function message_actions_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function message_actions_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_actions_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, message_actions_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_actions_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_actions_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_actions_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_actions_toPropertyKey(arg) {
  var key = message_actions_toPrimitive(arg, "string");
  return message_actions_typeof(key) === "symbol" ? key : String(key);
}
function message_actions_toPrimitive(input, hint) {
  if (message_actions_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_actions_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_actions_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) message_actions_setPrototypeOf(subClass, superClass);
}
function message_actions_setPrototypeOf(o, p) {
  message_actions_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_actions_setPrototypeOf(o, p);
}
function message_actions_createSuper(Derived) {
  var hasNativeReflectConstruct = message_actions_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_actions_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_actions_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_actions_possibleConstructorReturn(this, result);
  };
}
function message_actions_possibleConstructorReturn(self, call) {
  if (call && (message_actions_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 message_actions_assertThisInitialized(self);
}
function message_actions_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_actions_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 message_actions_getPrototypeOf(o) {
  message_actions_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_actions_getPrototypeOf(o);
}










var message_actions_converse$env = public_converse.env,
  message_actions_Strophe = message_actions_converse$env.Strophe,
  message_actions_u = message_actions_converse$env.u;
var MessageActions = /*#__PURE__*/function (_CustomElement) {
  message_actions_inherits(MessageActions, _CustomElement);
  var _super = message_actions_createSuper(MessageActions);
  function MessageActions() {
    message_actions_classCallCheck(this, MessageActions);
    return _super.apply(this, arguments);
  }
  message_actions_createClass(MessageActions, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      var settings = getAppSettings();
      this.listenTo(settings, 'change:allowed_audio_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:allowed_image_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:allowed_video_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:render_media', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      return (0,external_lit_namespaceObject.html)(message_actions_templateObject || (message_actions_templateObject = message_actions_taggedTemplateLiteral(["", ""])), until_m(this.renderActions(), ''));
    }
  }, {
    key: "renderActions",
    value: function () {
      var _renderActions = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee() {
        var should_drop_up, buttons, items;
        return message_actions_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              // We want to let the message actions menu drop upwards if we're at the
              // bottom of the message history, and down otherwise. This is to avoid
              // the menu disappearing behind the bottom panel (toolbar, textarea etc).
              // That's difficult to know from state, so we're making an approximation here.
              should_drop_up = this.model.collection.length > 2 && this.model === this.model.collection.last();
              _context.next = 3;
              return this.getActionButtons();
            case 3:
              buttons = _context.sent;
              items = buttons.map(function (b) {
                return MessageActions.getActionsDropdownItem(b);
              });
              if (!items.length) {
                _context.next = 9;
                break;
              }
              return _context.abrupt("return", (0,external_lit_namespaceObject.html)(message_actions_templateObject2 || (message_actions_templateObject2 = message_actions_taggedTemplateLiteral(["<converse-dropdown\n                class=\"chat-msg__actions ", "\"\n                .items=", "\n            ></converse-dropdown>"])), should_drop_up ? 'dropup dropup--left' : 'dropleft', items));
            case 9:
              return _context.abrupt("return", '');
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function renderActions() {
        return _renderActions.apply(this, arguments);
      }
      return renderActions;
    }()
  }, {
    key: "onMessageEditButtonClicked",
    value: function () {
      var _onMessageEditButtonClicked = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee2(ev) {
        var _u$ancestor, _u$ancestor$querySele;
        var currently_correcting, unsent_text, result;
        return message_actions_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev.preventDefault();
              currently_correcting = this.model.collection.findWhere('correcting'); // TODO: Use state intead of DOM querying
              // Then this code can also be put on the model
              unsent_text = (_u$ancestor = message_actions_u.ancestor(this, '.chatbox')) === null || _u$ancestor === void 0 ? void 0 : (_u$ancestor$querySele = _u$ancestor.querySelector('.chat-textarea')) === null || _u$ancestor$querySele === void 0 ? void 0 : _u$ancestor$querySele.value;
              if (!(unsent_text && (!currently_correcting || currently_correcting.getMessageText() !== unsent_text))) {
                _context2.next = 9;
                break;
              }
              _context2.next = 6;
              return shared_api.confirm(__('You have an unsent message which will be lost if you continue. Are you sure?'));
            case 6:
              result = _context2.sent;
              if (result) {
                _context2.next = 9;
                break;
              }
              return _context2.abrupt("return");
            case 9:
              if (currently_correcting !== this.model) {
                currently_correcting === null || currently_correcting === void 0 ? void 0 : currently_correcting.save('correcting', false);
                this.model.save('correcting', true);
              } else {
                this.model.save('correcting', false);
              }
            case 10:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function onMessageEditButtonClicked(_x) {
        return _onMessageEditButtonClicked.apply(this, arguments);
      }
      return onMessageEditButtonClicked;
    }()
  }, {
    key: "onDirectMessageRetractButtonClicked",
    value: function () {
      var _onDirectMessageRetractButtonClicked = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee3() {
        var retraction_warning, messages, result, chatbox;
        return message_actions_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (!(this.model.get('sender') !== 'me')) {
                _context3.next = 2;
                break;
              }
              return _context3.abrupt("return", log.error("onMessageRetractButtonClicked called for someone else's message!"));
            case 2:
              retraction_warning = __('Be aware that other XMPP/Jabber clients (and servers) may ' + 'not yet support retractions and that this message may not ' + 'be removed everywhere.');
              messages = [__('Are you sure you want to retract this message?')];
              if (shared_api.settings.get('show_retraction_warning')) {
                messages[1] = retraction_warning;
              }
              _context3.next = 7;
              return shared_api.confirm(__('Confirm'), messages);
            case 7:
              result = _context3.sent;
              if (result) {
                chatbox = this.model.collection.chatbox;
                chatbox.retractOwnMessage(this.model);
              }
            case 9:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function onDirectMessageRetractButtonClicked() {
        return _onDirectMessageRetractButtonClicked.apply(this, arguments);
      }
      return onDirectMessageRetractButtonClicked;
    }()
    /**
     * Retract someone else's message in this groupchat.
     * @private
     * @param { _converse.Message } message - The message which we're retracting.
     * @param { string } [reason] - The reason for retracting the message.
     */
  }, {
    key: "retractOtherMessage",
    value: function () {
      var _retractOtherMessage = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee4(reason) {
        var chatbox, result, err_msg, _err_msg;
        return message_actions_regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              chatbox = this.model.collection.chatbox;
              _context4.next = 3;
              return chatbox.retractOtherMessage(this.model, reason);
            case 3:
              result = _context4.sent;
              if (result === null) {
                err_msg = __("A timeout occurred while trying to retract the message");
                shared_api.alert('error', __('Error'), err_msg);
                log(err_msg, message_actions_Strophe.LogLevel.WARN);
              } else if (message_actions_u.isErrorStanza(result)) {
                _err_msg = __("Sorry, you're not allowed to retract this message.");
                shared_api.alert('error', __('Error'), _err_msg);
                log(_err_msg, message_actions_Strophe.LogLevel.WARN);
                log(result, message_actions_Strophe.LogLevel.WARN);
              }
            case 5:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function retractOtherMessage(_x2) {
        return _retractOtherMessage.apply(this, arguments);
      }
      return retractOtherMessage;
    }()
  }, {
    key: "onMUCMessageRetractButtonClicked",
    value: function () {
      var _onMUCMessageRetractButtonClicked = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee5() {
        var retraction_warning, messages, chatbox, _messages, _messages2, reason, err_msg;
        return message_actions_regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              retraction_warning = __('Be aware that other XMPP/Jabber clients (and servers) may ' + 'not yet support retractions and that this message may not ' + 'be removed everywhere.');
              if (!this.model.mayBeRetracted()) {
                _context5.next = 11;
                break;
              }
              messages = [__('Are you sure you want to retract this message?')];
              if (shared_api.settings.get('show_retraction_warning')) {
                messages[1] = retraction_warning;
              }
              _context5.next = 6;
              return shared_api.confirm(__('Confirm'), messages);
            case 6:
              if (!_context5.sent) {
                _context5.next = 9;
                break;
              }
              chatbox = this.model.collection.chatbox;
              chatbox.retractOwnMessage(this.model);
            case 9:
              _context5.next = 34;
              break;
            case 11:
              _context5.next = 13;
              return this.model.mayBeModerated();
            case 13:
              if (!_context5.sent) {
                _context5.next = 32;
                break;
              }
              if (!(this.model.get('sender') === 'me')) {
                _context5.next = 24;
                break;
              }
              _messages = [__('Are you sure you want to retract this message?')];
              if (shared_api.settings.get('show_retraction_warning')) {
                _messages = [_messages[0], retraction_warning, _messages[1]];
              }
              _context5.next = 19;
              return shared_api.confirm(__('Confirm'), _messages);
            case 19:
              _context5.t0 = !!_context5.sent;
              if (!_context5.t0) {
                _context5.next = 22;
                break;
              }
              this.retractOtherMessage();
            case 22:
              _context5.next = 30;
              break;
            case 24:
              _messages2 = [__('You are about to retract this message.'), __('You may optionally include a message, explaining the reason for the retraction.')];
              if (shared_api.settings.get('show_retraction_warning')) {
                _messages2 = [_messages2[0], retraction_warning, _messages2[1]];
              }
              _context5.next = 28;
              return shared_api.prompt(__('Message Retraction'), _messages2, __('Optional reason'));
            case 28:
              reason = _context5.sent;
              reason !== false && this.retractOtherMessage(reason);
            case 30:
              _context5.next = 34;
              break;
            case 32:
              err_msg = __("Sorry, you're not allowed to retract this message");
              shared_api.alert('error', __('Error'), err_msg);
            case 34:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function onMUCMessageRetractButtonClicked() {
        return _onMUCMessageRetractButtonClicked.apply(this, arguments);
      }
      return onMUCMessageRetractButtonClicked;
    }()
  }, {
    key: "onMessageRetractButtonClicked",
    value: function onMessageRetractButtonClicked(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      var chatbox = this.model.collection.chatbox;
      if (chatbox.get('type') === shared_converse.CHATROOMS_TYPE) {
        this.onMUCMessageRetractButtonClicked();
      } else {
        this.onDirectMessageRetractButtonClicked();
      }
    }
  }, {
    key: "onMediaToggleClicked",
    value: function onMediaToggleClicked(ev) {
      var _ev$preventDefault2;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      if (this.hasHiddenMedia(this.getMediaURLs())) {
        this.model.save({
          'hide_url_previews': false,
          'url_preview_transition': 'fade-in'
        });
      } else {
        var ogp_metadata = this.model.get('ogp_metadata') || [];
        if (ogp_metadata.length) {
          this.model.set('url_preview_transition', 'fade-out');
        } else {
          this.model.save({
            'hide_url_previews': true,
            'url_preview_transition': 'fade-in'
          });
        }
      }
    }

    /**
     * Check whether media is hidden or shown, which is used to determine the toggle text.
     *
     * If `render_media` is an array, check if there are media URLs outside
     * of that array, in which case we consider message media on the whole to be hidden (since
     * those excluded by the whitelist will be, even if the render_media whitelisted URLs are shown).
     * @param { Array<String> } media_urls
     * @returns { Boolean }
     */
  }, {
    key: "hasHiddenMedia",
    value: function hasHiddenMedia(media_urls) {
      if (typeof this.model.get('hide_url_previews') === 'boolean') {
        return this.model.get('hide_url_previews');
      }
      var render_media = shared_api.settings.get('render_media');
      if (Array.isArray(render_media)) {
        return media_urls.reduce(function (acc, url) {
          return acc || !isDomainWhitelisted(render_media, url);
        }, false);
      } else {
        return !render_media;
      }
    }
  }, {
    key: "getMediaURLs",
    value: function getMediaURLs() {
      var unfurls_to_show = (this.model.get('ogp_metadata') || []).map(function (o) {
        return {
          'url': o['og:image'],
          'is_image': true
        };
      }).filter(function (o) {
        return isMediaURLDomainAllowed(o);
      });
      var media_urls = utils_getMediaURLs(this.model.get('media_urls') || [], this.model.get('body')).filter(function (o) {
        return isMediaURLDomainAllowed(o);
      });
      return message_actions_toConsumableArray(new Set([].concat(message_actions_toConsumableArray(media_urls.map(function (o) {
        return o.url;
      })), message_actions_toConsumableArray(unfurls_to_show.map(function (o) {
        return o.url;
      })))));
    }

    /**
     * Adds a media rendering toggle to this message's action buttons if necessary.
     *
     * The toggle is only added if the message contains media URLs and if the
     * user is allowed to show or hide media for those URLs.
     *
     * Whether a user is allowed to show or hide domains depends on the config settings:
     * * allowed_audio_domains
     * * allowed_video_domains
     * * allowed_image_domains
     *
     * Whether media is currently shown or hidden is determined by the { @link hasHiddenMedia } method.
     *
     * @param { Array<MessageActionAttributes> } buttons - An array of objects representing action buttons
     */
  }, {
    key: "addMediaRenderingToggle",
    value: function addMediaRenderingToggle(buttons) {
      var _this2 = this;
      var urls = this.getMediaURLs();
      if (urls.length) {
        var hidden = this.hasHiddenMedia(urls);
        buttons.push({
          'i18n_text': hidden ? __('Show media') : __('Hide media'),
          'handler': function handler(ev) {
            return _this2.onMediaToggleClicked(ev);
          },
          'button_class': 'chat-msg__action-hide-previews',
          'icon_class': hidden ? 'fas fa-eye' : 'fas fa-eye-slash',
          'name': 'hide'
        });
      }
    }
  }, {
    key: "getActionButtons",
    value: function () {
      var _getActionButtons = message_actions_asyncToGenerator( /*#__PURE__*/message_actions_regeneratorRuntime().mark(function _callee6() {
        var _this3 = this;
        var buttons, may_be_moderated, retractable;
        return message_actions_regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              buttons = [];
              if (this.model.get('editable')) {
                /**
                 * @typedef { Object } MessageActionAttributes
                 * An object which represents a message action (as shown in the message dropdown);
                 * @property { String } i18n_text
                 * @property { Function } handler
                 * @property { String } button_class
                 * @property { String } icon_class
                 * @property { String } name
                 */
                buttons.push({
                  'i18n_text': this.model.get('correcting') ? __('Cancel Editing') : __('Edit'),
                  'handler': function handler(ev) {
                    return _this3.onMessageEditButtonClicked(ev);
                  },
                  'button_class': 'chat-msg__action-edit',
                  'icon_class': 'fa fa-pencil-alt',
                  'name': 'edit'
                });
              }
              _context6.t0 = ['groupchat', 'mep'].includes(this.model.get('type'));
              if (!_context6.t0) {
                _context6.next = 7;
                break;
              }
              _context6.next = 6;
              return this.model.mayBeModerated();
            case 6:
              _context6.t0 = _context6.sent;
            case 7:
              may_be_moderated = _context6.t0;
              retractable = !this.is_retracted && (this.model.mayBeRetracted() || may_be_moderated);
              if (retractable) {
                buttons.push({
                  'i18n_text': __('Retract'),
                  'handler': function handler(ev) {
                    return _this3.onMessageRetractButtonClicked(ev);
                  },
                  'button_class': 'chat-msg__action-retract',
                  'icon_class': 'fas fa-trash-alt',
                  'name': 'retract'
                });
              }
              if (this.model.collection) {
                _context6.next = 12;
                break;
              }
              return _context6.abrupt("return", []);
            case 12:
              this.addMediaRenderingToggle(buttons);

              /**
               * *Hook* which allows plugins to add more message action buttons
               * @event _converse#getMessageActionButtons
               * @example
               *  api.listen.on('getMessageActionButtons', (el, buttons) => {
               *      buttons.push({
               *          'i18n_text': 'Foo',
               *          'handler': ev => alert('Foo!'),
               *          'button_class': 'chat-msg__action-foo',
               *          'icon_class': 'fa fa-check',
               *          'name': 'foo'
               *      });
               *      return buttons;
               *  });
               */
              return _context6.abrupt("return", shared_api.hook('getMessageActionButtons', this, buttons));
            case 14:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
      function getActionButtons() {
        return _getActionButtons.apply(this, arguments);
      }
      return getActionButtons;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        is_retracted: {
          type: Boolean
        },
        model: {
          type: Object
        }
      };
    }
  }, {
    key: "getActionsDropdownItem",
    value: function getActionsDropdownItem(o) {
      return (0,external_lit_namespaceObject.html)(message_actions_templateObject3 || (message_actions_templateObject3 = message_actions_taggedTemplateLiteral(["\n            <button class=\"chat-msg__action ", "\" @click=", ">\n                <converse-icon\n                    class=\"", "\"\n                    color=\"var(--text-color-lighten-15-percent)\"\n                    size=\"1em\"\n                ></converse-icon>\n                ", "\n            </button>\n        "])), o.button_class, o.handler, o.icon_class, o.i18n_text);
    }
  }]);
  return MessageActions;
}(CustomElement);
shared_api.elements.define('converse-message-actions', MessageActions);
;// CONCATENATED MODULE: ./src/shared/modals/templates/image.js
var image_templateObject;
function image_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const templates_image = (function (o) {
  return (0,external_lit_namespaceObject.html)(image_templateObject || (image_templateObject = image_taggedTemplateLiteral(["<img class=\"chat-image chat-image--modal\" src=\"", "\">"])), o.src);
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/modals/styles/image.scss
var styles_image = __webpack_require__(2910);
;// CONCATENATED MODULE: ./src/shared/modals/styles/image.scss

      
      
      
      
      
      
      
      
      

var image_options = {};

image_options.styleTagTransform = (styleTagTransform_default());
image_options.setAttributes = (setAttributesWithoutAttributes_default());

      image_options.insert = insertBySelector_default().bind(null, "head");
    
image_options.domAPI = (styleDomAPI_default());
image_options.insertStyleElement = (insertStyleElement_default());

var image_update = injectStylesIntoStyleTag_default()(styles_image/* default */.Z, image_options);




       /* harmony default export */ const modals_styles_image = (styles_image/* default */.Z && styles_image/* default */.Z.locals ? styles_image/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/modals/image.js
function image_typeof(obj) {
  "@babel/helpers - typeof";

  return image_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;
  }, image_typeof(obj);
}
var modals_image_templateObject;
function modals_image_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function image_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function image_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, image_toPropertyKey(descriptor.key), descriptor);
  }
}
function image_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) image_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) image_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function image_toPropertyKey(arg) {
  var key = image_toPrimitive(arg, "string");
  return image_typeof(key) === "symbol" ? key : String(key);
}
function image_toPrimitive(input, hint) {
  if (image_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (image_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function image_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) image_setPrototypeOf(subClass, superClass);
}
function image_setPrototypeOf(o, p) {
  image_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return image_setPrototypeOf(o, p);
}
function image_createSuper(Derived) {
  var hasNativeReflectConstruct = image_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = image_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = image_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return image_possibleConstructorReturn(this, result);
  };
}
function image_possibleConstructorReturn(self, call) {
  if (call && (image_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 image_assertThisInitialized(self);
}
function image_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function image_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 image_getPrototypeOf(o) {
  image_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return image_getPrototypeOf(o);
}







var ImageModal = /*#__PURE__*/function (_BaseModal) {
  image_inherits(ImageModal, _BaseModal);
  var _super = image_createSuper(ImageModal);
  function ImageModal() {
    image_classCallCheck(this, ImageModal);
    return _super.apply(this, arguments);
  }
  image_createClass(ImageModal, [{
    key: "renderModal",
    value: function renderModal() {
      return templates_image({
        'src': this.src
      });
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      return (0,external_lit_namespaceObject.html)(modals_image_templateObject || (modals_image_templateObject = modals_image_taggedTemplateLiteral(["", "<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), __('Image: '), this.src, getFileName(this.src));
    }
  }]);
  return ImageModal;
}(modal_modal);

shared_api.elements.define('converse-image-modal', ImageModal);
;// CONCATENATED MODULE: ./node_modules/lit/directive.js

// EXTERNAL MODULE: ./node_modules/gifuct-js/lib/index.js
var lib = __webpack_require__(3960);
;// CONCATENATED MODULE: ./src/shared/gif/index.js
function gif_typeof(obj) {
  "@babel/helpers - typeof";

  return gif_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;
  }, gif_typeof(obj);
}
function gif_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  gif_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" == gif_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 gif_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 gif_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        gif_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        gif_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function gif_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function gif_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, gif_toPropertyKey(descriptor.key), descriptor);
  }
}
function gif_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) gif_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) gif_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function gif_toPropertyKey(arg) {
  var key = gif_toPrimitive(arg, "string");
  return gif_typeof(key) === "symbol" ? key : String(key);
}
function gif_toPrimitive(input, hint) {
  if (gif_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (gif_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}



var ConverseGif = /*#__PURE__*/function () {
  /**
   * Creates a new ConverseGif instance
   * @param { import('lit').LitElement } el
   * @param { Object } [options]
   * @param { Number } [options.width] - The width, in pixels, of the canvas
   * @param { Number } [options.height] - The height, in pixels, of the canvas
   * @param { Boolean } [options.loop=true] - Setting this to `true` will enable looping of the gif
   * @param { Boolean } [options.autoplay=true] - Same as the rel:autoplay attribute above, this arg overrides the img tag info.
   * @param { Number } [options.max_width] - Scale images over max_width down to max_width. Helpful with mobile.
   * @param { Function } [options.onIterationEnd] - Add a callback for when the gif reaches the end of a single loop (one iteration). The first argument passed will be the gif HTMLElement.
   * @param { Boolean } [options.show_progress_bar=true]
   * @param { String } [options.progress_bg_color='rgba(0,0,0,0.4)']
   * @param { String } [options.progress_color='rgba(255,0,22,.8)']
   * @param { Number } [options.progress_bar_height=5]
   */
  function ConverseGif(el, opts) {
    gif_classCallCheck(this, ConverseGif);
    this.options = Object.assign({
      width: null,
      height: null,
      autoplay: true,
      loop: true,
      show_progress_bar: true,
      progress_bg_color: 'rgba(0,0,0,0.4)',
      progress_color: 'rgba(255,0,22,.8)',
      progress_bar_height: 5
    }, opts);
    this.el = el;
    this.gif_el = el.querySelector('img');
    this.canvas = el.querySelector('canvas');
    this.ctx = this.canvas.getContext('2d');

    // Offscreen canvas with full gif
    this.offscreenCanvas = document.createElement('canvas');
    // Offscreen canvas for patches
    this.patchCanvas = document.createElement('canvas');
    this.ctx_scaled = false;
    this.frames = [];
    this.load_error = null;
    this.playing = this.options.autoplay;
    this.frame_idx = 0;
    this.iteration_count = 0;
    this.start = null;
    this.hovering = null;
    this.frameImageData = null;
    this.disposal_restore_from_idx = null;
    this.initialize();
  }
  gif_createClass(ConverseGif, [{
    key: "initialize",
    value: function () {
      var _initialize = gif_asyncToGenerator( /*#__PURE__*/gif_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        var data;
        return gif_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (this.options.width && this.options.height) {
                this.setSizes(this.options.width, this.options.height);
              }
              _context.next = 3;
              return this.fetchGIF(this.gif_el.src);
            case 3:
              data = _context.sent;
              requestAnimationFrame(function () {
                return _this.handleGIFResponse(data);
              });
            case 5:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "initPlayer",
    value: function initPlayer() {
      var _this2 = this;
      if (this.load_error) return;
      if (!(this.options.width && this.options.height)) {
        this.ctx.scale(this.getCanvasScale(), this.getCanvasScale());
      }

      // Show the first frame
      this.frame_idx = 0;
      this.renderImage();
      if (this.options.autoplay) {
        var _this$frames$this$fra, _this$frames$this$fra2;
        var delay = (_this$frames$this$fra = (_this$frames$this$fra2 = this.frames[this.frame_idx]) === null || _this$frames$this$fra2 === void 0 ? void 0 : _this$frames$this$fra2.delay) !== null && _this$frames$this$fra !== void 0 ? _this$frames$this$fra : 0;
        setTimeout(function () {
          return _this2.play();
        }, delay);
      }
    }

    /**
     * Gets the index of the frame "up next"
     * @returns {number}
     */
  }, {
    key: "getNextFrameNo",
    value: function getNextFrameNo() {
      if (this.frames.length === 0) {
        return 0;
      }
      return (this.frame_idx + 1 + this.frames.length) % this.frames.length;
    }

    /**
     * Called once we've looped through all frames in the GIF
     * @returns { Boolean } - Returns `true` if the GIF is now paused (i.e. further iterations are not desired)
     */
  }, {
    key: "onIterationEnd",
    value: function onIterationEnd() {
      var _this$options$onItera, _this$options;
      this.iteration_count++;
      (_this$options$onItera = (_this$options = this.options).onIterationEnd) === null || _this$options$onItera === void 0 ? void 0 : _this$options$onItera.call(_this$options, this);
      if (!this.options.loop) {
        this.pause();
        return true;
      }
      return false;
    }

    /**
     * Inner callback for the `requestAnimationFrame` function.
     *
     * This method gets wrapped by an arrow function so that the `previous_timestamp` and
     * `frame_delay` parameters can also be passed in. The `timestamp`
     * parameter comes from `requestAnimationFrame`.
     *
     * The purpose of this method is to call `renderImage` with the right delay
     * in order to render the GIF animation.
     *
     * Note, this method will cause the *next* upcoming frame to be rendered,
     * not the current one.
     *
     * This means `this.frame_idx` will be incremented before calling `this.renderImage`, so
     * `renderImage(0)` needs to be called *before* this method, otherwise the
     * animation will incorrectly start from frame #1 (this is done in `initPlayer`).
     *
     * @param { DOMHighResTimeStamp } timestamp - The timestamp as returned by `requestAnimationFrame`
     * @param { DOMHighResTimeStamp } previous_timestamp - The timestamp from the previous iteration of this method.
     * We need this in order to calculate whether we have waited long enough to
     * show the next frame.
     * @param { Number } frame_delay - The delay (in 1/100th of a second)
     * before the currently being shown frame should be replaced by a new one.
     */
  }, {
    key: "onAnimationFrame",
    value: function onAnimationFrame(timestamp, previous_timestamp, frame_delay) {
      var _this3 = this,
        _this$frames$this$fra3;
      if (!this.playing) {
        return;
      }
      if (timestamp - previous_timestamp < frame_delay) {
        this.hovering ? this.drawPauseIcon() : this.renderImage();
        // We need to wait longer
        requestAnimationFrame(function (ts) {
          return _this3.onAnimationFrame(ts, previous_timestamp, frame_delay);
        });
        return;
      }
      var next_frame = this.getNextFrameNo();
      if (next_frame === 0 && this.onIterationEnd()) {
        return;
      }
      this.frame_idx = next_frame;
      this.renderImage();
      var delay = ((_this$frames$this$fra3 = this.frames[this.frame_idx]) === null || _this$frames$this$fra3 === void 0 ? void 0 : _this$frames$this$fra3.delay) || 8;
      requestAnimationFrame(function (ts) {
        return _this3.onAnimationFrame(ts, timestamp, delay);
      });
    }
  }, {
    key: "setSizes",
    value: function setSizes(w, h) {
      this.canvas.width = w * this.getCanvasScale();
      this.canvas.height = h * this.getCanvasScale();
      this.offscreenCanvas.width = w;
      this.offscreenCanvas.height = h;
      this.offscreenCanvas.style.width = w + 'px';
      this.offscreenCanvas.style.height = h + 'px';
      this.offscreenCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
    }
  }, {
    key: "doShowProgress",
    value: function doShowProgress(pos, length, draw) {
      if (draw && this.options.show_progress_bar) {
        var height = this.options.progress_bar_height;
        var top = (this.canvas.height - height) / (this.ctx_scaled ? this.getCanvasScale() : 1);
        var mid = pos / length * this.canvas.width / (this.ctx_scaled ? this.getCanvasScale() : 1);
        var width = this.canvas.width / (this.ctx_scaled ? this.getCanvasScale() : 1);
        height /= this.ctx_scaled ? this.getCanvasScale() : 1;
        this.ctx.fillStyle = this.options.progress_bg_color;
        this.ctx.fillRect(mid, top, width - mid, height);
        this.ctx.fillStyle = this.options.progress_color;
        this.ctx.fillRect(0, top, mid, height);
      }
    }

    /**
     * Starts parsing the GIF stream data by calling `parseGIF` and passing in
     * a map of handler functions.
     * @param {ArrayBuffer} data - The GIF file data, as returned by the server
     */
  }, {
    key: "handleGIFResponse",
    value: function handleGIFResponse(data) {
      try {
        var _this$options$width, _this$options$height;
        var gif = (0,lib/* parseGIF */.vq)(data);
        this.hdr = gif.header;
        this.lsd = gif.lsd;
        this.setSizes((_this$options$width = this.options.width) !== null && _this$options$width !== void 0 ? _this$options$width : this.lsd.width, (_this$options$height = this.options.height) !== null && _this$options$height !== void 0 ? _this$options$height : this.lsd.height);
        this.frames = (0,lib/* decompressFrames */.zw)(gif, true);
      } catch (err) {
        this.showError();
      }
      this.initPlayer();
      !this.options.autoplay && this.drawPlayIcon();
    }
  }, {
    key: "drawError",
    value: function drawError() {
      this.ctx.fillStyle = 'black';
      this.ctx.fillRect(0, 0, this.options.width, this.options.height);
      this.ctx.strokeStyle = 'red';
      this.ctx.lineWidth = 3;
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(this.options.width, this.options.height);
      this.ctx.moveTo(0, this.options.height);
      this.ctx.lineTo(this.options.width, 0);
      this.ctx.stroke();
    }
  }, {
    key: "showError",
    value: function showError() {
      this.load_error = true;
      this.hdr = {
        width: this.gif_el.width,
        height: this.gif_el.height
      }; // Fake header.
      this.frames = [];
      this.drawError();
      this.el.requestUpdate();
    }
  }, {
    key: "manageDisposal",
    value: function manageDisposal(i) {
      if (i <= 0) return;
      var offscreenContext = this.offscreenCanvas.getContext('2d');
      var disposal = this.frames[i - 1].disposalType;
      /*
       *  Disposal method indicates the way in which the graphic is to
       *  be treated after being displayed.
       *
       *  Values :    0 - No disposal specified. The decoder is
       *                  not required to take any action.
       *              1 - Do not dispose. The graphic is to be left
       *                  in place.
       *              2 - Restore to background color. The area used by the
       *                  graphic must be restored to the background color.
       *              3 - Restore to previous. The decoder is required to
       *                  restore the area overwritten by the graphic with
       *                  what was there prior to rendering the graphic.
       *
       *                  Importantly, "previous" means the frame state
       *                  after the last disposal of method 0, 1, or 2.
       */
      if (i > 1) {
        if (disposal === 3) {
          // eslint-disable-next-line no-eq-null
          if (this.disposal_restore_from_idx != null) {
            offscreenContext.putImageData(this.frames[this.disposal_restore_from_idx].data, 0, 0);
          }
        } else {
          this.disposal_restore_from_idx = i - 1;
        }
      }
      if (disposal === 2) {
        // Restore to background color
        // Browser implementations historically restore to transparent; we do the same.
        // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079
        offscreenContext.clearRect(this.last_frame.dims.left, this.last_frame.dims.top, this.last_frame.dims.width, this.last_frame.dims.height);
      }
    }

    /**
     * Draws a gif frame at a specific index inside the canvas.
     * @param {boolean} show_pause_on_hover - The frame index
     */
  }, {
    key: "renderImage",
    value: function renderImage() {
      var show_pause_on_hover = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      if (!this.frames.length) return;
      var i = this.frame_idx;
      i = parseInt(i.toString(), 10);
      if (i > this.frames.length - 1 || i < 0) {
        i = 0;
      }
      this.manageDisposal(i);
      var frame = this.frames[i];
      var patchContext = this.patchCanvas.getContext('2d');
      var offscreenContext = this.offscreenCanvas.getContext('2d');
      var dims = frame.dims;
      if (!this.frameImageData || dims.width != this.frameImageData.width || dims.height != this.frameImageData.height) {
        this.patchCanvas.width = dims.width;
        this.patchCanvas.height = dims.height;
        this.frameImageData = patchContext.createImageData(dims.width, dims.height);
      }

      // set the patch data as an override
      this.frameImageData.data.set(frame.patch);
      // draw the patch back over the canvas
      patchContext.putImageData(this.frameImageData, 0, 0);
      offscreenContext.drawImage(this.patchCanvas, dims.left, dims.top);
      var imageData = offscreenContext.getImageData(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);
      this.ctx.putImageData(imageData, 0, 0);
      this.ctx.drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height);
      if (show_pause_on_hover && this.hovering) {
        this.drawPauseIcon();
      }
      this.last_frame = frame;
    }

    /**
     * Start playing the gif
     */
  }, {
    key: "play",
    value: function play() {
      var _this4 = this;
      this.playing = true;
      requestAnimationFrame(function (ts) {
        return _this4.onAnimationFrame(ts, 0, 0);
      });
    }

    /**
     * Pause the gif
     */
  }, {
    key: "pause",
    value: function pause() {
      var _this5 = this;
      this.playing = false;
      requestAnimationFrame(function () {
        return _this5.drawPlayIcon();
      });
    }
  }, {
    key: "drawPauseIcon",
    value: function drawPauseIcon() {
      if (!this.playing) return;

      // Clear the potential play button by re-rendering the current frame
      this.renderImage(false);

      // Draw dark overlay
      this.ctx.fillStyle = 'rgb(0, 0, 0, 0.25)';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      var icon_size = this.canvas.height * 0.1;
      // Draw bars
      this.ctx.lineWidth = this.canvas.height * 0.04;
      this.ctx.beginPath();
      this.ctx.moveTo(this.canvas.width / 2 - icon_size / 2, this.canvas.height / 2 - icon_size);
      this.ctx.lineTo(this.canvas.width / 2 - icon_size / 2, this.canvas.height / 2 + icon_size);
      this.ctx.fillStyle = 'rgb(200, 200, 200, 0.75)';
      this.ctx.stroke();
      this.ctx.beginPath();
      this.ctx.moveTo(this.canvas.width / 2 + icon_size / 2, this.canvas.height / 2 - icon_size);
      this.ctx.lineTo(this.canvas.width / 2 + icon_size / 2, this.canvas.height / 2 + icon_size);
      this.ctx.fillStyle = 'rgb(200, 200, 200, 0.75)';
      this.ctx.stroke();

      // Draw circle
      this.ctx.lineWidth = this.canvas.height * 0.02;
      this.ctx.strokeStyle = 'rgb(200, 200, 200, 0.75)';
      this.ctx.beginPath();
      this.ctx.arc(this.canvas.width / 2, this.canvas.height / 2, icon_size * 1.5, 0, 2 * Math.PI);
      this.ctx.stroke();
    }
  }, {
    key: "drawPlayIcon",
    value: function drawPlayIcon() {
      if (this.playing) return;

      // Clear the potential pause button by re-rendering the current frame
      this.renderImage(false);
      // Draw dark overlay
      this.ctx.fillStyle = 'rgb(0, 0, 0, 0.25)';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

      // Draw triangle
      var triangle_size = this.canvas.height * 0.1;
      var region = new Path2D();
      region.moveTo(this.canvas.width / 2 + triangle_size, this.canvas.height / 2); // start at the pointy end
      region.lineTo(this.canvas.width / 2 - triangle_size / 2, this.canvas.height / 2 + triangle_size);
      region.lineTo(this.canvas.width / 2 - triangle_size / 2, this.canvas.height / 2 - triangle_size);
      region.closePath();
      this.ctx.fillStyle = 'rgb(200, 200, 200, 0.75)';
      this.ctx.fill(region);

      // Draw circle
      var circle_size = triangle_size * 1.5;
      this.ctx.lineWidth = this.canvas.height * 0.02;
      this.ctx.strokeStyle = 'rgb(200, 200, 200, 0.75)';
      this.ctx.beginPath();
      this.ctx.arc(this.canvas.width / 2, this.canvas.height / 2, circle_size, 0, 2 * Math.PI);
      this.ctx.stroke();
    }
  }, {
    key: "getCanvasScale",
    value: function getCanvasScale() {
      var scale;
      if (this.options.max_width && this.hdr && this.lsd.width > this.options.max_width) {
        scale = this.options.max_width / this.lsd.width;
      } else {
        scale = 1;
      }
      return scale;
    }

    /**
     * Makes an HTTP request to fetch a GIF
     * @param { String } url
     * @returns { Promise<ArrayBuffer> } Returns a promise which resolves with the response data.
     */
  }, {
    key: "fetchGIF",
    value: function fetchGIF(url) {
      var _this6 = this;
      var promise = getOpenPromise();
      var h = new XMLHttpRequest();
      h.open('GET', url, true);
      h.responseType = 'arraybuffer';
      h === null || h === void 0 ? void 0 : h.overrideMimeType('text/plain; charset=x-user-defined');
      h.onload = function () {
        if (h.status != 200) {
          _this6.showError();
          return promise.reject();
        }
        promise.resolve(h.response);
      };
      h.onprogress = function (e) {
        return e.lengthComputable && _this6.doShowProgress(e.loaded, e.total, true);
      };
      h.onerror = function (e) {
        log.error(e);
        _this6.showError();
      };
      h.send();
      return promise;
    }
  }]);
  return ConverseGif;
}();

// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/components/styles/gif.scss
var gif = __webpack_require__(3871);
;// CONCATENATED MODULE: ./src/shared/components/styles/gif.scss

      
      
      
      
      
      
      
      
      

var gif_options = {};

gif_options.styleTagTransform = (styleTagTransform_default());
gif_options.setAttributes = (setAttributesWithoutAttributes_default());

      gif_options.insert = insertBySelector_default().bind(null, "head");
    
gif_options.domAPI = (styleDomAPI_default());
gif_options.insertStyleElement = (insertStyleElement_default());

var gif_update = injectStylesIntoStyleTag_default()(gif/* default */.Z, gif_options);




       /* harmony default export */ const styles_gif = (gif/* default */.Z && gif/* default */.Z.locals ? gif/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/components/gif.js
function components_gif_typeof(obj) {
  "@babel/helpers - typeof";

  return components_gif_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;
  }, components_gif_typeof(obj);
}
var gif_templateObject;
function gif_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function components_gif_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function components_gif_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, components_gif_toPropertyKey(descriptor.key), descriptor);
  }
}
function components_gif_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) components_gif_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) components_gif_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function components_gif_toPropertyKey(arg) {
  var key = components_gif_toPrimitive(arg, "string");
  return components_gif_typeof(key) === "symbol" ? key : String(key);
}
function components_gif_toPrimitive(input, hint) {
  if (components_gif_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (components_gif_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function gif_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) gif_setPrototypeOf(subClass, superClass);
}
function gif_setPrototypeOf(o, p) {
  gif_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return gif_setPrototypeOf(o, p);
}
function gif_createSuper(Derived) {
  var hasNativeReflectConstruct = gif_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = gif_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = gif_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return gif_possibleConstructorReturn(this, result);
  };
}
function gif_possibleConstructorReturn(self, call) {
  if (call && (components_gif_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 gif_assertThisInitialized(self);
}
function gif_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function gif_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 gif_getPrototypeOf(o) {
  gif_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return gif_getPrototypeOf(o);
}






var ConverseGIFElement = /*#__PURE__*/function (_CustomElement) {
  gif_inherits(ConverseGIFElement, _CustomElement);
  var _super = gif_createSuper(ConverseGIFElement);
  function ConverseGIFElement() {
    var _this;
    components_gif_classCallCheck(this, ConverseGIFElement);
    _this = _super.call(this);
    _this.src = null;
    _this.autoplay = false;
    _this.noloop = false;
    _this.fallback = 'url';
    return _this;
  }
  components_gif_createClass(ConverseGIFElement, [{
    key: "initGIF",
    value: function initGIF() {
      var options = {
        'autoplay': this.autoplay,
        'loop': !this.noloop
      };
      if (this.progress_color) {
        options['progress_color'] = this.progress_color;
      }
      this.supergif = new ConverseGif(this, options);
    }
  }, {
    key: "updated",
    value: function updated(changed) {
      if (!this.supergif || changed.has('src')) {
        this.initGIF();
        return;
      }
      if (changed.has('autoplay')) {
        this.supergif.options.autoplay = this.autoplay;
      }
      if (changed.has('noloop')) {
        this.supergif.options.loop = !this.noloop;
      }
      if (changed.has('progress_color')) {
        this.supergif.options.progress_color = this.progress_color;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$supergif,
        _this2 = this;
      return (_this$supergif = this.supergif) !== null && _this$supergif !== void 0 && _this$supergif.load_error && ['url', 'empty'].includes(this.fallback) ? this.renderErrorFallback() : (0,external_lit_namespaceObject.html)(gif_templateObject || (gif_templateObject = gif_taggedTemplateLiteral(["<canvas class=\"gif-canvas\"\n                @mouseover=", "\n                @mouseleave=", "\n                @click=", "><img class=\"gif\" src=\"", "\"></a></canvas>"])), function () {
        return _this2.setHover();
      }, function () {
        return _this2.unsetHover();
      }, function (ev) {
        return _this2.onControlsClicked(ev);
      }, this.src);
    }
  }, {
    key: "renderErrorFallback",
    value: function renderErrorFallback() {
      if (this.fallback === 'url') {
        return getHyperlinkTemplate(this.src);
      } else if (this.fallback === 'empty') {
        return '';
      }
    }
  }, {
    key: "setHover",
    value: function setHover() {
      var _this3 = this;
      if (this.supergif) {
        this.supergif.hovering = true;
        this.hover_timeout && clearTimeout(this.hover_timeout);
        this.hover_timeout = setTimeout(function () {
          return _this3.unsetHover();
        }, 2000);
      }
    }
  }, {
    key: "unsetHover",
    value: function unsetHover() {
      if (this.supergif) this.supergif.hovering = false;
    }
  }, {
    key: "onControlsClicked",
    value: function onControlsClicked(ev) {
      ev.preventDefault();
      if (this.supergif.playing) {
        this.supergif.pause();
      } else if (this.supergif.frames.length > 0) {
        // When the user manually clicks play, we turn on looping
        this.supergif.options.loop = true;
        this.supergif.play();
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      /**
       * @typedef { Object } ConverseGIFComponentProperties
       * @property { Boolean } autoplay
       * @property { Boolean } noloop
       * @property { String } progress_color
       * @property { String } nick
       * @property { ('url'|'empty'|'error') } fallback
       * @property { String } src
       */
      return {
        'autoplay': {
          type: Boolean
        },
        'noloop': {
          type: Boolean
        },
        'progress_color': {
          type: String
        },
        'fallback': {
          type: String
        },
        'src': {
          type: String
        }
      };
    }
  }]);
  return ConverseGIFElement;
}(CustomElement);

shared_api.elements.define('converse-gif', ConverseGIFElement);
;// CONCATENATED MODULE: ./src/templates/gif.js
var templates_gif_templateObject, gif_templateObject2;
function templates_gif_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const templates_gif = (function (url, hide_url) {
  return (0,external_lit_namespaceObject.html)(templates_gif_templateObject || (templates_gif_templateObject = templates_gif_taggedTemplateLiteral(["<converse-gif autoplay noloop fallback='empty' src=", "></converse-gif>", ""])), url, hide_url ? '' : (0,external_lit_namespaceObject.html)(gif_templateObject2 || (gif_templateObject2 = templates_gif_taggedTemplateLiteral(["<a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a>"])), url, url));
});
;// CONCATENATED MODULE: ./node_modules/lit/async-directive.js

;// CONCATENATED MODULE: ./src/shared/directives/image.js
function directives_image_typeof(obj) {
  "@babel/helpers - typeof";

  return directives_image_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;
  }, directives_image_typeof(obj);
}
var directives_image_templateObject, image_templateObject2;
function directives_image_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function directives_image_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function directives_image_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, directives_image_toPropertyKey(descriptor.key), descriptor);
  }
}
function directives_image_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) directives_image_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) directives_image_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function directives_image_toPropertyKey(arg) {
  var key = directives_image_toPrimitive(arg, "string");
  return directives_image_typeof(key) === "symbol" ? key : String(key);
}
function directives_image_toPrimitive(input, hint) {
  if (directives_image_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (directives_image_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function directives_image_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) directives_image_setPrototypeOf(subClass, superClass);
}
function directives_image_setPrototypeOf(o, p) {
  directives_image_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return directives_image_setPrototypeOf(o, p);
}
function directives_image_createSuper(Derived) {
  var hasNativeReflectConstruct = directives_image_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = directives_image_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = directives_image_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return directives_image_possibleConstructorReturn(this, result);
  };
}
function directives_image_possibleConstructorReturn(self, call) {
  if (call && (directives_image_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 directives_image_assertThisInitialized(self);
}
function directives_image_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function directives_image_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 directives_image_getPrototypeOf(o) {
  directives_image_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return directives_image_getPrototypeOf(o);
}






var URI = public_converse.env.URI;
var ImageDirective = /*#__PURE__*/function (_AsyncDirective) {
  directives_image_inherits(ImageDirective, _AsyncDirective);
  var _super = directives_image_createSuper(ImageDirective);
  function ImageDirective() {
    directives_image_classCallCheck(this, ImageDirective);
    return _super.apply(this, arguments);
  }
  directives_image_createClass(ImageDirective, [{
    key: "render",
    value: function render(src, href, onLoad, onClick) {
      return href ? (0,external_lit_namespaceObject.html)(directives_image_templateObject || (directives_image_templateObject = directives_image_taggedTemplateLiteral(["<a href=\"", "\" class=\"chat-image__link\" target=\"_blank\" rel=\"noopener\">", "</a>"])), href, this.renderImage(src, href, onLoad, onClick)) : this.renderImage(src, href, onLoad, onClick);
    }
  }, {
    key: "renderImage",
    value: function renderImage(src, href, onLoad, onClick) {
      var _this = this;
      return (0,external_lit_namespaceObject.html)(image_templateObject2 || (image_templateObject2 = directives_image_taggedTemplateLiteral(["<img class=\"chat-image img-thumbnail\"\n                loading=\"lazy\"\n                src=\"", "\"\n                @click=", "\n                @error=", "\n                @load=\"", "\"/></a>"])), src, onClick, function () {
        return _this.onError(src, href, onLoad, onClick);
      }, onLoad);
    }
  }, {
    key: "onError",
    value: function onError(src, href, onLoad, onClick) {
      if (isURLWithImageExtension(src)) {
        href && this.setValue(getHyperlinkTemplate(href));
      } else {
        // Before giving up and falling back to just rendering a hyperlink,
        // we attach `.png` and try one more time.
        // This works with some Imgur URLs
        var uri = new URI(src);
        var filename = uri.filename();
        uri.filename("".concat(filename, ".png"));
        this.setValue(renderImage(uri.toString(), href, onLoad, onClick));
      }
    }
  }]);
  return ImageDirective;
}(async_directive_f);
/**
 * lit directive which attempts to render an <img> element from a URL.
 * It will fall back to rendering an <a> element if it can't.
 *
 * @param { String } src - The value that will be assigned to the `src` attribute of the `<img>` element.
 * @param { String } href - The value that will be assigned to the `href` attribute of the `<img>` element.
 * @param { Function } onLoad - A callback function to be called once the image has loaded.
 * @param { Function } onClick - A callback function to be called once the image has been clicked.
 */
var renderImage = directive_e(ImageDirective);
;// CONCATENATED MODULE: ./src/templates/image.js
var templates_image_templateObject;
function templates_image_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const src_templates_image = (function (o) {
  return (0,external_lit_namespaceObject.html)(templates_image_templateObject || (templates_image_templateObject = templates_image_taggedTemplateLiteral(["", ""])), renderImage(o.src || o.url, o.href, o.onLoad, o.onClick));
});
;// CONCATENATED MODULE: ./src/shared/directives/styling.js
function styling_typeof(obj) {
  "@babel/helpers - typeof";

  return styling_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;
  }, styling_typeof(obj);
}
var styling_templateObject, styling_templateObject2;
function styling_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  styling_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" == styling_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 styling_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function styling_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function styling_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, styling_toPropertyKey(descriptor.key), descriptor);
  }
}
function styling_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) styling_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) styling_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function styling_toPropertyKey(arg) {
  var key = styling_toPrimitive(arg, "string");
  return styling_typeof(key) === "symbol" ? key : String(key);
}
function styling_toPrimitive(input, hint) {
  if (styling_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (styling_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function styling_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) styling_setPrototypeOf(subClass, superClass);
}
function styling_setPrototypeOf(o, p) {
  styling_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return styling_setPrototypeOf(o, p);
}
function styling_createSuper(Derived) {
  var hasNativeReflectConstruct = styling_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = styling_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = styling_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return styling_possibleConstructorReturn(this, result);
  };
}
function styling_possibleConstructorReturn(self, call) {
  if (call && (styling_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 styling_assertThisInitialized(self);
}
function styling_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function styling_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 styling_getPrototypeOf(o) {
  styling_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return styling_getPrototypeOf(o);
}
function styling_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 styling_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        styling_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        styling_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





function transform(_x) {
  return _transform.apply(this, arguments);
}
function _transform() {
  _transform = styling_asyncToGenerator( /*#__PURE__*/styling_regeneratorRuntime().mark(function _callee(t) {
    return styling_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.prev = 0;
          _context.next = 3;
          return t.addTemplates();
        case 3:
          _context.next = 8;
          break;
        case 5:
          _context.prev = 5;
          _context.t0 = _context["catch"](0);
          log.error(_context.t0);
        case 8:
          return _context.abrupt("return", t.payload);
        case 9:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[0, 5]]);
  }));
  return _transform.apply(this, arguments);
}
var StylingDirective = /*#__PURE__*/function (_Directive) {
  styling_inherits(StylingDirective, _Directive);
  var _super = styling_createSuper(StylingDirective);
  function StylingDirective() {
    styling_classCallCheck(this, StylingDirective);
    return _super.apply(this, arguments);
  }
  styling_createClass(StylingDirective, [{
    key: "render",
    value: function render(txt, offset, options) {
      // eslint-disable-line class-methods-use-this
      var t = new RichText(txt, offset, Object.assign(options, {
        'show_images': false,
        'embed_videos': false,
        'embed_audio': false
      }));
      return (0,external_lit_namespaceObject.html)(styling_templateObject || (styling_templateObject = styling_taggedTemplateLiteral(["", ""])), until_m(transform(t), (0,external_lit_namespaceObject.html)(styling_templateObject2 || (styling_templateObject2 = styling_taggedTemplateLiteral(["", ""])), t)));
    }
  }]);
  return StylingDirective;
}(directive_i);
var renderStylingDirectiveBody = directive_e(StylingDirective);
;// CONCATENATED MODULE: ./src/shared/styling.js
var shared_styling_templateObject, shared_styling_templateObject2, styling_templateObject3, styling_templateObject4, styling_templateObject5, styling_templateObject6;
function shared_styling_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Utility functions to help with parsing XEP-393 message styling hints
 * @todo Other parsing helpers can be made more abstract and placed here.
 */


var bracketing_directives = ['*', '_', '~', '`'];
var styling_directives = [].concat(bracketing_directives, ['```', '>']);
var styling_map = {
  '*': {
    'name': 'strong',
    'type': 'span'
  },
  '_': {
    'name': 'emphasis',
    'type': 'span'
  },
  '~': {
    'name': 'strike',
    'type': 'span'
  },
  '`': {
    'name': 'preformatted',
    'type': 'span'
  },
  '```': {
    'name': 'preformatted_block',
    'type': 'block'
  },
  '>': {
    'name': 'quote',
    'type': 'block'
  }
};
var dont_escape = ['_', '>', '`', '~'];
var styling_templates = {
  // m is the chatbox model
  // i is the offset of this directive relative to the start of the original message
  'emphasis': function emphasis(txt, i, options) {
    return (0,external_lit_namespaceObject.html)(shared_styling_templateObject || (shared_styling_templateObject = shared_styling_taggedTemplateLiteral(["<span class=\"styling-directive\">_</span><i>", "</i><span class=\"styling-directive\">_</span>"])), renderStylingDirectiveBody(txt, i, options));
  },
  'preformatted': function preformatted(txt) {
    return (0,external_lit_namespaceObject.html)(shared_styling_templateObject2 || (shared_styling_templateObject2 = shared_styling_taggedTemplateLiteral(["<span class=\"styling-directive\">`</span><code>", "</code><span class=\"styling-directive\">`</span>"], ["<span class=\"styling-directive\">\\`</span><code>", "</code><span class=\"styling-directive\">\\`</span>"])), txt);
  },
  'preformatted_block': function preformatted_block(txt) {
    return (0,external_lit_namespaceObject.html)(styling_templateObject3 || (styling_templateObject3 = shared_styling_taggedTemplateLiteral(["<div class=\"styling-directive\">```</div><code class=\"block\">", "</code><div class=\"styling-directive\">```</div>"], ["<div class=\"styling-directive\">\\`\\`\\`</div><code class=\"block\">", "</code><div class=\"styling-directive\">\\`\\`\\`</div>"])), txt);
  },
  'quote': function quote(txt, i, options) {
    return (0,external_lit_namespaceObject.html)(styling_templateObject4 || (styling_templateObject4 = shared_styling_taggedTemplateLiteral(["<blockquote>", "</blockquote>"])), renderStylingDirectiveBody(txt, i, options));
  },
  'strike': function strike(txt, i, options) {
    return (0,external_lit_namespaceObject.html)(styling_templateObject5 || (styling_templateObject5 = shared_styling_taggedTemplateLiteral(["<span class=\"styling-directive\">~</span><del>", "</del><span class=\"styling-directive\">~</span>"])), renderStylingDirectiveBody(txt, i, options));
  },
  'strong': function strong(txt, i, options) {
    return (0,external_lit_namespaceObject.html)(styling_templateObject6 || (styling_templateObject6 = shared_styling_taggedTemplateLiteral(["<span class=\"styling-directive\">*</span><b>", "</b><span class=\"styling-directive\">*</span>"])), renderStylingDirectiveBody(txt, i, options));
  }
};

/**
 * Checks whether a given character "d" at index "i" of "text" is a valid opening or closing directive.
 * @param { String } d - The potential directive
 * @param { String } text - The text in which  the directive appears
 * @param { Number } i - The directive index
 * @param { Boolean } opening - Check for a valid opening or closing directive
 */
function isValidDirective(d, text, i, opening) {
  // Ignore directives that are parts of words
  // More info on the Regexes used here: https://javascript.info/regexp-unicode#unicode-properties-p
  if (opening) {
    var regex = RegExp(dont_escape.includes(d) ? "^(\\p{L}|\\p{N})".concat(d) : "^(\\p{L}|\\p{N})\\".concat(d), 'u');
    if (i > 1 && regex.test(text.slice(i - 1))) {
      return false;
    }
    var is_quote = isQuoteDirective(d);
    if (is_quote && i > 0 && text[i - 1] !== '\n') {
      // Quote directives must be on newlines
      return false;
    } else if (bracketing_directives.includes(d) && text[i + 1] === d) {
      // Don't consider empty bracketing directives as valid (e.g. **, `` etc.)
      return false;
    }
  } else {
    var _regex = RegExp(dont_escape.includes(d) ? "^".concat(d, "(\\p{L}|\\p{N})") : "^\\".concat(d, "(\\p{L}|\\p{N})"), 'u');
    if (i < text.length - 1 && _regex.test(text.slice(i))) {
      return false;
    }
    if (bracketing_directives.includes(d) && text[i - 1] === d) {
      // Don't consider empty directives as valid (e.g. **, `` etc.)
      return false;
    }
  }
  return true;
}

/**
 * Given a specific index "i" of "text", return the directive it matches or null otherwise.
 * @param { String } text - The text in which  the directive appears
 * @param { Number } i - The directive index
 * @param { Boolean } opening - Whether we're looking for an opening or closing directive
 */
function getDirective(text, i) {
  var opening = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var d;
  if (/(^```[\s,\u200B]*\n)|(^```[\s,\u200B]*$)/.test(text.slice(i)) && (i === 0 || text[i - 1] === '>' || /\n\u200B{0,2}$/.test(text.slice(0, i)))) {
    d = text.slice(i, i + 3);
  } else if (styling_directives.includes(text.slice(i, i + 1))) {
    d = text.slice(i, i + 1);
    if (!isValidDirective(d, text, i, opening)) return null;
  } else {
    return null;
  }
  return d;
}

/**
 * Given a directive "d", which occurs in "text" at index "i", check that it
 * has a valid closing directive and return the length from start to end of the
 * directive.
 * @param { String } d -The directive
 * @param { Number } i - The directive index
 * @param { String } text -The text in which the directive appears
 */
function getDirectiveLength(d, text, i) {
  if (!d) return 0;
  var begin = i;
  i += d.length;
  if (isQuoteDirective(d)) {
    i += text.slice(i).split(/\n[^>]/).shift().length;
    return i - begin;
  } else if (styling_map[d].type === 'span') {
    var line = text.slice(i).split('\n').shift();
    var j = 0;
    var idx = line.indexOf(d);
    while (idx !== -1) {
      if (getDirective(text, i + idx, false) === d) {
        return idx + 2 * d.length;
      }
      idx = line.indexOf(d, j++);
    }
    return 0;
  } else {
    // block directives
    var substring = text.slice(i + 1);
    var _j = 0;
    var _idx = substring.indexOf(d);
    while (_idx !== -1) {
      if (getDirective(text, i + 1 + _idx, false) === d) {
        return _idx + 1 + 2 * d.length;
      }
      _idx = substring.indexOf(d, _j++);
    }
    return 0;
  }
}
function getDirectiveAndLength(text, i) {
  var d = getDirective(text, i);
  var length = d ? getDirectiveLength(d, text, i) : 0;
  return length > 0 ? {
    d: d,
    length: length
  } : {};
}
var isQuoteDirective = function isQuoteDirective(d) {
  return ['>', '&gt;'].includes(d);
};
function getDirectiveTemplate(d, text, offset, options) {
  var template = styling_templates[styling_map[d].name];
  if (isQuoteDirective(d)) {
    var newtext = text
    // Don't show the directive itself
    .replace(/\n>\s/g, "\n\u200B\u200B").replace(/\n>/g, "\n\u200B").replace(/\n$/, ''); // Trim line-break at the end
    return template(newtext, offset, options);
  } else {
    return template(text, offset, options);
  }
}
function containsDirectives(text) {
  for (var i = 0; i < styling_directives.length; i++) {
    if (text.includes(styling_directives[i])) {
      return true;
    }
  }
}
;// CONCATENATED MODULE: ./src/shared/chat/templates/new-day.js
var new_day_templateObject;
function new_day_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const new_day = (function (o) {
  return (0,external_lit_namespaceObject.html)(new_day_templateObject || (new_day_templateObject = new_day_taggedTemplateLiteral(["\n    <div class=\"message date-separator\" data-isodate=\"", "\">\n        <hr class=\"separator\"/>\n        <time class=\"separator-text\" datetime=\"", "\"><span>", "</span></time>\n    </div>\n"])), o.time, o.time, o.datestring);
});
;// CONCATENATED MODULE: ./src/shared/chat/utils.js
function shared_chat_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return shared_chat_utils_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;
  }, shared_chat_utils_typeof(obj);
}
var chat_utils_templateObject, chat_utils_templateObject2, chat_utils_templateObject3, chat_utils_templateObject4, chat_utils_templateObject5, chat_utils_templateObject6;
function shared_chat_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  shared_chat_utils_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" == shared_chat_utils_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 chat_utils_toConsumableArray(arr) {
  return chat_utils_arrayWithoutHoles(arr) || chat_utils_iterableToArray(arr) || chat_utils_unsupportedIterableToArray(arr) || chat_utils_nonIterableSpread();
}
function chat_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function chat_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return chat_utils_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 chat_utils_arrayLikeToArray(o, minLen);
}
function chat_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function chat_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return chat_utils_arrayLikeToArray(arr);
}
function chat_utils_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 chat_utils_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function shared_chat_utils_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 shared_chat_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        shared_chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        shared_chat_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var chat_utils_converse$env = public_converse.env,
  utils_dayjs = chat_utils_converse$env.dayjs,
  shared_chat_utils_u = chat_utils_converse$env.u;
function getHeadingDropdownItem(_x) {
  return _getHeadingDropdownItem.apply(this, arguments);
}
function _getHeadingDropdownItem() {
  _getHeadingDropdownItem = shared_chat_utils_asyncToGenerator( /*#__PURE__*/shared_chat_utils_regeneratorRuntime().mark(function _callee(promise_or_data) {
    var data;
    return shared_chat_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return promise_or_data;
        case 2:
          data = _context.sent;
          return _context.abrupt("return", data ? (0,external_lit_namespaceObject.html)(chat_utils_templateObject5 || (chat_utils_templateObject5 = chat_utils_taggedTemplateLiteral(["\n              <a href=\"#\" class=\"dropdown-item ", "\" @click=", " title=\"", "\">\n                  <converse-icon\n                      size=\"1em\"\n                      class=\"fa ", "\"\n                  ></converse-icon>\n                  ", "\n              </a>\n          "])), data.a_class, data.handler, data.i18n_title, data.icon_class, data.i18n_text) : '');
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _getHeadingDropdownItem.apply(this, arguments);
}
function getHeadingStandaloneButton(_x2) {
  return _getHeadingStandaloneButton.apply(this, arguments);
}
function _getHeadingStandaloneButton() {
  _getHeadingStandaloneButton = shared_chat_utils_asyncToGenerator( /*#__PURE__*/shared_chat_utils_regeneratorRuntime().mark(function _callee2(promise_or_data) {
    var data;
    return shared_chat_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return promise_or_data;
        case 2:
          data = _context2.sent;
          return _context2.abrupt("return", (0,external_lit_namespaceObject.html)(chat_utils_templateObject6 || (chat_utils_templateObject6 = chat_utils_taggedTemplateLiteral(["\n        <a\n            href=\"#\"\n            class=\"chatbox-btn ", "\"\n            @click=", "\n            title=\"", "\"\n        >\n            <converse-icon\n                size=\"1em\"\n                class=\"fa ", "\"\n            ></converse-icon>\n        </a>\n    "])), data.a_class, data.handler, data.i18n_title, data.icon_class));
        case 4:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _getHeadingStandaloneButton.apply(this, arguments);
}
function getStandaloneButtons(promise) {
  return promise.then(function (btns) {
    return btns.filter(function (b) {
      return b.standalone;
    }).map(function (b) {
      return getHeadingStandaloneButton(b);
    }).reverse().map(function (b) {
      return until_m(b, '');
    });
  });
}
function getDropdownButtons(promise) {
  return promise.then(function (btns) {
    var dropdown_btns = btns.filter(function (b) {
      return !b.standalone;
    }).map(function (b) {
      return getHeadingDropdownItem(b);
    });
    return dropdown_btns.length ? (0,external_lit_namespaceObject.html)(chat_utils_templateObject || (chat_utils_templateObject = chat_utils_taggedTemplateLiteral(["<converse-dropdown class=\"chatbox-btn dropleft\" .items=", "></converse-dropdown>"])), dropdown_btns) : '';
  });
}
function onScrolledDown(model) {
  if (!model.isHidden()) {
    if (shared_api.settings.get('allow_url_history_change')) {
      // Clear location hash if set to one of the messages in our history
      var hash = window.location.hash;
      hash && model.messages.get(hash.slice(1)) && shared_converse.router.history.navigate();
    }
  }
}

/**
 * Called when the chat content is scrolled up or down.
 * We want to record when the user has scrolled away from
 * the bottom, so that we don't automatically scroll away
 * from what the user is reading when new messages are received.
 *
 * Don't call this method directly, instead, call `markScrolled`,
 * which debounces this method.
 */
function _markScrolled(ev) {
  var el = ev.target;
  if (el.nodeName.toLowerCase() !== 'converse-chat-content') {
    return;
  }
  var scrolled = true;
  var is_at_bottom = Math.floor(el.scrollTop) === 0;
  var is_at_top = Math.ceil(el.clientHeight - el.scrollTop) >= el.scrollHeight - Math.ceil(el.scrollHeight / 20);
  if (is_at_bottom) {
    scrolled = false;
    onScrolledDown(el.model);
  } else if (is_at_top) {
    /**
     * Triggered once the chat's message area has been scrolled to the top
     * @event _converse#chatBoxScrolledUp
     * @property { _converse.ChatBoxView | _converse.ChatRoomView } view
     * @example _converse.api.listen.on('chatBoxScrolledUp', obj => { ... });
     */
    shared_api.trigger('chatBoxScrolledUp', el);
  }
  if (el.model.get('scolled') !== scrolled) {
    el.model.ui.set({
      scrolled: scrolled
    });
  }
}
var markScrolled = lodash_es_debounce(function (ev) {
  return _markScrolled(ev);
}, 50);

/**
 * Given a message object, returns a TemplateResult indicating a new day if
 * the passed in message is more than a day later than its predecessor.
 * @param { _converse.Message }
 */
function getDayIndicator(message) {
  var _message$collection;
  var messages = (_message$collection = message.collection) === null || _message$collection === void 0 ? void 0 : _message$collection.models;
  if (!messages) {
    return;
  }
  var idx = messages.indexOf(message);
  var prev_message = messages[idx - 1];
  if (!prev_message || utils_dayjs(message.get('time')).isAfter(utils_dayjs(prev_message.get('time')), 'day')) {
    var day_date = utils_dayjs(message.get('time')).startOf('day');
    return new_day({
      'type': 'date',
      'time': day_date.toISOString(),
      'datestring': day_date.format("dddd MMM Do YYYY")
    });
  }
}
function getHats(message) {
  if (message.get('type') === 'groupchat') {
    var _message$occupant;
    var allowed_hats = shared_api.settings.get('muc_hats').filter(function (hat) {
      return hat;
    }).map(function (hat) {
      return hat.toLowerCase();
    });
    var vcard_roles = [];
    if (allowed_hats.includes('vcard_roles')) {
      vcard_roles = message.vcard ? message.vcard.get('role') : null;
      vcard_roles = vcard_roles ? vcard_roles.split(',').filter(function (hat) {
        return hat;
      }).map(function (hat) {
        return {
          title: hat
        };
      }) : [];
    }
    var muc_role = message.occupant ? [message.occupant.get('role')] : [];
    var muc_affiliation = message.occupant ? [message.occupant.get('affiliation')] : [];
    var affiliation_role_hats = [].concat(muc_role, muc_affiliation).filter(function (hat) {
      return hat;
    }).filter(function (hat) {
      return allowed_hats.includes(hat.toLowerCase());
    }).map(function (hat) {
      return {
        title: hat
      };
    });
    var hats = allowed_hats.includes('xep317') ? ((_message$occupant = message.occupant) === null || _message$occupant === void 0 ? void 0 : _message$occupant.get('hats')) || [] : [];
    return [].concat(chat_utils_toConsumableArray(hats), chat_utils_toConsumableArray(vcard_roles), chat_utils_toConsumableArray(affiliation_role_hats));
  }
  return [];
}
function unique(arr) {
  return chat_utils_toConsumableArray(new Set(arr));
}
function getTonedEmojis() {
  if (!public_converse.emojis.toned) {
    public_converse.emojis.toned = unique(Object.values(public_converse.emojis.json.people).filter(function (person) {
      return person.sn.includes('_tone');
    }).map(function (person) {
      return person.sn.replace(/_tone[1-5]/, '');
    }));
  }
  return public_converse.emojis.toned;
}
function getEmojiMarkup(data) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    unicode_only: false,
    add_title_wrapper: false
  };
  var emoji = data.emoji;
  var shortname = data.shortname;
  if (emoji) {
    if (options.unicode_only) {
      return emoji;
    } else if (shared_api.settings.get('use_system_emojis')) {
      if (options.add_title_wrapper) {
        return shortname ? (0,external_lit_namespaceObject.html)(chat_utils_templateObject2 || (chat_utils_templateObject2 = chat_utils_taggedTemplateLiteral(["<span title=\"", "\">", "</span>"])), shortname, emoji) : emoji;
      } else {
        return emoji;
      }
    } else {
      var path = shared_api.settings.get('emoji_image_path');
      return (0,external_lit_namespaceObject.html)(chat_utils_templateObject3 || (chat_utils_templateObject3 = chat_utils_taggedTemplateLiteral(["<img class=\"emoji\"\n                loading=\"lazy\"\n                draggable=\"false\"\n                title=\"", "\"\n                alt=\"", "\"\n                src=\"", "/72x72/", ".png\"/>"])), shortname, emoji, path, data.cp);
    }
  } else if (options.unicode_only) {
    return shortname;
  } else {
    return (0,external_lit_namespaceObject.html)(chat_utils_templateObject4 || (chat_utils_templateObject4 = chat_utils_taggedTemplateLiteral(["<img class=\"emoji\"\n            loading=\"lazy\"\n            draggable=\"false\"\n            title=\"", "\"\n            alt=\"", "\"\n            src=\"", "\">"])), shortname, shortname, public_converse.emojis.by_sn[shortname].url);
  }
}
function utils_addEmojisMarkup(text, options) {
  var list = [text];
  [].concat(chat_utils_toConsumableArray(getShortnameReferences(text)), chat_utils_toConsumableArray(getCodePointReferences(text))).sort(function (a, b) {
    return b.begin - a.begin;
  }).forEach(function (ref) {
    var text = list.shift();
    var emoji = getEmojiMarkup(ref, options);
    if (typeof emoji === 'string') {
      list = [text.slice(0, ref.begin) + emoji + text.slice(ref.end)].concat(chat_utils_toConsumableArray(list));
    } else {
      list = [text.slice(0, ref.begin), emoji, text.slice(ref.end)].concat(chat_utils_toConsumableArray(list));
    }
  });
  return list;
}

/**
 * Returns an emoji represented by the passed in shortname.
 * Scans the passed in text for shortnames and replaces them with
 * emoji unicode glyphs or alternatively if it's a custom emoji
 * without unicode representation then a lit TemplateResult
 * which represents image tag markup is returned.
 *
 * The shortname needs to be defined in `emojis.json`
 * and needs to have either a `cp` attribute for the codepoint, or
 * an `url` attribute which points to the source for the image.
 *
 * @namespace u
 * @method u.shortnamesToEmojis
 * @param { String } str - String containg the shortname(s)
 * @param { Object } options
 * @param { Boolean } options.unicode_only - Whether emojis are rendered as
 *  unicode codepoints. If so, the returned result will be an array
 *  with containing one string, because the emojis themselves will
 *  also be strings. If set to false, emojis will be represented by
 *  lit TemplateResult objects.
 * @param { Boolean } options.add_title_wrapper - Whether unicode
 *  codepoints should be wrapped with a `<span>` element with a
 *  title, so that the shortname is shown upon hovering with the
 *  mouse.
 * @returns {Array} An array of at least one string, or otherwise
 * strings and lit TemplateResult objects.
 */
function shortnamesToEmojis(str) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    unicode_only: false,
    add_title_wrapper: false
  };
  str = convertASCII2Emoji(str);
  return utils_addEmojisMarkup(str, options);
}
Object.assign(shared_chat_utils_u, {
  shortnamesToEmojis: shortnamesToEmojis
});
;// CONCATENATED MODULE: ./src/shared/rich-text.js
function rich_text_typeof(obj) {
  "@babel/helpers - typeof";

  return rich_text_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;
  }, rich_text_typeof(obj);
}
var rich_text_templateObject, rich_text_templateObject2;
function rich_text_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  rich_text_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" == rich_text_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 rich_text_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 rich_text_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        rich_text_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        rich_text_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function rich_text_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 rich_text_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? rich_text_ownKeys(Object(source), !0).forEach(function (key) {
      rich_text_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : rich_text_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function rich_text_defineProperty(obj, key, value) {
  key = rich_text_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 rich_text_toConsumableArray(arr) {
  return rich_text_arrayWithoutHoles(arr) || rich_text_iterableToArray(arr) || rich_text_unsupportedIterableToArray(arr) || rich_text_nonIterableSpread();
}
function rich_text_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function rich_text_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function rich_text_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return rich_text_arrayLikeToArray(arr);
}
function rich_text_createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = rich_text_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 rich_text_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return rich_text_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 rich_text_arrayLikeToArray(o, minLen);
}
function rich_text_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 rich_text_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function rich_text_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, rich_text_toPropertyKey(descriptor.key), descriptor);
  }
}
function rich_text_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) rich_text_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) rich_text_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function rich_text_toPropertyKey(arg) {
  var key = rich_text_toPrimitive(arg, "string");
  return rich_text_typeof(key) === "symbol" ? key : String(key);
}
function rich_text_toPrimitive(input, hint) {
  if (rich_text_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (rich_text_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function rich_text_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) rich_text_setPrototypeOf(subClass, superClass);
}
function rich_text_createSuper(Derived) {
  var hasNativeReflectConstruct = rich_text_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = rich_text_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = rich_text_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return rich_text_possibleConstructorReturn(this, result);
  };
}
function rich_text_possibleConstructorReturn(self, call) {
  if (call && (rich_text_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 rich_text_assertThisInitialized(self);
}
function rich_text_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function rich_text_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  rich_text_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !rich_text_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return rich_text_construct(Class, arguments, rich_text_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return rich_text_setPrototypeOf(Wrapper, Class);
  };
  return rich_text_wrapNativeSuper(Class);
}
function rich_text_construct(Parent, args, Class) {
  if (rich_text_isNativeReflectConstruct()) {
    rich_text_construct = Reflect.construct.bind();
  } else {
    rich_text_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) rich_text_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return rich_text_construct.apply(null, arguments);
}
function rich_text_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 rich_text_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function rich_text_setPrototypeOf(o, p) {
  rich_text_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return rich_text_setPrototypeOf(o, p);
}
function rich_text_getPrototypeOf(o) {
  rich_text_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return rich_text_getPrototypeOf(o);
}
function rich_text_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}













var rich_text_isString = function isString(s) {
  return typeof s === 'string';
};

// We don't render more than two line-breaks, replace extra line-breaks with
// the zero-width whitespace character
var collapseLineBreaks = function collapseLineBreaks(text) {
  return text.replace(/\n\n+/g, function (m) {
    return "\n".concat("\u200B".repeat(m.length - 2), "\n");
  });
};
var tplMentionWithNick = function tplMentionWithNick(o) {
  return (0,external_lit_namespaceObject.html)(rich_text_templateObject || (rich_text_templateObject = rich_text_taggedTemplateLiteral(["<span class=\"mention mention--self badge badge-info\" data-uri=\"", "\">", "</span>"])), o.uri, o.mention);
};
var tplMention = function tplMention(o) {
  return (0,external_lit_namespaceObject.html)(rich_text_templateObject2 || (rich_text_templateObject2 = rich_text_taggedTemplateLiteral(["<span class=\"mention\" data-uri=\"", "\">", "</span>"])), o.uri, o.mention);
};

/**
 * @class RichText
 * A String subclass that is used to render rich text (i.e. text that contains
 * hyperlinks, images, mentions, styling etc.).
 *
 * The "rich" parts of the text is represented by lit TemplateResult
 * objects which are added via the {@link RichText.addTemplateResult}
 * method and saved as metadata.
 *
 * By default Converse adds TemplateResults to support emojis, hyperlinks,
 * images, map URIs and mentions.
 *
 * 3rd party plugins can listen for the `beforeMessageBodyTransformed`
 * and/or `afterMessageBodyTransformed` events and then call
 * `addTemplateResult` on the RichText instance in order to add their own
 * rich features.
 */
var RichText = /*#__PURE__*/function (_String) {
  rich_text_inherits(RichText, _String);
  var _super = rich_text_createSuper(RichText);
  /**
   * Create a new {@link RichText} instance.
   * @param { String } text - The text to be annotated
   * @param { number } offset - The offset of this particular piece of text
   *  from the start of the original message text. This is necessary because
   *  RichText instances can be nested when templates call directives
   *  which create new RichText instances (as happens with XEP-393 styling directives).
   * @param { Object } options
   * @param { String } options.nick - The current user's nickname (only relevant if the message is in a XEP-0045 MUC)
   * @param { Boolean } options.render_styling - Whether XEP-0393 message styling should be applied to the message
   * @param { Boolean } [options.embed_audio] - Whether audio URLs should be rendered as <audio> elements.
   *  If set to `true`, then audio files will always be rendered with an
   *  audio player. If set to `false`, they won't, and if not defined, then the `embed_audio` setting
   *  is used to determine whether they should be rendered as playable audio or as hyperlinks.
   * @param { Boolean } [options.embed_videos] - Whether video URLs should be rendered as <video> elements.
   *  If set to `true`, then videos will always be rendered with a video
   *  player. If set to `false`, they won't, and if not defined, then the `embed_videos` setting
   *  is used to determine whether they should be rendered as videos or as hyperlinks.
   * @param { Array } [options.mentions] - An array of mention references
   * @param { Array } [options.media_urls] - An array of {@link MediaURLMetadata} objects,
   *  used to render media such as images, videos and audio. It might not be
   *  possible to have the media metadata available, so if this value is
   *  `undefined` then the passed-in `text` will be parsed for URLs. If you
   *  don't want this parsing to happen, pass in an empty array for this
   *  option.
   * @param { Boolean } [options.show_images] - Whether image URLs should be rendered as <img> elements.
   * @param { Boolean } options.show_me_message - Whether /me messages should be rendered differently
   * @param { Function } options.onImgClick - Callback for when an inline rendered image has been clicked
   * @param { Function } options.onImgLoad - Callback for when an inline rendered image has been loaded
   */
  function RichText(text) {
    var _this;
    var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    rich_text_classCallCheck(this, RichText);
    _this = _super.call(this, text);
    _this.embed_audio = options === null || options === void 0 ? void 0 : options.embed_audio;
    _this.embed_videos = options === null || options === void 0 ? void 0 : options.embed_videos;
    _this.mentions = (options === null || options === void 0 ? void 0 : options.mentions) || [];
    _this.media_urls = options === null || options === void 0 ? void 0 : options.media_urls;
    _this.nick = options === null || options === void 0 ? void 0 : options.nick;
    _this.offset = offset;
    _this.onImgClick = options === null || options === void 0 ? void 0 : options.onImgClick;
    _this.onImgLoad = options === null || options === void 0 ? void 0 : options.onImgLoad;
    _this.options = options;
    _this.payload = [];
    _this.references = [];
    _this.render_styling = options === null || options === void 0 ? void 0 : options.render_styling;
    _this.show_images = options === null || options === void 0 ? void 0 : options.show_images;
    _this.hide_media_urls = options === null || options === void 0 ? void 0 : options.hide_media_urls;
    return _this;
  }
  rich_text_createClass(RichText, [{
    key: "shouldRenderMedia",
    value: function shouldRenderMedia(url_text, type) {
      var override;
      if (type === 'image') {
        override = this.show_images;
      } else if (type === 'audio') {
        override = this.embed_audio;
      } else if (type === 'video') {
        override = this.embed_videos;
      }
      if (typeof override === 'boolean') {
        return override;
      }
      return shouldRenderMediaFromURL(url_text, type);
    }

    /**
     * Look for `http` URIs and return templates that render them as URL links
     * @param { String } text
     * @param { number } local_offset - The index of the passed in text relative to
     *  the start of this RichText instance (which is not necessarily the same as the
     *  offset from the start of the original message stanza's body text).
     */
  }, {
    key: "addHyperlinks",
    value: function addHyperlinks(text, local_offset) {
      var _this2 = this;
      var full_offset = local_offset + this.offset;
      var urls_meta = this.media_urls || getMediaURLsMetadata(text, local_offset).media_urls || [];
      var media_urls = utils_getMediaURLs(urls_meta, text, full_offset);
      media_urls.filter(function (o) {
        return !o.is_encrypted;
      }).forEach(function (url_obj) {
        var url_text = url_obj.url;
        var filtered_url = filterQueryParamsFromURL(url_text);
        var template;
        if (isGIFURL(url_text) && _this2.shouldRenderMedia(url_text, 'image')) {
          template = templates_gif(filtered_url, _this2.hide_media_urls);
        } else if (isImageURL(url_text) && _this2.shouldRenderMedia(url_text, 'image')) {
          template = src_templates_image({
            'src': filtered_url,
            // XXX: bit of an abuse of `hide_media_urls`, might want a dedicated option here
            'href': _this2.hide_media_urls ? null : filtered_url,
            'onClick': _this2.onImgClick,
            'onLoad': _this2.onImgLoad
          });
        } else if (isVideoURL(url_text) && _this2.shouldRenderMedia(url_text, 'video')) {
          template = video(filtered_url, _this2.hide_media_urls);
        } else if (isAudioURL(url_text) && _this2.shouldRenderMedia(url_text, 'audio')) {
          template = audio(filtered_url, _this2.hide_media_urls);
        } else {
          template = getHyperlinkTemplate(filtered_url);
        }
        _this2.addTemplateResult(url_obj.start + local_offset, url_obj.end + local_offset, template);
      });
    }

    /**
     * Look for `geo` URIs and return templates that render them as URL links
     * @param { String } text
     * @param { number } offset - The index of the passed in text relative to
     *  the start of the message body text.
     */
  }, {
    key: "addMapURLs",
    value: function addMapURLs(text, offset) {
      var regex = /geo:([\-0-9.]+),([\-0-9.]+)(?:,([\-0-9.]+))?(?:\?(.*))?/g;
      var matches = text.matchAll(regex);
      var _iterator = rich_text_createForOfIteratorHelper(matches),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var m = _step.value;
          this.addTemplateResult(m.index + offset, m.index + m[0].length + offset, getHyperlinkTemplate(m[0].replace(regex, shared_api.settings.get('geouri_replacement'))));
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }

    /**
     * Look for emojis (shortnames or unicode) and add templates for rendering them.
     * @param { String } text
     * @param { number } offset - The index of the passed in text relative to
     *  the start of the message body text.
     */
  }, {
    key: "addEmojis",
    value: function addEmojis(text, offset) {
      var _this3 = this;
      var references = [].concat(rich_text_toConsumableArray(getShortnameReferences(text.toString())), rich_text_toConsumableArray(getCodePointReferences(text.toString())));
      references.forEach(function (e) {
        _this3.addTemplateResult(e.begin + offset, e.end + offset, getEmojiMarkup(e, {
          'add_title_wrapper': true
        }));
      });
    }

    /**
     * Look for mentions included as XEP-0372 references and add templates for
     * rendering them.
     * @param { String } text
     * @param { number } local_offset - The index of the passed in text relative to
     *  the start of this RichText instance (which is not necessarily the same as the
     *  offset from the start of the original message stanza's body text).
     */
  }, {
    key: "addMentions",
    value: function addMentions(text, local_offset) {
      var _this$mentions,
        _this4 = this;
      var full_offset = local_offset + this.offset;
      (_this$mentions = this.mentions) === null || _this$mentions === void 0 ? void 0 : _this$mentions.forEach(function (ref) {
        var begin = Number(ref.begin) - full_offset;
        if (begin < 0 || begin >= full_offset + text.length) {
          return;
        }
        var end = Number(ref.end) - full_offset;
        var mention = text.slice(begin, end);
        if (mention === _this4.nick) {
          _this4.addTemplateResult(begin + local_offset, end + local_offset, tplMentionWithNick(rich_text_objectSpread(rich_text_objectSpread({}, ref), {}, {
            mention: mention
          })));
        } else {
          _this4.addTemplateResult(begin + local_offset, end + local_offset, tplMention(rich_text_objectSpread(rich_text_objectSpread({}, ref), {}, {
            mention: mention
          })));
        }
      });
    }

    /**
     * Look for XEP-0393 styling directives and add templates for rendering them.
     */
  }, {
    key: "addStyling",
    value: function addStyling() {
      var _this5 = this;
      if (!containsDirectives(this)) {
        return;
      }
      var references = [];
      var mention_ranges = this.mentions.map(function (m) {
        return Array.from({
          'length': Number(m.end)
        }, function (_, i) {
          return Number(m.begin) + i;
        });
      });
      var i = 0;
      while (i < this.length) {
        if (mention_ranges.filter(function (r) {
          return r.includes(i);
        }).length) {
          // eslint-disable-line no-loop-func
          // Don't treat potential directives if they fall within a
          // declared XEP-0372 reference
          i++;
          continue;
        }
        var _getDirectiveAndLengt = getDirectiveAndLength(this, i),
          d = _getDirectiveAndLengt.d,
          length = _getDirectiveAndLengt.length;
        if (d && length) {
          var is_quote = isQuoteDirective(d);
          var end = i + length;
          var slice_end = is_quote ? end : end - d.length;
          var slice_begin = d === '```' ? i + d.length + 1 : i + d.length;
          if (is_quote && this[slice_begin] === ' ') {
            // Trim leading space inside codeblock
            slice_begin += 1;
          }
          var offset = slice_begin;
          var text = this.slice(slice_begin, slice_end);
          references.push({
            'begin': i,
            'template': getDirectiveTemplate(d, text, offset, this.options),
            end: end
          });
          i = end;
        }
        i++;
      }
      references.forEach(function (ref) {
        return _this5.addTemplateResult(ref.begin, ref.end, ref.template);
      });
    }
  }, {
    key: "trimMeMessage",
    value: function trimMeMessage() {
      if (this.offset === 0) {
        // Subtract `/me ` from 3rd person messages
        if (this.isMeCommand()) {
          this.payload[0] = this.payload[0].substring(4);
        }
      }
    }

    /**
     * Look for plaintext (i.e. non-templated) sections of this RichText
     * instance and add references via the passed in function.
     * @param { Function } func
     */
  }, {
    key: "addAnnotations",
    value: function addAnnotations(func) {
      var payload = this.marshall();
      var idx = 0; // The text index of the element in the payload
      var _iterator2 = rich_text_createForOfIteratorHelper(payload),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var text = _step2.value;
          if (!text) {
            continue;
          } else if (rich_text_isString(text)) {
            func.call(this, text, idx);
            idx += text.length;
          } else {
            idx = text.end;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }

    /**
     * Parse the text and add template references for rendering the "rich" parts.
     **/
  }, {
    key: "addTemplates",
    value: function () {
      var _addTemplates = rich_text_asyncToGenerator( /*#__PURE__*/rich_text_regeneratorRuntime().mark(function _callee() {
        return rich_text_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.trigger('beforeMessageBodyTransformed', this, {
                'Synchronous': true
              });
            case 2:
              this.render_styling && this.addStyling();
              this.addAnnotations(this.addMentions);
              this.addAnnotations(this.addHyperlinks);
              this.addAnnotations(this.addMapURLs);
              _context.next = 8;
              return shared_api.emojis.initialize();
            case 8:
              this.addAnnotations(this.addEmojis);

              /**
               * Synchronous event which provides a hook for transforming a chat message's body text
               * after the default transformations have been applied.
               * @event _converse#afterMessageBodyTransformed
               * @param { RichText } text - A {@link RichText } instance. You
               *  can call {@link RichText#addTemplateResult} on it in order to
               *  add TemplateResult objects meant to render rich parts of the message.
               * @example _converse.api.listen.on('afterMessageBodyTransformed', (view, text) => { ... });
               */
              _context.next = 11;
              return shared_api.trigger('afterMessageBodyTransformed', this, {
                'Synchronous': true
              });
            case 11:
              this.payload = this.marshall();
              this.options.show_me_message && this.trimMeMessage();
              this.payload = this.payload.map(function (item) {
                return rich_text_isString(item) ? item : item.template;
              });
            case 14:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function addTemplates() {
        return _addTemplates.apply(this, arguments);
      }
      return addTemplates;
    }()
    /**
     * The "rich" markup parts of a chat message are represented by lit
     * TemplateResult objects.
     *
     * This method can be used to add new template results to this message's
     * text.
     *
     * @method RichText.addTemplateResult
     * @param { Number } begin - The starting index of the plain message text
     * which is being replaced with markup.
     * @param { Number } end - The ending index of the plain message text
     * which is being replaced with markup.
     * @param { Object } template - The lit TemplateResult instance
     */
  }, {
    key: "addTemplateResult",
    value: function addTemplateResult(begin, end, template) {
      this.references.push({
        begin: begin,
        end: end,
        template: template
      });
    }
  }, {
    key: "isMeCommand",
    value: function isMeCommand() {
      var text = this.toString();
      if (!text) {
        return false;
      }
      return text.startsWith('/me ');
    }

    /**
     * Take the annotations and return an array of text and TemplateResult
     * instances to be rendered to the DOM.
     * @method RichText#marshall
     */
  }, {
    key: "marshall",
    value: function marshall() {
      var list = [this.toString()];
      this.references.sort(function (a, b) {
        return b.begin - a.begin;
      }).forEach(function (ref) {
        var text = list.shift();
        list = [text.slice(0, ref.begin), ref, text.slice(ref.end)].concat(rich_text_toConsumableArray(list));
      });
      return list.reduce(function (acc, i) {
        return rich_text_isString(i) ? [].concat(rich_text_toConsumableArray(acc), [convertASCII2Emoji(collapseLineBreaks(i))]) : [].concat(rich_text_toConsumableArray(acc), [i]);
      }, []);
    }
  }]);
  return RichText;
}( /*#__PURE__*/rich_text_wrapNativeSuper(String));
;// CONCATENATED MODULE: ./src/shared/directives/rich-text.js
var directives_rich_text_templateObject, directives_rich_text_templateObject2;
function directives_rich_text_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) directives_rich_text_setPrototypeOf(subClass, superClass);
}
function directives_rich_text_setPrototypeOf(o, p) {
  directives_rich_text_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return directives_rich_text_setPrototypeOf(o, p);
}
function directives_rich_text_createSuper(Derived) {
  var hasNativeReflectConstruct = directives_rich_text_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = directives_rich_text_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = directives_rich_text_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return directives_rich_text_possibleConstructorReturn(this, result);
  };
}
function directives_rich_text_possibleConstructorReturn(self, call) {
  if (call && (directives_rich_text_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 directives_rich_text_assertThisInitialized(self);
}
function directives_rich_text_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function directives_rich_text_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 directives_rich_text_getPrototypeOf(o) {
  directives_rich_text_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return directives_rich_text_getPrototypeOf(o);
}
function directives_rich_text_typeof(obj) {
  "@babel/helpers - typeof";

  return directives_rich_text_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;
  }, directives_rich_text_typeof(obj);
}
function directives_rich_text_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function directives_rich_text_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  directives_rich_text_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" == directives_rich_text_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 directives_rich_text_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 directives_rich_text_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        directives_rich_text_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        directives_rich_text_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function directives_rich_text_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function directives_rich_text_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, directives_rich_text_toPropertyKey(descriptor.key), descriptor);
  }
}
function directives_rich_text_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) directives_rich_text_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) directives_rich_text_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function directives_rich_text_toPropertyKey(arg) {
  var key = directives_rich_text_toPrimitive(arg, "string");
  return directives_rich_text_typeof(key) === "symbol" ? key : String(key);
}
function directives_rich_text_toPrimitive(input, hint) {
  if (directives_rich_text_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (directives_rich_text_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}





var RichTextRenderer = /*#__PURE__*/function () {
  function RichTextRenderer(text, offset) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    directives_rich_text_classCallCheck(this, RichTextRenderer);
    this.offset = offset;
    this.options = options;
    this.text = text;
  }
  directives_rich_text_createClass(RichTextRenderer, [{
    key: "transform",
    value: function () {
      var _transform = directives_rich_text_asyncToGenerator( /*#__PURE__*/directives_rich_text_regeneratorRuntime().mark(function _callee() {
        var text;
        return directives_rich_text_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              text = new RichText(this.text, this.offset, this.options);
              _context.prev = 1;
              _context.next = 4;
              return text.addTemplates();
            case 4:
              _context.next = 9;
              break;
            case 6:
              _context.prev = 6;
              _context.t0 = _context["catch"](1);
              log.error(_context.t0);
            case 9:
              return _context.abrupt("return", text.payload);
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[1, 6]]);
      }));
      function transform() {
        return _transform.apply(this, arguments);
      }
      return transform;
    }()
  }, {
    key: "render",
    value: function render() {
      return (0,external_lit_namespaceObject.html)(directives_rich_text_templateObject || (directives_rich_text_templateObject = directives_rich_text_taggedTemplateLiteral(["", ""])), until_m(this.transform(), (0,external_lit_namespaceObject.html)(directives_rich_text_templateObject2 || (directives_rich_text_templateObject2 = directives_rich_text_taggedTemplateLiteral(["", ""])), this.text)));
    }
  }]);
  return RichTextRenderer;
}();
var RichTextDirective = /*#__PURE__*/function (_Directive) {
  directives_rich_text_inherits(RichTextDirective, _Directive);
  var _super = directives_rich_text_createSuper(RichTextDirective);
  function RichTextDirective() {
    directives_rich_text_classCallCheck(this, RichTextDirective);
    return _super.apply(this, arguments);
  }
  directives_rich_text_createClass(RichTextDirective, [{
    key: "render",
    value: function render(text, offset, options, callback) {
      // eslint-disable-line class-methods-use-this
      var renderer = new RichTextRenderer(text, offset, options);
      var result = renderer.render();
      callback === null || callback === void 0 ? void 0 : callback();
      return result;
    }
  }]);
  return RichTextDirective;
}(directive_i);
var renderRichText = directive_e(RichTextDirective);
/* harmony default export */ const rich_text = (renderRichText);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/message-body.scss
var message_body = __webpack_require__(4311);
;// CONCATENATED MODULE: ./src/shared/chat/styles/message-body.scss

      
      
      
      
      
      
      
      
      

var message_body_options = {};

message_body_options.styleTagTransform = (styleTagTransform_default());
message_body_options.setAttributes = (setAttributesWithoutAttributes_default());

      message_body_options.insert = insertBySelector_default().bind(null, "head");
    
message_body_options.domAPI = (styleDomAPI_default());
message_body_options.insertStyleElement = (insertStyleElement_default());

var message_body_update = injectStylesIntoStyleTag_default()(message_body/* default */.Z, message_body_options);




       /* harmony default export */ const styles_message_body = (message_body/* default */.Z && message_body/* default */.Z.locals ? message_body/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/message-body.js
function message_body_typeof(obj) {
  "@babel/helpers - typeof";

  return message_body_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;
  }, message_body_typeof(obj);
}
function message_body_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_body_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, message_body_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_body_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_body_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_body_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_body_toPropertyKey(arg) {
  var key = message_body_toPrimitive(arg, "string");
  return message_body_typeof(key) === "symbol" ? key : String(key);
}
function message_body_toPrimitive(input, hint) {
  if (message_body_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_body_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_body_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) message_body_setPrototypeOf(subClass, superClass);
}
function message_body_setPrototypeOf(o, p) {
  message_body_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_body_setPrototypeOf(o, p);
}
function message_body_createSuper(Derived) {
  var hasNativeReflectConstruct = message_body_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_body_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_body_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_body_possibleConstructorReturn(this, result);
  };
}
function message_body_possibleConstructorReturn(self, call) {
  if (call && (message_body_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 message_body_assertThisInitialized(self);
}
function message_body_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_body_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 message_body_getPrototypeOf(o) {
  message_body_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_body_getPrototypeOf(o);
}







var MessageBody = /*#__PURE__*/function (_CustomElement) {
  message_body_inherits(MessageBody, _CustomElement);
  var _super = message_body_createSuper(MessageBody);
  function MessageBody() {
    message_body_classCallCheck(this, MessageBody);
    return _super.apply(this, arguments);
  }
  message_body_createClass(MessageBody, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      var settings = getAppSettings();
      this.listenTo(settings, 'change:allowed_audio_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:allowed_image_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:allowed_video_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:render_media', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "onImgClick",
    value: function onImgClick(ev) {
      // eslint-disable-line class-methods-use-this
      ev.preventDefault();
      shared_api.modal.show('converse-image-modal', {
        'src': ev.target.src
      }, ev);
    }
  }, {
    key: "onImgLoad",
    value: function onImgLoad() {
      this.dispatchEvent(new CustomEvent('imageLoaded', {
        detail: this,
        'bubbles': true
      }));
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var callback = function callback() {
        var _this2$model$collecti;
        return (_this2$model$collecti = _this2.model.collection) === null || _this2$model$collecti === void 0 ? void 0 : _this2$model$collecti.trigger('rendered', _this2.model);
      };
      var offset = 0;
      var options = {
        'media_urls': this.model.get('media_urls'),
        'mentions': this.model.get('references'),
        'nick': this.model.collection.chatbox.get('nick'),
        'onImgClick': function onImgClick(ev) {
          return _this2.onImgClick(ev);
        },
        'onImgLoad': function onImgLoad() {
          return _this2.onImgLoad();
        },
        'render_styling': !this.model.get('is_unstyled') && shared_api.settings.get('allow_message_styling'),
        'show_me_message': true
      };
      if (this.hide_url_previews === "false") {
        options.embed_audio = true;
        options.embed_videos = true;
        options.show_images = true;
      } else if (this.hide_url_previews === "true") {
        options.embed_audio = false;
        options.embed_videos = false;
        options.show_images = false;
      }
      return rich_text(this.text, offset, options, callback);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        // We make this a string instead of a boolean, since we want to
        // distinguish between true, false and undefined states
        hide_url_previews: {
          type: String
        },
        is_me_message: {
          type: Boolean
        },
        model: {
          type: Object
        },
        text: {
          type: String
        }
      };
    }
  }]);
  return MessageBody;
}(CustomElement);

shared_api.elements.define('converse-chat-message-body', MessageBody);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/components/styles/icon.scss
var icon = __webpack_require__(2259);
;// CONCATENATED MODULE: ./src/shared/components/styles/icon.scss

      
      
      
      
      
      
      
      
      

var icon_options = {};

icon_options.styleTagTransform = (styleTagTransform_default());
icon_options.setAttributes = (setAttributesWithoutAttributes_default());

      icon_options.insert = insertBySelector_default().bind(null, "head");
    
icon_options.domAPI = (styleDomAPI_default());
icon_options.insertStyleElement = (insertStyleElement_default());

var icon_update = injectStylesIntoStyleTag_default()(icon/* default */.Z, icon_options);




       /* harmony default export */ const styles_icon = (icon/* default */.Z && icon/* default */.Z.locals ? icon/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/components/icons.js
function icons_typeof(obj) {
  "@babel/helpers - typeof";

  return icons_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;
  }, icons_typeof(obj);
}
var icons_templateObject;
function icons_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function icons_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function icons_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, icons_toPropertyKey(descriptor.key), descriptor);
  }
}
function icons_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) icons_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) icons_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function icons_toPropertyKey(arg) {
  var key = icons_toPrimitive(arg, "string");
  return icons_typeof(key) === "symbol" ? key : String(key);
}
function icons_toPrimitive(input, hint) {
  if (icons_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (icons_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function icons_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) icons_setPrototypeOf(subClass, superClass);
}
function icons_setPrototypeOf(o, p) {
  icons_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return icons_setPrototypeOf(o, p);
}
function icons_createSuper(Derived) {
  var hasNativeReflectConstruct = icons_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = icons_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = icons_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return icons_possibleConstructorReturn(this, result);
  };
}
function icons_possibleConstructorReturn(self, call) {
  if (call && (icons_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 icons_assertThisInitialized(self);
}
function icons_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function icons_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 icons_getPrototypeOf(o) {
  icons_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return icons_getPrototypeOf(o);
}
/**
 * @copyright Alfredo Medrano Sánchez and the Converse.js contributors
 * @description
 *  Component inspired by the one from fa-icons
 *  https://github.com/obsidiansoft-io/fa-icons/blob/master/LICENSE
 * @license Mozilla Public License (MPLv2)
 */





var ConverseIcon = /*#__PURE__*/function (_CustomElement) {
  icons_inherits(ConverseIcon, _CustomElement);
  var _super = icons_createSuper(ConverseIcon);
  function ConverseIcon() {
    var _this;
    icons_classCallCheck(this, ConverseIcon);
    _this = _super.call(this);
    _this.class_name = "";
    _this.style = "";
    _this.size = "";
    _this.color = "";
    return _this;
  }
  icons_createClass(ConverseIcon, [{
    key: "getSource",
    value: function getSource() {
      return "#icon-".concat(this.class_name.trim().split(" ")[1].replace("fa-", ""));
    }
  }, {
    key: "getStyles",
    value: function getStyles() {
      var _this$color$match;
      var cssprop = (_this$color$match = this.color.match(/var\((--.*)\)/)) === null || _this$color$match === void 0 ? void 0 : _this$color$match[1];
      var color = cssprop ? getComputedStyle(this).getPropertyValue(cssprop) : this.color;
      return "\n            ".concat(this.size ? "width: ".concat(this.size, ";") : '', "\n            ").concat(this.size ? "height: ".concat(this.size, ";") : '', "\n            ").concat(color ? "fill: ".concat(color, ";") : '', "\n            ").concat(this.style, "\n        ");
    }
  }, {
    key: "render",
    value: function render() {
      return (0,external_lit_namespaceObject.html)(icons_templateObject || (icons_templateObject = icons_taggedTemplateLiteral(["<svg .style=\"", "\"> <use href=\"", "\"> </use> </svg>"])), this.getStyles(), this.getSource());
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        color: String,
        class_name: {
          attribute: "class"
        },
        style: String,
        size: String
      };
    }
  }]);
  return ConverseIcon;
}(CustomElement);
shared_api.elements.define("converse-icon", ConverseIcon);
;// CONCATENATED MODULE: ./src/shared/dom-navigator.js
function dom_navigator_typeof(obj) {
  "@babel/helpers - typeof";

  return dom_navigator_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;
  }, dom_navigator_typeof(obj);
}
function dom_navigator_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function dom_navigator_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, dom_navigator_toPropertyKey(descriptor.key), descriptor);
  }
}
function dom_navigator_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) dom_navigator_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) dom_navigator_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function dom_navigator_toPropertyKey(arg) {
  var key = dom_navigator_toPrimitive(arg, "string");
  return dom_navigator_typeof(key) === "symbol" ? key : String(key);
}
function dom_navigator_toPrimitive(input, hint) {
  if (dom_navigator_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (dom_navigator_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
/**
 * @module dom-navigator
 * @description A class for navigating the DOM with the keyboard
 * This module started as a fork of Rubens Mariuzzo's dom-navigator.
 * @copyright Rubens Mariuzzo, JC Brand
 */


var keycodes = public_converse.keycodes;

/**
 * Indicates if a given element is fully visible in the viewport.
 * @param { Element } el The element to check.
 * @return { Boolean } True if the given element is fully visible in the viewport, otherwise false.
 */
function inViewport(el) {
  var rect = el.getBoundingClientRect();
  return rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth;
}

/**
 * Return the absolute offset top of an element.
 * @param el { Element } The element.
 * @return { Number } The offset top.
 */
function absoluteOffsetTop(el) {
  var offsetTop = 0;
  do {
    if (!isNaN(el.offsetTop)) {
      offsetTop += el.offsetTop;
    }
  } while (el = el.offsetParent);
  return offsetTop;
}

/**
 * Return the absolute offset left of an element.
 * @param el { Element } The element.
 * @return { Number } The offset left.
 */
function absoluteOffsetLeft(el) {
  var offsetLeft = 0;
  do {
    if (!isNaN(el.offsetLeft)) {
      offsetLeft += el.offsetLeft;
    }
  } while (el = el.offsetParent);
  return offsetLeft;
}

/**
 * Adds the ability to navigate the DOM with the arrow keys
 * @class DOMNavigator
 */
var DOMNavigator = /*#__PURE__*/function () {
  /**
   * Create a new DOM Navigator.
   * @param { Element } container The container of the element to navigate.
   * @param { Object } options The options to configure the DOM navigator.
   * @param { Function } options.getSelector
   * @param { Number } [options.down] - The keycode for navigating down
   * @param { Number } [options.left] - The keycode for navigating left
   * @param { Number } [options.right] - The keycode for navigating right
   * @param { Number } [options.up] - The keycode for navigating up
   * @param { String } [options.selected] - The class that should be added to the currently selected DOM element.
   * @param { String } [options.jump_to_picked] - A selector, which if
   * matched by the next element being navigated to, based on the direction
   * given by `jump_to_picked_direction`, will cause navigation
   * to jump to the element that matches the `jump_to_picked_selector`.
   * For example, this is useful when navigating to tabs. You want to
   * immediately navigate to the currently active tab instead of just
   * navigating to the first tab.
   * @param { String } [options.jump_to_picked_selector=picked] - The selector
   * indicating the currently picked element to jump to.
   * @param { String } [options.jump_to_picked_direction] - The direction for
   * which jumping to the picked element should be enabled.
   * @param { Function } [options.onSelected] - The callback function which
   * should be called when en element gets selected.
   * @constructor
   */
  function DOMNavigator(container, options) {
    dom_navigator_classCallCheck(this, DOMNavigator);
    this.doc = window.document;
    this.container = container;
    this.scroll_container = options.scroll_container || container;
    this.options = Object.assign({}, DOMNavigator.DEFAULTS, options);
    this.init();
  }

  /**
   * Initialize the navigator.
   */
  dom_navigator_createClass(DOMNavigator, [{
    key: "init",
    value: function init() {
      var _this = this;
      this.selected = null;
      this.keydownHandler = null;
      this.elements = {};
      // Create hotkeys map.
      this.keys = {};
      this.options.down.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.down;
      });
      this.options.end.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.end;
      });
      this.options.home.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.home;
      });
      this.options.left.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.left;
      });
      this.options.right.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.right;
      });
      this.options.up.forEach(function (key) {
        return _this.keys[key] = DOMNavigator.DIRECTION.up;
      });
    }

    /**
     * Enable this navigator.
     */
  }, {
    key: "enable",
    value: function enable() {
      var _this2 = this;
      this.getElements();
      this.keydownHandler = function (event) {
        return _this2.handleKeydown(event);
      };
      this.doc.addEventListener('keydown', this.keydownHandler);
      this.enabled = true;
    }

    /**
     * Disable this navigator.
     */
  }, {
    key: "disable",
    value: function disable() {
      if (this.keydownHandler) {
        this.doc.removeEventListener('keydown', this.keydownHandler);
      }
      this.unselect();
      this.elements = {};
      this.enabled = false;
    }

    /**
     * Destroy this navigator removing any event registered and any other data.
     */
  }, {
    key: "destroy",
    value: function destroy() {
      this.disable();
      if (this.container.domNavigator) {
        delete this.container.domNavigator;
      }
    }

    /**
     * @param {'down'|'right'|'left'|'up'} direction
     * @returns { HTMLElement }
     */
  }, {
    key: "getNextElement",
    value: function getNextElement(direction) {
      var el;
      if (direction === DOMNavigator.DIRECTION.home) {
        el = this.getElements(direction)[0];
      } else if (direction === DOMNavigator.DIRECTION.end) {
        el = Array.from(this.getElements(direction)).pop();
      } else if (this.selected) {
        if (direction === DOMNavigator.DIRECTION.right) {
          var els = this.getElements(direction);
          el = els.slice(els.indexOf(this.selected))[1];
        } else if (direction == DOMNavigator.DIRECTION.left) {
          var _els = this.getElements(direction);
          el = _els.slice(0, _els.indexOf(this.selected)).pop() || this.selected;
        } else if (direction == DOMNavigator.DIRECTION.down) {
          var left = this.selected.offsetLeft;
          var top = this.selected.offsetTop + this.selected.offsetHeight;
          var _els2 = this.elementsAfter(0, top);
          var getDistance = function getDistance(el) {
            return Math.abs(el.offsetLeft - left) + Math.abs(el.offsetTop - top);
          };
          el = DOMNavigator.getClosestElement(_els2, getDistance);
        } else if (direction == DOMNavigator.DIRECTION.up) {
          var _left = this.selected.offsetLeft;
          var _top = this.selected.offsetTop - 1;
          var _els3 = this.elementsBefore(Infinity, _top);
          var _getDistance = function _getDistance(el) {
            return Math.abs(_left - el.offsetLeft) + Math.abs(_top - el.offsetTop);
          };
          el = DOMNavigator.getClosestElement(_els3, _getDistance);
        } else {
          throw new Error("getNextElement: invalid direction value");
        }
      } else {
        if (direction === DOMNavigator.DIRECTION.right || direction === DOMNavigator.DIRECTION.down) {
          // If nothing is selected, we pretend that the first element is
          // selected, so we return the next.
          el = this.getElements(direction)[1];
        } else {
          el = this.getElements(direction)[0];
        }
      }
      if (this.options.jump_to_picked && el && el.matches(this.options.jump_to_picked) && direction === this.options.jump_to_picked_direction) {
        el = this.container.querySelector(this.options.jump_to_picked_selector) || el;
      }
      return el;
    }

    /**
     * Select the given element.
     * @param { Element } el The DOM element to select.
     * @param { string } [direction] The direction.
     */
  }, {
    key: "select",
    value: function select(el, direction) {
      if (!el || el === this.selected) {
        return;
      }
      this.unselect();
      direction && this.scrollTo(el, direction);
      if (el.matches('input')) {
        el.focus();
      } else {
        utils_html.addClass(this.options.selected, el);
      }
      this.selected = el;
      this.options.onSelected && this.options.onSelected(el);
    }

    /**
     * Remove the current selection
     */
  }, {
    key: "unselect",
    value: function unselect() {
      if (this.selected) {
        utils_html.removeClass(this.options.selected, this.selected);
        delete this.selected;
      }
    }

    /**
     * Scroll the container to an element.
     * @param { HTMLElement } el The destination element.
     * @param { String } direction The direction of the current navigation.
     * @return void.
     */
  }, {
    key: "scrollTo",
    value: function scrollTo(el, direction) {
      if (!this.inScrollContainerViewport(el)) {
        var container = this.scroll_container;
        if (!container.contains(el)) {
          return;
        }
        switch (direction) {
          case DOMNavigator.DIRECTION.left:
            container.scrollLeft = el.offsetLeft - container.offsetLeft;
            container.scrollTop = el.offsetTop - container.offsetTop;
            break;
          case DOMNavigator.DIRECTION.up:
            container.scrollTop = el.offsetTop - container.offsetTop;
            break;
          case DOMNavigator.DIRECTION.right:
            container.scrollLeft = el.offsetLeft - container.offsetLeft - (container.offsetWidth - el.offsetWidth);
            container.scrollTop = el.offsetTop - container.offsetTop - (container.offsetHeight - el.offsetHeight);
            break;
          case DOMNavigator.DIRECTION.down:
            container.scrollTop = el.offsetTop - container.offsetTop - (container.offsetHeight - el.offsetHeight);
            break;
        }
      } else if (!inViewport(el)) {
        switch (direction) {
          case DOMNavigator.DIRECTION.left:
            document.body.scrollLeft = absoluteOffsetLeft(el) - document.body.offsetLeft;
            break;
          case DOMNavigator.DIRECTION.up:
            document.body.scrollTop = absoluteOffsetTop(el) - document.body.offsetTop;
            break;
          case DOMNavigator.DIRECTION.right:
            document.body.scrollLeft = absoluteOffsetLeft(el) - document.body.offsetLeft - (document.documentElement.clientWidth - el.offsetWidth);
            break;
          case DOMNavigator.DIRECTION.down:
            document.body.scrollTop = absoluteOffsetTop(el) - document.body.offsetTop - (document.documentElement.clientHeight - el.offsetHeight);
            break;
        }
      }
    }

    /**
     * Indicate if an element is in the container viewport.
     * @param { HTMLElement } el The element to check.
     * @return { Boolean } true if the given element is in the container viewport, otherwise false.
     */
  }, {
    key: "inScrollContainerViewport",
    value: function inScrollContainerViewport(el) {
      var container = this.scroll_container;
      // Check on left side.
      if (el.offsetLeft - container.scrollLeft < container.offsetLeft) {
        return false;
      }
      // Check on top side.
      if (el.offsetTop - container.scrollTop < container.offsetTop) {
        return false;
      }
      // Check on right side.
      if (el.offsetLeft + el.offsetWidth - container.scrollLeft > container.offsetLeft + container.offsetWidth) {
        return false;
      }
      // Check on down side.
      if (el.offsetTop + el.offsetHeight - container.scrollTop > container.offsetTop + container.offsetHeight) {
        return false;
      }
      return true;
    }

    /**
     * Find and store the navigable elements
     */
  }, {
    key: "getElements",
    value: function getElements(direction) {
      var selector = this.options.getSelector ? this.options.getSelector(direction) : this.options.selector;
      if (!this.elements[selector]) {
        this.elements[selector] = Array.from(this.container.querySelectorAll(selector));
      }
      return this.elements[selector];
    }

    /**
     * Return an array of navigable elements after an offset.
     * @param { number } left The left offset.
     * @param { number } top The top offset.
     * @return { Array } An array of elements.
     */
  }, {
    key: "elementsAfter",
    value: function elementsAfter(left, top) {
      return this.getElements(DOMNavigator.DIRECTION.down).filter(function (el) {
        return el.offsetLeft >= left && el.offsetTop >= top;
      });
    }

    /**
     * Return an array of navigable elements before an offset.
     * @param { number } left The left offset.
     * @param { number } top The top offset.
     * @return { Array } An array of elements.
     */
  }, {
    key: "elementsBefore",
    value: function elementsBefore(left, top) {
      return this.getElements(DOMNavigator.DIRECTION.up).filter(function (el) {
        return el.offsetLeft <= left && el.offsetTop <= top;
      });
    }

    /**
     * Handle the key down event.
     * @param { Event } event The event object.
     */
  }, {
    key: "handleKeydown",
    value: function handleKeydown(ev) {
      var keys = keycodes;
      var direction = ev.shiftKey ? this.keys["".concat(keys.SHIFT, "+").concat(ev.which)] : this.keys[ev.which];
      if (direction) {
        ev.preventDefault();
        ev.stopPropagation();
        var next = this.getNextElement(direction, ev);
        this.select(next, direction);
      }
    }
  }], [{
    key: "DIRECTION",
    get:
    /**
     * Directions.
     * @returns {{left: string, up: string, right: string, down: string}}
     * @constructor
     */
    function get() {
      return {
        down: 'down',
        end: 'end',
        home: 'home',
        left: 'left',
        right: 'right',
        up: 'up'
      };
    }

    /**
     * The default options for the DOM navigator.
     * @returns {{
     *     down: number,
     *     getSelector: null,
     *     jump_to_picked: null,
     *     jump_to_picked_direction: null,
     *     jump_to_picked_selector: string,
     *     left: number,
     *     onSelected: null,
     *     right: number,
     *     selected: string,
     *     up: number
     * }}
     */
  }, {
    key: "DEFAULTS",
    get: function get() {
      return {
        home: ["".concat(keycodes.SHIFT, "+").concat(keycodes.UP_ARROW)],
        end: ["".concat(keycodes.SHIFT, "+").concat(keycodes.DOWN_ARROW)],
        up: [keycodes.UP_ARROW],
        down: [keycodes.DOWN_ARROW],
        left: [keycodes.LEFT_ARROW, "".concat(keycodes.SHIFT, "+").concat(keycodes.TAB)],
        right: [keycodes.RIGHT_ARROW, keycodes.TAB],
        getSelector: null,
        jump_to_picked: null,
        jump_to_picked_direction: null,
        jump_to_picked_selector: 'picked',
        onSelected: null,
        selected: 'selected',
        selector: 'li'
      };
    }
  }, {
    key: "getClosestElement",
    value: function getClosestElement(els, getDistance) {
      var next = els.reduce(function (prev, curr) {
        var current_distance = getDistance(curr);
        if (current_distance < prev.distance) {
          return {
            distance: current_distance,
            element: curr
          };
        }
        return prev;
      }, {
        distance: Infinity
      });
      return next.element;
    }
  }]);
  return DOMNavigator;
}();
/* harmony default export */ const dom_navigator = (DOMNavigator);
;// CONCATENATED MODULE: ./src/shared/components/dropdownbase.js
function dropdownbase_typeof(obj) {
  "@babel/helpers - typeof";

  return dropdownbase_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;
  }, dropdownbase_typeof(obj);
}
function dropdownbase_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function dropdownbase_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, dropdownbase_toPropertyKey(descriptor.key), descriptor);
  }
}
function dropdownbase_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) dropdownbase_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) dropdownbase_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function dropdownbase_toPropertyKey(arg) {
  var key = dropdownbase_toPrimitive(arg, "string");
  return dropdownbase_typeof(key) === "symbol" ? key : String(key);
}
function dropdownbase_toPrimitive(input, hint) {
  if (dropdownbase_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (dropdownbase_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function dropdownbase_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    dropdownbase_get = Reflect.get.bind();
  } else {
    dropdownbase_get = function _get(target, property, receiver) {
      var base = dropdownbase_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return dropdownbase_get.apply(this, arguments);
}
function dropdownbase_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = dropdownbase_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function dropdownbase_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) dropdownbase_setPrototypeOf(subClass, superClass);
}
function dropdownbase_setPrototypeOf(o, p) {
  dropdownbase_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return dropdownbase_setPrototypeOf(o, p);
}
function dropdownbase_createSuper(Derived) {
  var hasNativeReflectConstruct = dropdownbase_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = dropdownbase_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = dropdownbase_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return dropdownbase_possibleConstructorReturn(this, result);
  };
}
function dropdownbase_possibleConstructorReturn(self, call) {
  if (call && (dropdownbase_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 dropdownbase_assertThisInitialized(self);
}
function dropdownbase_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function dropdownbase_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 dropdownbase_getPrototypeOf(o) {
  dropdownbase_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return dropdownbase_getPrototypeOf(o);
}


var dropdownbase_u = public_converse.env.utils;
var DropdownBase = /*#__PURE__*/function (_CustomElement) {
  dropdownbase_inherits(DropdownBase, _CustomElement);
  var _super = dropdownbase_createSuper(DropdownBase);
  function DropdownBase() {
    dropdownbase_classCallCheck(this, DropdownBase);
    return _super.apply(this, arguments);
  }
  dropdownbase_createClass(DropdownBase, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      dropdownbase_get(dropdownbase_getPrototypeOf(DropdownBase.prototype), "connectedCallback", this).call(this);
      this.registerEvents();
    }
  }, {
    key: "registerEvents",
    value: function registerEvents() {
      var _this = this;
      this.clickOutside = function (ev) {
        return _this._clickOutside(ev);
      };
      document.addEventListener('click', this.clickOutside);
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      var _this2 = this;
      dropdownbase_get(dropdownbase_getPrototypeOf(DropdownBase.prototype), "firstUpdated", this).call(this);
      this.menu = this.querySelector('.dropdown-menu');
      this.button = this.querySelector('button');
      this.addEventListener('click', function (ev) {
        return _this2.toggleMenu(ev);
      });
      this.addEventListener('keyup', function (ev) {
        return _this2.handleKeyUp(ev);
      });
    }
  }, {
    key: "_clickOutside",
    value: function _clickOutside(ev) {
      if (!this.contains(ev.composedPath()[0])) {
        this.hideMenu(ev);
      }
    }
  }, {
    key: "hideMenu",
    value: function hideMenu() {
      var _this$button, _this$button2;
      dropdownbase_u.removeClass('show', this.menu);
      (_this$button = this.button) === null || _this$button === void 0 ? void 0 : _this$button.setAttribute('aria-expanded', false);
      (_this$button2 = this.button) === null || _this$button2 === void 0 ? void 0 : _this$button2.blur();
    }
  }, {
    key: "showMenu",
    value: function showMenu() {
      dropdownbase_u.addClass('show', this.menu);
      this.button.setAttribute('aria-expanded', true);
    }
  }, {
    key: "toggleMenu",
    value: function toggleMenu(ev) {
      ev.preventDefault();
      if (dropdownbase_u.hasClass('show', this.menu)) {
        this.hideMenu();
      } else {
        this.showMenu();
      }
    }
  }, {
    key: "handleKeyUp",
    value: function handleKeyUp(ev) {
      if (ev.keyCode === public_converse.keycodes.ESCAPE) {
        this.hideMenu();
      }
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      document.removeEventListener('click', this.clickOutside);
      dropdownbase_get(dropdownbase_getPrototypeOf(DropdownBase.prototype), "disconnectedCallback", this).call(this);
    }
  }]);
  return DropdownBase;
}(CustomElement);

// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/components/styles/dropdown.scss
var dropdown = __webpack_require__(7829);
;// CONCATENATED MODULE: ./src/shared/components/styles/dropdown.scss

      
      
      
      
      
      
      
      
      

var dropdown_options = {};

dropdown_options.styleTagTransform = (styleTagTransform_default());
dropdown_options.setAttributes = (setAttributesWithoutAttributes_default());

      dropdown_options.insert = insertBySelector_default().bind(null, "head");
    
dropdown_options.domAPI = (styleDomAPI_default());
dropdown_options.insertStyleElement = (insertStyleElement_default());

var dropdown_update = injectStylesIntoStyleTag_default()(dropdown/* default */.Z, dropdown_options);




       /* harmony default export */ const styles_dropdown = (dropdown/* default */.Z && dropdown/* default */.Z.locals ? dropdown/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/components/dropdown.js
function dropdown_typeof(obj) {
  "@babel/helpers - typeof";

  return dropdown_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;
  }, dropdown_typeof(obj);
}
var dropdown_templateObject;
function dropdown_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function dropdown_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function dropdown_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, dropdown_toPropertyKey(descriptor.key), descriptor);
  }
}
function dropdown_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) dropdown_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) dropdown_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function dropdown_toPropertyKey(arg) {
  var key = dropdown_toPrimitive(arg, "string");
  return dropdown_typeof(key) === "symbol" ? key : String(key);
}
function dropdown_toPrimitive(input, hint) {
  if (dropdown_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (dropdown_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function dropdown_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    dropdown_get = Reflect.get.bind();
  } else {
    dropdown_get = function _get(target, property, receiver) {
      var base = dropdown_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return dropdown_get.apply(this, arguments);
}
function dropdown_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = dropdown_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function dropdown_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) dropdown_setPrototypeOf(subClass, superClass);
}
function dropdown_setPrototypeOf(o, p) {
  dropdown_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return dropdown_setPrototypeOf(o, p);
}
function dropdown_createSuper(Derived) {
  var hasNativeReflectConstruct = dropdown_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = dropdown_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = dropdown_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return dropdown_possibleConstructorReturn(this, result);
  };
}
function dropdown_possibleConstructorReturn(self, call) {
  if (call && (dropdown_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 dropdown_assertThisInitialized(self);
}
function dropdown_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function dropdown_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 dropdown_getPrototypeOf(o) {
  dropdown_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return dropdown_getPrototypeOf(o);
}








var Dropdown = /*#__PURE__*/function (_DropdownBase) {
  dropdown_inherits(Dropdown, _DropdownBase);
  var _super = dropdown_createSuper(Dropdown);
  function Dropdown() {
    var _this;
    dropdown_classCallCheck(this, Dropdown);
    _this = _super.call(this);
    _this.icon_classes = 'fa fa-bars';
    return _this;
  }
  dropdown_createClass(Dropdown, [{
    key: "render",
    value: function render() {
      return (0,external_lit_namespaceObject.html)(dropdown_templateObject || (dropdown_templateObject = dropdown_taggedTemplateLiteral(["\n            <button type=\"button\" class=\"btn btn--transparent btn--standalone\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n                <converse-icon size=\"1em\" class=\"", "\">\n            </button>\n            <div class=\"dropdown-menu\">\n                ", "\n            </div>\n        "])), this.icon_classes, this.items.map(function (b) {
        return until_m(b, '');
      }));
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      dropdown_get(dropdown_getPrototypeOf(Dropdown.prototype), "firstUpdated", this).call(this);
      this.initArrowNavigation();
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this2 = this;
      dropdown_get(dropdown_getPrototypeOf(Dropdown.prototype), "connectedCallback", this).call(this);
      this.hideOnEscape = function (ev) {
        return ev.keyCode === KEYCODES.ESCAPE && _this2.hideMenu();
      };
      document.addEventListener('keydown', this.hideOnEscape);
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      document.removeEventListener('keydown', this.hideOnEscape);
      dropdown_get(dropdown_getPrototypeOf(Dropdown.prototype), "disconnectedCallback", this).call(this);
    }
  }, {
    key: "hideMenu",
    value: function hideMenu() {
      var _this$navigator;
      dropdown_get(dropdown_getPrototypeOf(Dropdown.prototype), "hideMenu", this).call(this);
      (_this$navigator = this.navigator) === null || _this$navigator === void 0 ? void 0 : _this$navigator.disable();
    }
  }, {
    key: "initArrowNavigation",
    value: function initArrowNavigation() {
      if (!this.navigator) {
        var options = {
          'selector': '.dropdown-item',
          'onSelected': function onSelected(el) {
            return el.focus();
          }
        };
        this.navigator = new dom_navigator(this.menu, options);
      }
    }
  }, {
    key: "enableArrowNavigation",
    value: function enableArrowNavigation(ev) {
      if (ev) {
        ev.preventDefault();
        ev.stopPropagation();
      }
      this.navigator.enable();
      this.navigator.select(this.menu.firstElementChild);
    }
  }, {
    key: "handleKeyUp",
    value: function handleKeyUp(ev) {
      dropdown_get(dropdown_getPrototypeOf(Dropdown.prototype), "handleKeyUp", this).call(this, ev);
      if (ev.keyCode === KEYCODES.DOWN_ARROW && !this.navigator.enabled) {
        this.enableArrowNavigation(ev);
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'icon_classes': {
          type: String
        },
        'items': {
          type: Array
        }
      };
    }
  }]);
  return Dropdown;
}(DropdownBase);

shared_api.elements.define('converse-dropdown', Dropdown);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/components/styles/message-versions.scss
var message_versions = __webpack_require__(5605);
;// CONCATENATED MODULE: ./src/shared/components/styles/message-versions.scss

      
      
      
      
      
      
      
      
      

var message_versions_options = {};

message_versions_options.styleTagTransform = (styleTagTransform_default());
message_versions_options.setAttributes = (setAttributesWithoutAttributes_default());

      message_versions_options.insert = insertBySelector_default().bind(null, "head");
    
message_versions_options.domAPI = (styleDomAPI_default());
message_versions_options.insertStyleElement = (insertStyleElement_default());

var message_versions_update = injectStylesIntoStyleTag_default()(message_versions/* default */.Z, message_versions_options);




       /* harmony default export */ const styles_message_versions = (message_versions/* default */.Z && message_versions/* default */.Z.locals ? message_versions/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/components/message-versions.js
function message_versions_typeof(obj) {
  "@babel/helpers - typeof";

  return message_versions_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;
  }, message_versions_typeof(obj);
}
var message_versions_templateObject, message_versions_templateObject2, message_versions_templateObject3, message_versions_templateObject4;
function message_versions_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_versions_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, message_versions_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_versions_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_versions_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_versions_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_versions_toPropertyKey(arg) {
  var key = message_versions_toPrimitive(arg, "string");
  return message_versions_typeof(key) === "symbol" ? key : String(key);
}
function message_versions_toPrimitive(input, hint) {
  if (message_versions_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_versions_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_versions_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) message_versions_setPrototypeOf(subClass, superClass);
}
function message_versions_setPrototypeOf(o, p) {
  message_versions_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_versions_setPrototypeOf(o, p);
}
function message_versions_createSuper(Derived) {
  var hasNativeReflectConstruct = message_versions_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_versions_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_versions_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_versions_possibleConstructorReturn(this, result);
  };
}
function message_versions_possibleConstructorReturn(self, call) {
  if (call && (message_versions_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 message_versions_assertThisInitialized(self);
}
function message_versions_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_versions_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 message_versions_getPrototypeOf(o) {
  message_versions_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_versions_getPrototypeOf(o);
}
function message_versions_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





var message_versions_dayjs = public_converse.env.dayjs;
var tplOlderVersion = function tplOlderVersion(k, older_versions) {
  return (0,external_lit_namespaceObject.html)(message_versions_templateObject || (message_versions_templateObject = message_versions_taggedTemplateLiteral(["<p class=\"older-msg\"><time>", "</time>: ", "</p>"])), message_versions_dayjs(k).format('MMM D, YYYY, HH:mm:ss'), older_versions[k]);
};
var MessageVersions = /*#__PURE__*/function (_CustomElement) {
  message_versions_inherits(MessageVersions, _CustomElement);
  var _super = message_versions_createSuper(MessageVersions);
  function MessageVersions() {
    var _this;
    message_versions_classCallCheck(this, MessageVersions);
    _this = _super.call(this);
    _this.model = null;
    return _this;
  }
  message_versions_createClass(MessageVersions, [{
    key: "render",
    value: function render() {
      var older_versions = this.model.get('older_versions');
      var keys = Object.keys(older_versions);
      return (0,external_lit_namespaceObject.html)(message_versions_templateObject2 || (message_versions_templateObject2 = message_versions_taggedTemplateLiteral(["\n            ", "\n            <hr/>\n            <h4>", "</h4>\n            <p><time>", "</time>: ", "</p>"])), keys.length ? (0,external_lit_namespaceObject.html)(message_versions_templateObject3 || (message_versions_templateObject3 = message_versions_taggedTemplateLiteral(["<h4>", "</h4> ", ""])), __('Older versions'), keys.map(function (k) {
        return tplOlderVersion(k, older_versions);
      })) : (0,external_lit_namespaceObject.html)(message_versions_templateObject4 || (message_versions_templateObject4 = message_versions_taggedTemplateLiteral(["<h4>", "</h4>"])), __('No older versions found')), __('Current version'), message_versions_dayjs(this.model.get('time')).format('MMM D, YYYY, HH:mm:ss'), this.model.getMessageText());
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        model: {
          type: Object
        }
      };
    }
  }]);
  return MessageVersions;
}(CustomElement);
shared_api.elements.define('converse-message-versions', MessageVersions);
;// CONCATENATED MODULE: ./src/shared/modals/message-versions.js
function modals_message_versions_typeof(obj) {
  "@babel/helpers - typeof";

  return modals_message_versions_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;
  }, modals_message_versions_typeof(obj);
}
var modals_message_versions_templateObject;
function modals_message_versions_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function modals_message_versions_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function modals_message_versions_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, modals_message_versions_toPropertyKey(descriptor.key), descriptor);
  }
}
function modals_message_versions_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) modals_message_versions_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) modals_message_versions_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modals_message_versions_toPropertyKey(arg) {
  var key = modals_message_versions_toPrimitive(arg, "string");
  return modals_message_versions_typeof(key) === "symbol" ? key : String(key);
}
function modals_message_versions_toPrimitive(input, hint) {
  if (modals_message_versions_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modals_message_versions_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function modals_message_versions_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) modals_message_versions_setPrototypeOf(subClass, superClass);
}
function modals_message_versions_setPrototypeOf(o, p) {
  modals_message_versions_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return modals_message_versions_setPrototypeOf(o, p);
}
function modals_message_versions_createSuper(Derived) {
  var hasNativeReflectConstruct = modals_message_versions_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = modals_message_versions_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = modals_message_versions_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return modals_message_versions_possibleConstructorReturn(this, result);
  };
}
function modals_message_versions_possibleConstructorReturn(self, call) {
  if (call && (modals_message_versions_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 modals_message_versions_assertThisInitialized(self);
}
function modals_message_versions_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function modals_message_versions_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 modals_message_versions_getPrototypeOf(o) {
  modals_message_versions_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return modals_message_versions_getPrototypeOf(o);
}





var MessageVersionsModal = /*#__PURE__*/function (_BaseModal) {
  modals_message_versions_inherits(MessageVersionsModal, _BaseModal);
  var _super = modals_message_versions_createSuper(MessageVersionsModal);
  function MessageVersionsModal() {
    modals_message_versions_classCallCheck(this, MessageVersionsModal);
    return _super.apply(this, arguments);
  }
  modals_message_versions_createClass(MessageVersionsModal, [{
    key: "renderModal",
    value: function renderModal() {
      return (0,external_lit_namespaceObject.html)(modals_message_versions_templateObject || (modals_message_versions_templateObject = modals_message_versions_taggedTemplateLiteral(["<converse-message-versions .model=", "></converse-message-versions>"])), this.model);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Message versions');
    }
  }]);
  return MessageVersionsModal;
}(modal_modal);

shared_api.elements.define('converse-message-versions-modal', MessageVersionsModal);
;// CONCATENATED MODULE: ./src/shared/modals/templates/user-details.js
function user_details_typeof(obj) {
  "@babel/helpers - typeof";

  return user_details_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;
  }, user_details_typeof(obj);
}
var user_details_templateObject, user_details_templateObject2, user_details_templateObject3, user_details_templateObject4, user_details_templateObject5, user_details_templateObject6, user_details_templateObject7, user_details_templateObject8, user_details_templateObject9;
function user_details_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 user_details_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? user_details_ownKeys(Object(source), !0).forEach(function (key) {
      user_details_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : user_details_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function user_details_defineProperty(obj, key, value) {
  key = user_details_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 user_details_toPropertyKey(arg) {
  var key = user_details_toPrimitive(arg, "string");
  return user_details_typeof(key) === "symbol" ? key : String(key);
}
function user_details_toPrimitive(input, hint) {
  if (user_details_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (user_details_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function user_details_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





var remove_button = function remove_button(el) {
  var i18n_remove_contact = __('Remove as contact');
  return (0,external_lit_namespaceObject.html)(user_details_templateObject || (user_details_templateObject = user_details_taggedTemplateLiteral(["\n        <button type=\"button\" @click=\"", "\" class=\"btn btn-danger remove-contact\">\n            <converse-icon\n                class=\"fas fa-trash-alt\"\n                color=\"var(--text-color-lighten-15-percent)\"\n                size=\"1em\"\n            ></converse-icon>\n            ", "\n        </button>\n    "])), function (ev) {
    return el.removeContact(ev);
  }, i18n_remove_contact);
};
var tplFooter = function tplFooter(el) {
  var is_roster_contact = el.model.contact !== undefined;
  var i18n_refresh = __('Refresh');
  var allow_contact_removal = shared_api.settings.get('allow_contact_removal');
  return (0,external_lit_namespaceObject.html)(user_details_templateObject2 || (user_details_templateObject2 = user_details_taggedTemplateLiteral(["\n        <div class=\"modal-footer\">\n            ", "\n            <button type=\"button\" class=\"btn btn-info refresh-contact\" @click=", ">\n                <converse-icon\n                    class=\"fa fa-refresh\"\n                    color=\"var(--text-color-lighten-15-percent)\"\n                    size=\"1em\"\n                ></converse-icon>\n                ", "</button>\n            ", "\n        </div>\n    "])), modal_close_button, function (ev) {
    return el.refreshContact(ev);
  }, i18n_refresh, allow_contact_removal && is_roster_contact ? remove_button(el) : '');
};
var tplUserDetailsModal = function tplUserDetailsModal(el) {
  var _el$model;
  var vcard = (_el$model = el.model) === null || _el$model === void 0 ? void 0 : _el$model.vcard;
  var vcard_json = vcard ? vcard.toJSON() : {};
  var o = user_details_objectSpread(user_details_objectSpread({}, el.model.toJSON()), vcard_json);
  var i18n_address = __('XMPP Address');
  var i18n_email = __('Email');
  var i18n_full_name = __('Full Name');
  var i18n_nickname = __('Nickname');
  var i18n_profile = __('The User\'s Profile Image');
  var i18n_role = __('Role');
  var i18n_url = __('URL');
  var avatar_data = {
    'alt_text': i18n_profile,
    'extra_classes': 'mb-3',
    'height': '120',
    'width': '120'
  };
  return (0,external_lit_namespaceObject.html)(user_details_templateObject3 || (user_details_templateObject3 = user_details_taggedTemplateLiteral(["\n        <div class=\"modal-body\">\n            ", "\n            ", "\n            <p><label>", ":</label> <a href=\"xmpp:", "\">", "</a></p>\n            ", "\n            ", "\n            ", "\n            ", "\n\n            <converse-omemo-fingerprints jid=", "></converse-omemo-fingerprints>\n        </div>\n    "])), o.image ? (0,external_lit_namespaceObject.html)(user_details_templateObject4 || (user_details_templateObject4 = user_details_taggedTemplateLiteral(["<div class=\"mb-4\">", "</div>"])), avatar(Object.assign(o, avatar_data))) : '', o.fullname ? (0,external_lit_namespaceObject.html)(user_details_templateObject5 || (user_details_templateObject5 = user_details_taggedTemplateLiteral(["<p><label>", ":</label> ", "</p>"])), i18n_full_name, o.fullname) : '', i18n_address, o.jid, o.jid, o.nickname ? (0,external_lit_namespaceObject.html)(user_details_templateObject6 || (user_details_templateObject6 = user_details_taggedTemplateLiteral(["<p><label>", ":</label> ", "</p>"])), i18n_nickname, o.nickname) : '', o.url ? (0,external_lit_namespaceObject.html)(user_details_templateObject7 || (user_details_templateObject7 = user_details_taggedTemplateLiteral(["<p><label>", ":</label> <a target=\"_blank\" rel=\"noopener\" href=\"", "\">", "</a></p>"])), i18n_url, o.url, o.url) : '', o.email ? (0,external_lit_namespaceObject.html)(user_details_templateObject8 || (user_details_templateObject8 = user_details_taggedTemplateLiteral(["<p><label>", ":</label> <a href=\"mailto:", "\">", "</a></p>"])), i18n_email, o.email, o.email) : '', o.role ? (0,external_lit_namespaceObject.html)(user_details_templateObject9 || (user_details_templateObject9 = user_details_taggedTemplateLiteral(["<p><label>", ":</label> ", "</p>"])), i18n_role, o.role) : '', o.jid);
};
;// CONCATENATED MODULE: ./src/plugins/rosterview/utils.js
function utils_createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = rosterview_utils_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 rosterview_utils_toConsumableArray(arr) {
  return rosterview_utils_arrayWithoutHoles(arr) || rosterview_utils_iterableToArray(arr) || rosterview_utils_unsupportedIterableToArray(arr) || rosterview_utils_nonIterableSpread();
}
function rosterview_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function rosterview_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return rosterview_utils_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 rosterview_utils_arrayLikeToArray(o, minLen);
}
function rosterview_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function rosterview_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return rosterview_utils_arrayLikeToArray(arr);
}
function rosterview_utils_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 utils_removeContact(contact) {
  contact.removeFromRoster(function () {
    return contact.destroy();
  }, function (e) {
    e && log.error(e);
    shared_api.alert('error', __('Error'), [__('Sorry, there was an error while trying to remove %1$s as a contact.', contact.getDisplayName())]);
  });
}
function highlightRosterItem(chatbox) {
  var _converse$roster, _converse$roster$get;
  (_converse$roster = shared_converse.roster) === null || _converse$roster === void 0 ? void 0 : (_converse$roster$get = _converse$roster.get(chatbox.get('jid'))) === null || _converse$roster$get === void 0 ? void 0 : _converse$roster$get.trigger('highlight');
}
function toggleGroup(ev, name) {
  var _ev$preventDefault;
  ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
  var collapsed = shared_converse.roster.state.get('collapsed_groups');
  if (collapsed.includes(name)) {
    shared_converse.roster.state.save('collapsed_groups', collapsed.filter(function (n) {
      return n !== name;
    }));
  } else {
    shared_converse.roster.state.save('collapsed_groups', [].concat(rosterview_utils_toConsumableArray(collapsed), [name]));
  }
}
function isContactFiltered(contact, groupname) {
  var filter = shared_converse.roster_filter;
  var type = filter.get('filter_type');
  var q = type === 'state' ? filter.get('chat_state').toLowerCase() : filter.get('filter_text').toLowerCase();
  if (!q) return false;
  if (type === 'state') {
    var sticky_groups = [shared_converse.HEADER_REQUESTING_CONTACTS, shared_converse.HEADER_UNREAD];
    if (sticky_groups.includes(groupname)) {
      // When filtering by chat state, we still want to
      // show sticky groups, even though they don't
      // match the state in question.
      return false;
    } else if (q === 'unread_messages') {
      return contact.get('num_unread') === 0;
    } else if (q === 'online') {
      return ["offline", "unavailable"].includes(contact.presence.get('show'));
    } else {
      return !contact.presence.get('show').includes(q);
    }
  } else if (type === 'contacts') {
    return !contact.getFilterCriteria().includes(q);
  }
}
function shouldShowContact(contact, groupname) {
  var chat_status = contact.presence.get('show');
  if (shared_api.settings.get('hide_offline_users') && chat_status === 'offline') {
    // If pending or requesting, show
    if (contact.get('ask') === 'subscribe' || contact.get('subscription') === 'from' || contact.get('requesting') === true) {
      return !isContactFiltered(contact, groupname);
    }
    return false;
  }
  return !isContactFiltered(contact, groupname);
}
function shouldShowGroup(group) {
  var filter = shared_converse.roster_filter;
  var type = filter.get('filter_type');
  if (type === 'groups') {
    var _filter$get;
    var q = (_filter$get = filter.get('filter_text')) === null || _filter$get === void 0 ? void 0 : _filter$get.toLowerCase();
    if (!q) {
      return true;
    }
    if (!group.toLowerCase().includes(q)) {
      return false;
    }
  }
  return true;
}
function populateContactsMap(contacts_map, contact) {
  if (contact.get('requesting')) {
    var name = shared_converse.HEADER_REQUESTING_CONTACTS;
    contacts_map[name] ? contacts_map[name].push(contact) : contacts_map[name] = [contact];
  } else {
    var contact_groups;
    if (shared_api.settings.get('roster_groups')) {
      contact_groups = contact.get('groups');
      contact_groups = contact_groups.length === 0 ? [shared_converse.HEADER_UNGROUPED] : contact_groups;
    } else {
      if (contact.get('ask') === 'subscribe') {
        contact_groups = [shared_converse.HEADER_PENDING_CONTACTS];
      } else {
        contact_groups = [shared_converse.HEADER_CURRENT_CONTACTS];
      }
    }
    var _iterator = utils_createForOfIteratorHelper(contact_groups),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _name = _step.value;
        contacts_map[_name] ? contacts_map[_name].push(contact) : contacts_map[_name] = [contact];
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  if (contact.get('num_unread')) {
    var _name2 = shared_converse.HEADER_UNREAD;
    contacts_map[_name2] ? contacts_map[_name2].push(contact) : contacts_map[_name2] = [contact];
  }
  return contacts_map;
}
;// CONCATENATED MODULE: ./src/shared/modals/user-details.js
function modals_user_details_typeof(obj) {
  "@babel/helpers - typeof";

  return modals_user_details_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;
  }, modals_user_details_typeof(obj);
}
function user_details_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  user_details_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" == modals_user_details_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 user_details_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 user_details_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        user_details_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        user_details_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function user_details_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function user_details_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, modals_user_details_toPropertyKey(descriptor.key), descriptor);
  }
}
function user_details_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) user_details_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) user_details_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function modals_user_details_toPropertyKey(arg) {
  var key = modals_user_details_toPrimitive(arg, "string");
  return modals_user_details_typeof(key) === "symbol" ? key : String(key);
}
function modals_user_details_toPrimitive(input, hint) {
  if (modals_user_details_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (modals_user_details_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function user_details_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    user_details_get = Reflect.get.bind();
  } else {
    user_details_get = function _get(target, property, receiver) {
      var base = user_details_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return user_details_get.apply(this, arguments);
}
function user_details_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = user_details_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function user_details_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) user_details_setPrototypeOf(subClass, superClass);
}
function user_details_setPrototypeOf(o, p) {
  user_details_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return user_details_setPrototypeOf(o, p);
}
function user_details_createSuper(Derived) {
  var hasNativeReflectConstruct = user_details_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = user_details_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = user_details_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return user_details_possibleConstructorReturn(this, result);
  };
}
function user_details_possibleConstructorReturn(self, call) {
  if (call && (modals_user_details_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 user_details_assertThisInitialized(self);
}
function user_details_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function user_details_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 user_details_getPrototypeOf(o) {
  user_details_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return user_details_getPrototypeOf(o);
}






var user_details_u = public_converse.env.utils;
var UserDetailsModal = /*#__PURE__*/function (_BaseModal) {
  user_details_inherits(UserDetailsModal, _BaseModal);
  var _super = user_details_createSuper(UserDetailsModal);
  function UserDetailsModal() {
    user_details_classCallCheck(this, UserDetailsModal);
    return _super.apply(this, arguments);
  }
  user_details_createClass(UserDetailsModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      user_details_get(user_details_getPrototypeOf(UserDetailsModal.prototype), "initialize", this).call(this);
      this.model.rosterContactAdded.then(function () {
        return _this.registerContactEventHandlers();
      });
      this.listenTo(this.model, 'change', this.render);
      this.registerContactEventHandlers();
      /**
       * Triggered once the UserDetailsModal has been initialized
       * @event _converse#userDetailsModalInitialized
       * @type { _converse.ChatBox }
       * @example _converse.api.listen.on('userDetailsModalInitialized', (chatbox) => { ... });
       */
      shared_api.trigger('userDetailsModalInitialized', this.model);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return tplUserDetailsModal(this);
    }
  }, {
    key: "renderModalFooter",
    value: function renderModalFooter() {
      return tplFooter(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      return this.model.getDisplayName();
    }
  }, {
    key: "registerContactEventHandlers",
    value: function registerContactEventHandlers() {
      var _this2 = this;
      if (this.model.contact !== undefined) {
        this.listenTo(this.model.contact, 'change', this.render);
        this.listenTo(this.model.contact.vcard, 'change', this.render);
        this.model.contact.on('destroy', function () {
          delete _this2.model.contact;
          _this2.render();
        });
      }
    }
  }, {
    key: "refreshContact",
    value: function () {
      var _refreshContact = user_details_asyncToGenerator( /*#__PURE__*/user_details_regeneratorRuntime().mark(function _callee(ev) {
        var refresh_icon;
        return user_details_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (ev && ev.preventDefault) {
                ev.preventDefault();
              }
              refresh_icon = this.el.querySelector('.fa-refresh');
              user_details_u.addClass('fa-spin', refresh_icon);
              _context.prev = 3;
              _context.next = 6;
              return shared_api.vcard.update(this.model.contact.vcard, true);
            case 6:
              _context.next = 12;
              break;
            case 8:
              _context.prev = 8;
              _context.t0 = _context["catch"](3);
              log.fatal(_context.t0);
              this.alert(__('Sorry, something went wrong while trying to refresh'), 'danger');
            case 12:
              user_details_u.removeClass('fa-spin', refresh_icon);
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[3, 8]]);
      }));
      function refreshContact(_x) {
        return _refreshContact.apply(this, arguments);
      }
      return refreshContact;
    }()
  }, {
    key: "removeContact",
    value: function () {
      var _removeContact2 = user_details_asyncToGenerator( /*#__PURE__*/user_details_regeneratorRuntime().mark(function _callee2(ev) {
        var _ev$preventDefault,
          _this3 = this;
        var result;
        return user_details_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
              if (shared_api.settings.get('allow_contact_removal')) {
                _context2.next = 3;
                break;
              }
              return _context2.abrupt("return");
            case 3:
              _context2.next = 5;
              return shared_api.confirm(__("Are you sure you want to remove this contact?"));
            case 5:
              result = _context2.sent;
              if (result) {
                // XXX: The `dismissHandler` in bootstrap.native tries to
                // reference the remove button after it's been cleared from
                // the DOM, so we delay removing the contact to give it time.
                setTimeout(function () {
                  return utils_removeContact(_this3.model.contact);
                }, 1);
                this.modal.hide();
              }
            case 7:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function removeContact(_x2) {
        return _removeContact2.apply(this, arguments);
      }
      return removeContact;
    }()
  }]);
  return UserDetailsModal;
}(modal_modal);

shared_api.elements.define('converse-user-details-modal', UserDetailsModal);
;// CONCATENATED MODULE: ./src/shared/chat/templates/file-progress.js
var file_progress_templateObject, file_progress_templateObject2;
function file_progress_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var file_progress_filesize = public_converse.env.filesize;
/* harmony default export */ const file_progress = (function (el) {
  var _el$model$vcard, _el$model$vcard2;
  var i18n_uploading = __('Uploading file:');
  var filename = el.model.file.name;
  var size = file_progress_filesize(el.model.file.size);
  return (0,external_lit_namespaceObject.html)(file_progress_templateObject || (file_progress_templateObject = file_progress_taggedTemplateLiteral(["\n        <div class=\"message chat-msg\">\n            ", "\n            <div class=\"chat-msg__content\">\n                <span class=\"chat-msg__text\">", " <strong>", "</strong>, ", "</span>\n                <progress value=\"", "\"/>\n            </div>\n        </div>"])), el.shouldShowAvatar() ? (0,external_lit_namespaceObject.html)(file_progress_templateObject2 || (file_progress_templateObject2 = file_progress_taggedTemplateLiteral(["<a class=\"show-msg-author-modal\" @click=", ">\n                    <converse-avatar class=\"avatar align-self-center\"\n                        .data=", "\n                        nonce=", "\n                        height=\"40\" width=\"40\"></converse-avatar>\n                </a>"])), el.showUserModal, (_el$model$vcard = el.model.vcard) === null || _el$model$vcard === void 0 ? void 0 : _el$model$vcard.attributes, (_el$model$vcard2 = el.model.vcard) === null || _el$model$vcard2 === void 0 ? void 0 : _el$model$vcard2.get('vcard_updated')) : '', i18n_uploading, filename, size, el.model.get('progress'));
});
;// CONCATENATED MODULE: ./src/shared/chat/templates/info-message.js
var info_message_templateObject, info_message_templateObject2, info_message_templateObject3, info_message_templateObject4;
function info_message_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



var info_message_dayjs = public_converse.env.dayjs;
/* harmony default export */ const info_message = (function (el) {
  var isodate = info_message_dayjs(el.model.get('time')).toISOString();
  var i18n_retry = __('Retry');
  return (0,external_lit_namespaceObject.html)(info_message_templateObject || (info_message_templateObject = info_message_taggedTemplateLiteral(["\n        <div class=\"message chat-info chat-", "\"\n            data-isodate=\"", "\"\n            data-type=\"", "\"\n            data-value=\"", "\">\n\n            <div class=\"chat-info__message\">\n                <converse-rich-text\n                    .mentions=", "\n                    render_styling\n                    text=", ">\n                </converse-rich-text>\n            </div>\n            ", "\n            ", "\n            ", "\n        </div>"])), el.model.get('type'), isodate, el.data_name, el.data_value, el.model.get('references'), el.model.getMessageText(), el.model.get('reason') ? (0,external_lit_namespaceObject.html)(info_message_templateObject2 || (info_message_templateObject2 = info_message_taggedTemplateLiteral(["<q class=\"reason\">", "</q>"])), el.model.get('reason')) : "", el.model.get('error_text') ? (0,external_lit_namespaceObject.html)(info_message_templateObject3 || (info_message_templateObject3 = info_message_taggedTemplateLiteral(["<q class=\"reason\">", "</q>"])), el.model.get('error_text')) : "", el.model.get('retry_event_id') ? (0,external_lit_namespaceObject.html)(info_message_templateObject4 || (info_message_templateObject4 = info_message_taggedTemplateLiteral(["<a class=\"retry\" @click=", ">", "</a>"])), el.onRetryClicked, i18n_retry) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/mep-message.js
var mep_message_templateObject, mep_message_templateObject2, mep_message_templateObject3;
function mep_message_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var mep_message_dayjs = public_converse.env.dayjs;
/* harmony default export */ const mep_message = (function (el) {
  var isodate = mep_message_dayjs(el.model.get('time')).toISOString();
  return (0,external_lit_namespaceObject.html)(mep_message_templateObject || (mep_message_templateObject = mep_message_taggedTemplateLiteral(["\n        <div class=\"message chat-info message--mep ", "\"\n            data-isodate=\"", "\"\n            data-type=\"", "\"\n            data-value=\"", "\">\n\n            <div class=\"chat-msg__content\">\n                <div class=\"chat-msg__body chat-msg__body--", " ", "\">\n                    <div class=\"chat-info__message\">\n                        ", "\n                    </div>\n                    <converse-message-actions\n                        ?is_retracted=", "\n                        .model=", "></converse-message-actions>\n                </div>\n            </div>\n        </div>"])), el.getExtraMessageClasses(), isodate, el.data_name, el.data_value, el.model.get('type'), el.model.get('is_delayed') ? 'chat-msg__body--delayed' : '', el.isRetracted() ? el.renderRetraction() : (0,external_lit_namespaceObject.html)(mep_message_templateObject2 || (mep_message_templateObject2 = mep_message_taggedTemplateLiteral(["\n                            <converse-rich-text\n                                .mentions=", "\n                                render_styling\n                                text=", ">\n                            </converse-rich-text>\n                            ", "\n                        "])), el.model.get('references'), el.model.getMessageText(), el.model.get('reason') ? (0,external_lit_namespaceObject.html)(mep_message_templateObject3 || (mep_message_templateObject3 = mep_message_taggedTemplateLiteral(["<q class=\"reason\"><converse-rich-text text=", "></converse-rich-text></q>"])), el.model.get('reason')) : ""), el.isRetracted(), el.model);
});
;// CONCATENATED MODULE: ./src/shared/components/image.js
function components_image_typeof(obj) {
  "@babel/helpers - typeof";

  return components_image_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;
  }, components_image_typeof(obj);
}
function components_image_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function components_image_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, components_image_toPropertyKey(descriptor.key), descriptor);
  }
}
function components_image_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) components_image_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) components_image_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function components_image_toPropertyKey(arg) {
  var key = components_image_toPrimitive(arg, "string");
  return components_image_typeof(key) === "symbol" ? key : String(key);
}
function components_image_toPrimitive(input, hint) {
  if (components_image_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (components_image_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function components_image_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) components_image_setPrototypeOf(subClass, superClass);
}
function components_image_setPrototypeOf(o, p) {
  components_image_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return components_image_setPrototypeOf(o, p);
}
function components_image_createSuper(Derived) {
  var hasNativeReflectConstruct = components_image_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = components_image_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = components_image_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return components_image_possibleConstructorReturn(this, result);
  };
}
function components_image_possibleConstructorReturn(self, call) {
  if (call && (components_image_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 components_image_assertThisInitialized(self);
}
function components_image_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function components_image_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 components_image_getPrototypeOf(o) {
  components_image_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return components_image_getPrototypeOf(o);
}





var Image = /*#__PURE__*/function (_CustomElement) {
  components_image_inherits(Image, _CustomElement);
  var _super = components_image_createSuper(Image);
  function Image() {
    var _this;
    components_image_classCallCheck(this, Image);
    _this = _super.call(this);
    _this.src = null;
    _this.href = null;
    _this.onImgClick = null;
    _this.onImgLoad = null;
    return _this;
  }
  components_image_createClass(Image, [{
    key: "render",
    value: function render() {
      if (isGIFURL(this.src) && shouldRenderMediaFromURL(this.src, 'image')) {
        return templates_gif(filterQueryParamsFromURL(this.src), true);
      } else {
        return src_templates_image({
          'src': filterQueryParamsFromURL(this.src),
          'href': this.href,
          'onClick': this.onImgClick,
          'onLoad': this.onImgLoad
        });
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'src': {
          type: String
        },
        'onImgLoad': {
          type: Function
        },
        // If specified, image is wrapped in a hyperlink that points to this URL.
        'href': {
          type: String
        }
      };
    }
  }]);
  return Image;
}(CustomElement);

shared_api.elements.define('converse-image', Image);
;// CONCATENATED MODULE: ./src/shared/chat/templates/unfurl.js
var unfurl_templateObject, unfurl_templateObject2, unfurl_templateObject3, unfurl_templateObject4, unfurl_templateObject5, unfurl_templateObject6, unfurl_templateObject7;
function unfurl_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



function isValidURL(url) {
  // We don't consider relative URLs as valid
  return !!getURI(url).host();
}
function isValidImage(image) {
  return image && isDomainAllowed(image, 'allowed_image_domains') && isValidURL(image);
}
var tplUrlWrapper = function tplUrlWrapper(o, wrapped_template) {
  return o.url && isValidURL(o.url) && !isGIFURL(o.image) ? (0,external_lit_namespaceObject.html)(unfurl_templateObject || (unfurl_templateObject = unfurl_taggedTemplateLiteral(["<a href=\"", "\" target=\"_blank\" rel=\"noopener\">", "</a>"])), o.url, wrapped_template(o)) : wrapped_template(o);
};
var tplImage = function tplImage(o) {
  return (0,external_lit_namespaceObject.html)(unfurl_templateObject2 || (unfurl_templateObject2 = unfurl_taggedTemplateLiteral(["<converse-image class=\"card-img-top hor_centered\" href=\"", "\" src=\"", "\" .onImgLoad=", "></converse-image>"])), o.url, o.image, o.onload);
};
/* harmony default export */ const unfurl = (function (o) {
  var show_image = isValidImage(o.image);
  var has_body_info = o.title || o.description || o.url;
  if (show_image || has_body_info) {
    return (0,external_lit_namespaceObject.html)(unfurl_templateObject3 || (unfurl_templateObject3 = unfurl_taggedTemplateLiteral(["<div class=\"card card--unfurl\">\n            ", "\n            ", "\n        </div>"])), show_image ? tplImage(o) : '', has_body_info ? (0,external_lit_namespaceObject.html)(unfurl_templateObject4 || (unfurl_templateObject4 = unfurl_taggedTemplateLiteral([" <div class=\"card-body\">\n                      ", "\n                      ", "\n                      ", "\n                  </div>"])), o.title ? tplUrlWrapper(o, function (o) {
      return (0,external_lit_namespaceObject.html)(unfurl_templateObject5 || (unfurl_templateObject5 = unfurl_taggedTemplateLiteral(["<h5 class=\"card-title\">", "</h5>"])), o.title);
    }) : '', o.description ? (0,external_lit_namespaceObject.html)(unfurl_templateObject6 || (unfurl_templateObject6 = unfurl_taggedTemplateLiteral(["<p class=\"card-text\">\n                                <converse-rich-text text=", "></converse-rich-text>\n                            </p>"])), o.description) : '', o.url ? (0,external_lit_namespaceObject.html)(unfurl_templateObject7 || (unfurl_templateObject7 = unfurl_taggedTemplateLiteral(["<p class=\"card-text\">\n                                <a href=\"", "\" target=\"_blank\" rel=\"noopener\">", "</a>\n                            </p>"])), o.url, getURI(o.url).domain()) : '') : '');
  } else {
    return '';
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/unfurl.scss
var styles_unfurl = __webpack_require__(3638);
;// CONCATENATED MODULE: ./src/shared/chat/styles/unfurl.scss

      
      
      
      
      
      
      
      
      

var unfurl_options = {};

unfurl_options.styleTagTransform = (styleTagTransform_default());
unfurl_options.setAttributes = (setAttributesWithoutAttributes_default());

      unfurl_options.insert = insertBySelector_default().bind(null, "head");
    
unfurl_options.domAPI = (styleDomAPI_default());
unfurl_options.insertStyleElement = (insertStyleElement_default());

var unfurl_update = injectStylesIntoStyleTag_default()(styles_unfurl/* default */.Z, unfurl_options);




       /* harmony default export */ const chat_styles_unfurl = (styles_unfurl/* default */.Z && styles_unfurl/* default */.Z.locals ? styles_unfurl/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/unfurl.js
function unfurl_typeof(obj) {
  "@babel/helpers - typeof";

  return unfurl_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;
  }, unfurl_typeof(obj);
}
function unfurl_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function unfurl_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, unfurl_toPropertyKey(descriptor.key), descriptor);
  }
}
function unfurl_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) unfurl_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) unfurl_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function unfurl_toPropertyKey(arg) {
  var key = unfurl_toPrimitive(arg, "string");
  return unfurl_typeof(key) === "symbol" ? key : String(key);
}
function unfurl_toPrimitive(input, hint) {
  if (unfurl_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (unfurl_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function unfurl_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) unfurl_setPrototypeOf(subClass, superClass);
}
function unfurl_setPrototypeOf(o, p) {
  unfurl_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return unfurl_setPrototypeOf(o, p);
}
function unfurl_createSuper(Derived) {
  var hasNativeReflectConstruct = unfurl_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = unfurl_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = unfurl_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return unfurl_possibleConstructorReturn(this, result);
  };
}
function unfurl_possibleConstructorReturn(self, call) {
  if (call && (unfurl_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 unfurl_assertThisInitialized(self);
}
function unfurl_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function unfurl_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 unfurl_getPrototypeOf(o) {
  unfurl_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return unfurl_getPrototypeOf(o);
}





var MessageUnfurl = /*#__PURE__*/function (_CustomElement) {
  unfurl_inherits(MessageUnfurl, _CustomElement);
  var _super = unfurl_createSuper(MessageUnfurl);
  function MessageUnfurl() {
    unfurl_classCallCheck(this, MessageUnfurl);
    return _super.apply(this, arguments);
  }
  unfurl_createClass(MessageUnfurl, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      var settings = getAppSettings();
      this.listenTo(settings, 'change:allowed_image_domains', function () {
        return _this.requestUpdate();
      });
      this.listenTo(settings, 'change:render_media', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      return unfurl(Object.assign({
        'onload': function onload() {
          return _this2.onImageLoad();
        }
      }, {
        description: this.description || '',
        image: this.image || '',
        title: this.title || '',
        url: this.url || ''
      }));
    }
  }, {
    key: "onImageLoad",
    value: function onImageLoad() {
      this.dispatchEvent(new CustomEvent('imageLoaded', {
        detail: this,
        'bubbles': true
      }));
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        description: {
          type: String
        },
        image: {
          type: String
        },
        jid: {
          type: String
        },
        title: {
          type: String
        },
        url: {
          type: String
        }
      };
    }
  }]);
  return MessageUnfurl;
}(CustomElement);

shared_api.elements.define('converse-message-unfurl', MessageUnfurl);
;// CONCATENATED MODULE: ./src/shared/chat/templates/message.js
var message_templateObject, message_templateObject2, message_templateObject3, message_templateObject4, message_templateObject5, message_templateObject6, message_templateObject7, message_templateObject8;
function message_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





/* harmony default export */ const templates_message = (function (el, o) {
  var _el$model$vcard, _el$model$vcard2, _el$model$get;
  var i18n_new_messages = __('New messages');
  var is_followup = el.model.isFollowup();
  return (0,external_lit_namespaceObject.html)(message_templateObject || (message_templateObject = message_taggedTemplateLiteral(["\n        ", "\n        <div class=\"message chat-msg ", "\"\n                data-isodate=\"", "\"\n                data-msgid=\"", "\"\n                data-from=\"", "\"\n                data-encrypted=\"", "\">\n\n            <!-- Anchor to allow us to scroll the message into view -->\n            <a id=\"", "\"></a>\n\n            ", "\n\n            <div class=\"chat-msg__content chat-msg__content--", " ", "\">\n                ", "\n\n                <div class=\"chat-msg__body chat-msg__body--", " ", " ", "\">\n                    <div class=\"chat-msg__message\">\n                        ", "\n                        ", "\n                    </div>\n                    <converse-message-actions\n                        .model=", "\n                        ?is_retracted=", "></converse-message-actions>\n                </div>\n\n                ", "\n            </div>\n        </div>"])), o.is_first_unread ? (0,external_lit_namespaceObject.html)(message_templateObject2 || (message_templateObject2 = message_taggedTemplateLiteral(["<div class=\"message separator\"><hr class=\"separator\"><span class=\"separator-text\">", "</span></div>"])), i18n_new_messages) : '', el.getExtraMessageClasses(), o.time, o.msgid, o.from, o.is_encrypted, o.msgid, o.should_show_avatar && !is_followup ? (0,external_lit_namespaceObject.html)(message_templateObject3 || (message_templateObject3 = message_taggedTemplateLiteral(["<a class=\"show-msg-author-modal\" @click=", ">\n                    <converse-avatar\n                        class=\"avatar align-self-center\"\n                        .data=", "\n                        nonce=", "\n                        height=\"40\" width=\"40\"></converse-avatar>\n                </a>"])), el.showUserModal, (_el$model$vcard = el.model.vcard) === null || _el$model$vcard === void 0 ? void 0 : _el$model$vcard.attributes, (_el$model$vcard2 = el.model.vcard) === null || _el$model$vcard2 === void 0 ? void 0 : _el$model$vcard2.get('vcard_updated')) : '', o.sender, o.is_me_message ? 'chat-msg__content--action' : '', !o.is_me_message && !is_followup ? (0,external_lit_namespaceObject.html)(message_templateObject4 || (message_templateObject4 = message_taggedTemplateLiteral(["\n                    <span class=\"chat-msg__heading\">\n                        <span class=\"chat-msg__author\"><a class=\"show-msg-author-modal\" @click=", ">", "</a></span>\n                        ", "\n                        <time timestamp=\"", "\" class=\"chat-msg__time\">", "</time>\n                        ", "\n                    </span>"])), el.showUserModal, o.username, o.hats.map(function (h) {
    return (0,external_lit_namespaceObject.html)(message_templateObject5 || (message_templateObject5 = message_taggedTemplateLiteral(["<span class=\"badge badge-secondary\">", "</span>"])), h.title);
  }), el.model.get('edited') || el.model.get('time'), o.pretty_time, o.is_encrypted ? (0,external_lit_namespaceObject.html)(message_templateObject6 || (message_templateObject6 = message_taggedTemplateLiteral(["<converse-icon class=\"fa fa-lock\" size=\"1.1em\"></converse-icon>"]))) : '') : '', o.message_type, o.received ? 'chat-msg__body--received' : '', o.is_delayed ? 'chat-msg__body--delayed' : '', o.is_me_message ? (0,external_lit_namespaceObject.html)(message_templateObject7 || (message_templateObject7 = message_taggedTemplateLiteral(["\n                            <time timestamp=\"", "\" class=\"chat-msg__time\">", "</time>&nbsp;\n                            <span class=\"chat-msg__author\">", "", "</span>&nbsp;"])), o.edited || o.time, o.pretty_time, o.is_me_message ? '**' : '', o.username) : '', o.is_retracted ? el.renderRetraction() : el.renderMessageText(), el.model, o.is_retracted, (_el$model$get = el.model.get('ogp_metadata')) === null || _el$model$get === void 0 ? void 0 : _el$model$get.map(function (m) {
    var _el$chatbox;
    if (el.model.get('hide_url_previews') === true) {
      return '';
    }
    if (!shouldRenderMediaFromURL(m['og:image'], 'image')) {
      return '';
    }
    return (0,external_lit_namespaceObject.html)(message_templateObject8 || (message_templateObject8 = message_taggedTemplateLiteral(["<converse-message-unfurl\n                        @animationend=\"", "\"\n                        class=\"", "\"\n                        jid=\"", "\"\n                        description=\"", "\"\n                        title=\"", "\"\n                        image=\"", "\"\n                        url=\"", "\"></converse-message-unfurl>"])), el.onUnfurlAnimationEnd, el.model.get('url_preview_transition'), (_el$chatbox = el.chatbox) === null || _el$chatbox === void 0 ? void 0 : _el$chatbox.get('jid'), m['og:description'] || '', m['og:title'] || '', m['og:image'] || '', m['og:url'] || '');
  }));
});
;// CONCATENATED MODULE: ./src/shared/chat/templates/message-text.js
var message_text_templateObject, message_text_templateObject2, message_text_templateObject3, message_text_templateObject4, message_text_templateObject5, message_text_templateObject6;
function message_text_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



var tplEditedIcon = function tplEditedIcon(el) {
  var i18n_edited = __('This message has been edited');
  return (0,external_lit_namespaceObject.html)(message_text_templateObject || (message_text_templateObject = message_text_taggedTemplateLiteral(["<converse-icon title=\"", "\" class=\"fa fa-edit chat-msg__edit-modal\" @click=", " size=\"1em\"></converse-icon>"])), i18n_edited, el.showMessageVersionsModal);
};
var tplCheckmark = function tplCheckmark() {
  return (0,external_lit_namespaceObject.html)(message_text_templateObject2 || (message_text_templateObject2 = message_text_taggedTemplateLiteral(["<converse-icon size=\"1em\" color=\"var(--chat-color)\" class=\"fa fa-check chat-msg__receipt\"></converse-icon>"])));
};
/* harmony default export */ const message_text = (function (el) {
  var i18n_show = __('Show more');
  var is_groupchat_message = el.model.get('type') === 'groupchat';
  var i18n_show_less = __('Show less');
  var tplSpoilerHint = (0,external_lit_namespaceObject.html)(message_text_templateObject3 || (message_text_templateObject3 = message_text_taggedTemplateLiteral(["\n        <div class=\"chat-msg__spoiler-hint\">\n            <span class=\"spoiler-hint\">", "</span>\n            <a class=\"badge badge-info spoiler-toggle\" href=\"#\" @click=", ">\n                <converse-icon size=\"1em\" color=\"var(--background)\" class=\"fa ", "\"></converse-icon>\n                ", "\n            </a>\n        </div>\n    "])), el.model.get('spoiler_hint'), el.toggleSpoilerMessage, el.model.get('is_spoiler_visible') ? 'fa-eye-slash' : 'fa-eye', el.model.get('is_spoiler_visible') ? i18n_show_less : i18n_show);
  var spoiler_classes = el.model.get('is_spoiler') ? "spoiler ".concat(el.model.get('is_spoiler_visible') ? '' : 'hidden') : '';
  var text = el.model.getMessageText();
  var show_oob = el.model.get('oob_url') && text !== el.model.get('oob_url');
  return (0,external_lit_namespaceObject.html)(message_text_templateObject4 || (message_text_templateObject4 = message_text_taggedTemplateLiteral(["\n        ", "\n        ", "\n        <span class=\"chat-msg__body--wrapper\">\n            <converse-chat-message-body\n                class=\"chat-msg__text ", " ", "\"\n                .model=\"", "\"\n                hide_url_previews=", "\n                ?is_me_message=", "\n                text=\"", "\"></converse-chat-message-body>\n            ", "\n            ", "\n        </span>\n        ", "\n        <div class=\"chat-msg__error\">", "</div>\n    "])), el.model.get('is_spoiler') ? tplSpoilerHint : '', el.model.get('subject') ? (0,external_lit_namespaceObject.html)(message_text_templateObject5 || (message_text_templateObject5 = message_text_taggedTemplateLiteral(["<div class=\"chat-msg__subject\">", "</div>"])), el.model.get('subject')) : '', el.model.get('is_only_emojis') ? 'chat-msg__text--larger' : '', spoiler_classes, el.model, el.model.get('hide_url_previews'), el.model.isMeCommand(), text, el.model.get('received') && !el.model.isMeCommand() && !is_groupchat_message ? tplCheckmark() : '', el.model.get('edited') ? tplEditedIcon(el) : '', show_oob ? (0,external_lit_namespaceObject.html)(message_text_templateObject6 || (message_text_templateObject6 = message_text_taggedTemplateLiteral(["<div class=\"chat-msg__media\">", "</div>"])), getOOBURLMarkup(el.model.get('oob_url'))) : '', el.model.get('error_text') || el.model.get('error'));
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/retraction.scss
var retraction = __webpack_require__(5382);
;// CONCATENATED MODULE: ./src/shared/chat/styles/retraction.scss

      
      
      
      
      
      
      
      
      

var retraction_options = {};

retraction_options.styleTagTransform = (styleTagTransform_default());
retraction_options.setAttributes = (setAttributesWithoutAttributes_default());

      retraction_options.insert = insertBySelector_default().bind(null, "head");
    
retraction_options.domAPI = (styleDomAPI_default());
retraction_options.insertStyleElement = (insertStyleElement_default());

var retraction_update = injectStylesIntoStyleTag_default()(retraction/* default */.Z, retraction_options);




       /* harmony default export */ const styles_retraction = (retraction/* default */.Z && retraction/* default */.Z.locals ? retraction/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/templates/retraction.js
var retraction_templateObject, retraction_templateObject2;
function retraction_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const templates_retraction = (function (el) {
  var retraction_text = el.isRetracted() ? el.getRetractionText() : null;
  return (0,external_lit_namespaceObject.html)(retraction_templateObject || (retraction_templateObject = retraction_taggedTemplateLiteral(["\n        <div class=\"retraction\">", "</div>\n        ", ""])), retraction_text, el.model.get('moderation_reason') ? (0,external_lit_namespaceObject.html)(retraction_templateObject2 || (retraction_templateObject2 = retraction_taggedTemplateLiteral(["<q class=\"chat-msg--retracted__reason\">", "</q>"])), el.model.get('moderation_reason')) : '');
});
;// CONCATENATED MODULE: ./src/shared/chat/message.js
function chat_message_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_message_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;
  }, chat_message_typeof(obj);
}
function chat_message_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chat_message_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" == chat_message_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 chat_message_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 chat_message_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chat_message_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chat_message_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function message_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_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, message_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_toPropertyKey(arg) {
  var key = message_toPrimitive(arg, "string");
  return chat_message_typeof(key) === "symbol" ? key : String(key);
}
function message_toPrimitive(input, hint) {
  if (chat_message_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chat_message_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_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) message_setPrototypeOf(subClass, superClass);
}
function message_setPrototypeOf(o, p) {
  message_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_setPrototypeOf(o, p);
}
function message_createSuper(Derived) {
  var hasNativeReflectConstruct = message_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_possibleConstructorReturn(this, result);
  };
}
function message_possibleConstructorReturn(self, call) {
  if (call && (chat_message_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 message_assertThisInitialized(self);
}
function message_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_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 message_getPrototypeOf(o) {
  message_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_getPrototypeOf(o);
}




















var chat_message_converse$env = public_converse.env,
  chat_message_Strophe = chat_message_converse$env.Strophe,
  message_dayjs = chat_message_converse$env.dayjs;
var Message = /*#__PURE__*/function (_CustomElement) {
  message_inherits(Message, _CustomElement);
  var _super = message_createSuper(Message);
  function Message() {
    message_classCallCheck(this, Message);
    return _super.apply(this, arguments);
  }
  message_createClass(Message, [{
    key: "initialize",
    value: function () {
      var _initialize = chat_message_asyncToGenerator( /*#__PURE__*/chat_message_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        var settings;
        return chat_message_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return this.setModels();
            case 2:
              if (this.model) {
                _context.next = 5;
                break;
              }
              // Happen during tests due to a race condition
              log.error('Could not find module for converse-chat-message');
              return _context.abrupt("return");
            case 5:
              settings = getAppSettings();
              this.listenTo(settings, 'change:render_media', function () {
                // Reset individual show/hide state of media
                _this.model.save('hide_url_previews', undefined);
                _this.requestUpdate();
              });
              this.listenTo(this.chatbox, 'change:first_unread_id', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change', function () {
                return _this.requestUpdate();
              });
              this.model.vcard && this.listenTo(this.model.vcard, 'change', function () {
                return _this.requestUpdate();
              });
              if (this.model.get('type') === 'groupchat') {
                if (this.model.occupant) {
                  this.listenTo(this.model.occupant, 'change', function () {
                    return _this.requestUpdate();
                  });
                } else {
                  this.listenTo(this.model, 'occupantAdded', function () {
                    _this.requestUpdate();
                    _this.listenTo(_this.model.occupant, 'change', function () {
                      return _this.requestUpdate();
                    });
                  });
                }
              }
            case 11:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "setModels",
    value: function () {
      var _setModels = chat_message_asyncToGenerator( /*#__PURE__*/chat_message_regeneratorRuntime().mark(function _callee2() {
        return chat_message_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return shared_api.chatboxes.get(this.jid);
            case 2:
              this.chatbox = _context2.sent;
              _context2.next = 5;
              return this.chatbox.initialized;
            case 5:
              _context2.next = 7;
              return this.chatbox.messages.fetched;
            case 7:
              this.model = this.chatbox.messages.get(this.mid);
              this.model && this.requestUpdate();
            case 9:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function setModels() {
        return _setModels.apply(this, arguments);
      }
      return setModels;
    }()
  }, {
    key: "render",
    value: function render() {
      if (!this.model) {
        return '';
      } else if (this.show_spinner) {
        return spinner();
      } else if (this.model.get('file') && this.model.get('upload') !== shared_converse.SUCCESS) {
        return this.renderFileProgress();
      } else if (['mep'].includes(this.model.get('type'))) {
        return this.renderMEPMessage();
      } else if (['error', 'info'].includes(this.model.get('type'))) {
        return this.renderInfoMessage();
      } else {
        return this.renderChatMessage();
      }
    }
  }, {
    key: "getProps",
    value: function getProps() {
      return Object.assign(this.model.toJSON(), this.getDerivedMessageProps());
    }
  }, {
    key: "renderRetraction",
    value: function renderRetraction() {
      return templates_retraction(this);
    }
  }, {
    key: "renderMessageText",
    value: function renderMessageText() {
      return message_text(this);
    }
  }, {
    key: "renderMEPMessage",
    value: function renderMEPMessage() {
      return mep_message(this);
    }
  }, {
    key: "renderInfoMessage",
    value: function renderInfoMessage() {
      return info_message(this);
    }
  }, {
    key: "renderFileProgress",
    value: function renderFileProgress() {
      if (!this.model.file) {
        // Can happen when file upload failed and page was reloaded
        return '';
      }
      return file_progress(this);
    }
  }, {
    key: "renderChatMessage",
    value: function renderChatMessage() {
      return templates_message(this, this.getProps());
    }
  }, {
    key: "shouldShowAvatar",
    value: function shouldShowAvatar() {
      return shared_api.settings.get('show_message_avatar') && !this.model.isMeCommand() && ['chat', 'groupchat', 'normal'].includes(this.model.get('type'));
    }
  }, {
    key: "onUnfurlAnimationEnd",
    value: function onUnfurlAnimationEnd() {
      if (this.model.get('url_preview_transition') === 'fade-out') {
        this.model.save({
          'hide_url_previews': true,
          'url_preview_transition': 'fade-in'
        });
      }
    }
  }, {
    key: "onRetryClicked",
    value: function () {
      var _onRetryClicked = chat_message_asyncToGenerator( /*#__PURE__*/chat_message_regeneratorRuntime().mark(function _callee3() {
        return chat_message_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              this.show_spinner = true;
              this.requestUpdate();
              _context3.next = 4;
              return shared_api.trigger(this.model.get('retry_event_id'), {
                'synchronous': true
              });
            case 4:
              this.model.destroy();
              this.parentElement.removeChild(this);
            case 6:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function onRetryClicked() {
        return _onRetryClicked.apply(this, arguments);
      }
      return onRetryClicked;
    }()
  }, {
    key: "isRetracted",
    value: function isRetracted() {
      return this.model.get('retracted') || this.model.get('moderated') === 'retracted';
    }
  }, {
    key: "hasMentions",
    value: function hasMentions() {
      var is_groupchat = this.model.get('type') === 'groupchat';
      return is_groupchat && this.model.get('sender') === 'them' && this.chatbox.isUserMentioned(this.model);
    }
  }, {
    key: "getOccupantAffiliation",
    value: function getOccupantAffiliation() {
      var _this$model$occupant;
      return (_this$model$occupant = this.model.occupant) === null || _this$model$occupant === void 0 ? void 0 : _this$model$occupant.get('affiliation');
    }
  }, {
    key: "getOccupantRole",
    value: function getOccupantRole() {
      var _this$model$occupant2;
      return (_this$model$occupant2 = this.model.occupant) === null || _this$model$occupant2 === void 0 ? void 0 : _this$model$occupant2.get('role');
    }
  }, {
    key: "getExtraMessageClasses",
    value: function getExtraMessageClasses() {
      var extra_classes = [this.model.isFollowup() ? 'chat-msg--followup' : null, this.model.get('is_delayed') ? 'delayed' : null, this.model.isMeCommand() ? 'chat-msg--action' : null, this.isRetracted() ? 'chat-msg--retracted' : null, this.model.get('type'), this.shouldShowAvatar() ? 'chat-msg--with-avatar' : null].map(function (c) {
        return c;
      });
      if (this.model.get('type') === 'groupchat') {
        var _this$getOccupantRole, _this$getOccupantAffi;
        extra_classes.push((_this$getOccupantRole = this.getOccupantRole()) !== null && _this$getOccupantRole !== void 0 ? _this$getOccupantRole : '');
        extra_classes.push((_this$getOccupantAffi = this.getOccupantAffiliation()) !== null && _this$getOccupantAffi !== void 0 ? _this$getOccupantAffi : '');
        if (this.model.get('sender') === 'them' && this.hasMentions()) {
          extra_classes.push('mentioned');
        }
      }
      this.model.get('correcting') && extra_classes.push('correcting');
      return extra_classes.filter(function (c) {
        return c;
      }).join(" ");
    }
  }, {
    key: "getDerivedMessageProps",
    value: function getDerivedMessageProps() {
      var format = shared_api.settings.get('time_format');
      return {
        'pretty_time': message_dayjs(this.model.get('edited') || this.model.get('time')).format(format),
        'has_mentions': this.hasMentions(),
        'hats': getHats(this.model),
        'is_first_unread': this.chatbox.get('first_unread_id') === this.model.get('id'),
        'is_me_message': this.model.isMeCommand(),
        'is_retracted': this.isRetracted(),
        'username': this.model.getDisplayName(),
        'should_show_avatar': this.shouldShowAvatar()
      };
    }
  }, {
    key: "getRetractionText",
    value: function getRetractionText() {
      if (['groupchat', 'mep'].includes(this.model.get('type')) && this.model.get('moderated_by')) {
        var retracted_by_mod = this.model.get('moderated_by');
        var chatbox = this.model.collection.chatbox;
        if (!this.model.mod) {
          this.model.mod = chatbox.occupants.findOccupant({
            'jid': retracted_by_mod
          }) || chatbox.occupants.findOccupant({
            'nick': chat_message_Strophe.getResourceFromJid(retracted_by_mod)
          });
        }
        var modname = this.model.mod ? this.model.mod.getDisplayName() : 'A moderator';
        return __('%1$s has removed this message', modname);
      } else {
        return __('%1$s has removed this message', this.model.getDisplayName());
      }
    }
  }, {
    key: "showUserModal",
    value: function showUserModal(ev) {
      if (this.model.get('sender') === 'me') {
        shared_api.modal.show('converse-profile-modal', {
          model: this.model
        }, ev);
      } else if (this.model.get('type') === 'groupchat') {
        ev.preventDefault();
        shared_api.modal.show('converse-muc-occupant-modal', {
          'model': this.model.getOccupant(),
          'message': this.model
        }, ev);
      } else {
        ev.preventDefault();
        var chatbox = this.model.collection.chatbox;
        shared_api.modal.show('converse-user-details-modal', {
          model: chatbox
        }, ev);
      }
    }
  }, {
    key: "showMessageVersionsModal",
    value: function showMessageVersionsModal(ev) {
      ev.preventDefault();
      shared_api.modal.show('converse-message-versions-modal', {
        'model': this.model
      }, ev);
    }
  }, {
    key: "toggleSpoilerMessage",
    value: function toggleSpoilerMessage(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      this.model.save({
        'is_spoiler_visible': !this.model.get('is_spoiler_visible')
      });
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        jid: {
          type: String
        },
        mid: {
          type: String
        }
      };
    }
  }]);
  return Message;
}(CustomElement);

shared_api.elements.define('converse-chat-message', Message);
;// CONCATENATED MODULE: ./src/shared/chat/message-history.js
function message_history_typeof(obj) {
  "@babel/helpers - typeof";

  return message_history_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;
  }, message_history_typeof(obj);
}
var message_history_templateObject, message_history_templateObject2;
function message_history_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function message_history_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_history_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, message_history_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_history_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_history_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_history_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_history_toPropertyKey(arg) {
  var key = message_history_toPrimitive(arg, "string");
  return message_history_typeof(key) === "symbol" ? key : String(key);
}
function message_history_toPrimitive(input, hint) {
  if (message_history_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_history_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_history_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) message_history_setPrototypeOf(subClass, superClass);
}
function message_history_setPrototypeOf(o, p) {
  message_history_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_history_setPrototypeOf(o, p);
}
function message_history_createSuper(Derived) {
  var hasNativeReflectConstruct = message_history_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_history_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_history_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_history_possibleConstructorReturn(this, result);
  };
}
function message_history_possibleConstructorReturn(self, call) {
  if (call && (message_history_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 message_history_assertThisInitialized(self);
}
function message_history_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_history_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 message_history_getPrototypeOf(o) {
  message_history_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_history_getPrototypeOf(o);
}







var MessageHistory = /*#__PURE__*/function (_CustomElement) {
  message_history_inherits(MessageHistory, _CustomElement);
  var _super = message_history_createSuper(MessageHistory);
  function MessageHistory() {
    message_history_classCallCheck(this, MessageHistory);
    return _super.apply(this, arguments);
  }
  message_history_createClass(MessageHistory, [{
    key: "render",
    value: function render() {
      var _this = this;
      var msgs = this.messages;
      if (msgs.length) {
        return repeat_c(msgs, function (m) {
          return m.get('id');
        }, function (m) {
          return (0,external_lit_namespaceObject.html)(message_history_templateObject || (message_history_templateObject = message_history_taggedTemplateLiteral(["", ""])), _this.renderMessage(m));
        });
      } else {
        return '';
      }
    }
  }, {
    key: "renderMessage",
    value: function renderMessage(model) {
      if (model.get('dangling_retraction') || model.get('is_only_key')) {
        return '';
      }
      var template_hook = model.get('template_hook');
      if (typeof template_hook === 'string') {
        var template_promise = shared_api.hook(template_hook, model, '');
        return until_m(template_promise, '');
      } else {
        var template = (0,external_lit_namespaceObject.html)(message_history_templateObject2 || (message_history_templateObject2 = message_history_taggedTemplateLiteral(["<converse-chat-message\n                jid=\"", "\"\n                mid=\"", "\"></converse-chat-message>"])), this.model.get('jid'), model.get('id'));
        var day = getDayIndicator(model);
        return day ? [day, template] : template;
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        model: {
          type: Object
        },
        messages: {
          type: Array
        }
      };
    }
  }]);
  return MessageHistory;
}(CustomElement);

shared_api.elements.define('converse-message-history', MessageHistory);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/chat-content.scss
var chat_content = __webpack_require__(7593);
;// CONCATENATED MODULE: ./src/shared/chat/styles/chat-content.scss

      
      
      
      
      
      
      
      
      

var chat_content_options = {};

chat_content_options.styleTagTransform = (styleTagTransform_default());
chat_content_options.setAttributes = (setAttributesWithoutAttributes_default());

      chat_content_options.insert = insertBySelector_default().bind(null, "head");
    
chat_content_options.domAPI = (styleDomAPI_default());
chat_content_options.insertStyleElement = (insertStyleElement_default());

var chat_content_update = injectStylesIntoStyleTag_default()(chat_content/* default */.Z, chat_content_options);




       /* harmony default export */ const styles_chat_content = (chat_content/* default */.Z && chat_content/* default */.Z.locals ? chat_content/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/chat-content.js
function chat_content_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_content_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;
  }, chat_content_typeof(obj);
}
var chat_content_templateObject;
function chat_content_toConsumableArray(arr) {
  return chat_content_arrayWithoutHoles(arr) || chat_content_iterableToArray(arr) || chat_content_unsupportedIterableToArray(arr) || chat_content_nonIterableSpread();
}
function chat_content_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function chat_content_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return chat_content_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 chat_content_arrayLikeToArray(o, minLen);
}
function chat_content_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function chat_content_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return chat_content_arrayLikeToArray(arr);
}
function chat_content_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 chat_content_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function chat_content_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chat_content_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" == chat_content_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 chat_content_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 chat_content_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chat_content_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chat_content_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function chat_content_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function chat_content_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, chat_content_toPropertyKey(descriptor.key), descriptor);
  }
}
function chat_content_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) chat_content_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) chat_content_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function chat_content_toPropertyKey(arg) {
  var key = chat_content_toPrimitive(arg, "string");
  return chat_content_typeof(key) === "symbol" ? key : String(key);
}
function chat_content_toPrimitive(input, hint) {
  if (chat_content_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chat_content_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function chat_content_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    chat_content_get = Reflect.get.bind();
  } else {
    chat_content_get = function _get(target, property, receiver) {
      var base = chat_content_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return chat_content_get.apply(this, arguments);
}
function chat_content_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = chat_content_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function chat_content_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) chat_content_setPrototypeOf(subClass, superClass);
}
function chat_content_setPrototypeOf(o, p) {
  chat_content_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return chat_content_setPrototypeOf(o, p);
}
function chat_content_createSuper(Derived) {
  var hasNativeReflectConstruct = chat_content_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = chat_content_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = chat_content_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return chat_content_possibleConstructorReturn(this, result);
  };
}
function chat_content_possibleConstructorReturn(self, call) {
  if (call && (chat_content_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 chat_content_assertThisInitialized(self);
}
function chat_content_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function chat_content_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 chat_content_getPrototypeOf(o) {
  chat_content_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return chat_content_getPrototypeOf(o);
}







var ChatContent = /*#__PURE__*/function (_CustomElement) {
  chat_content_inherits(ChatContent, _CustomElement);
  var _super = chat_content_createSuper(ChatContent);
  function ChatContent() {
    chat_content_classCallCheck(this, ChatContent);
    return _super.apply(this, arguments);
  }
  chat_content_createClass(ChatContent, [{
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      chat_content_get(chat_content_getPrototypeOf(ChatContent.prototype), "disconnectedCallback", this).call(this);
      this.removeEventListener('scroll', markScrolled);
    }
  }, {
    key: "initialize",
    value: function () {
      var _initialize = chat_content_asyncToGenerator( /*#__PURE__*/chat_content_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return chat_content_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return this.setModels();
            case 2:
              this.listenTo(this.model, 'change:hidden_occupants', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'rendered', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'reset', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.notifications, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.ui, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.ui, 'change:scrolled', this.scrollDown);
              if (this.model.occupants) {
                this.listenTo(this.model.occupants, 'change', function () {
                  return _this.requestUpdate();
                });
              }
              this.addEventListener('scroll', markScrolled);
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "setModels",
    value: function () {
      var _setModels = chat_content_asyncToGenerator( /*#__PURE__*/chat_content_regeneratorRuntime().mark(function _callee2() {
        return chat_content_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return shared_api.chatboxes.get(this.jid);
            case 2:
              this.model = _context2.sent;
              _context2.next = 5;
              return this.model.initialized;
            case 5:
              this.requestUpdate();
            case 6:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function setModels() {
        return _setModels.apply(this, arguments);
      }
      return setModels;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this$model$ui;
      if (!this.model) {
        return '';
      }
      // This element has "flex-direction: reverse", so elements here are
      // shown in reverse order.
      return (0,external_lit_namespaceObject.html)(chat_content_templateObject || (chat_content_templateObject = chat_content_taggedTemplateLiteral(["\n            <div class=\"chat-content__notifications\">", "</div>\n            <converse-message-history\n                .model=", "\n                .messages=", ">\n            </converse-message-history>\n            ", "\n        "])), this.model.getNotificationsText(), this.model, chat_content_toConsumableArray(this.model.messages.models), (_this$model$ui = this.model.ui) !== null && _this$model$ui !== void 0 && _this$model$ui.get('chat-content-spinner-top') ? spinner() : '');
    }
  }, {
    key: "scrollDown",
    value: function scrollDown() {
      if (this.model.ui.get('scrolled')) {
        return;
      }
      if (this.scrollTo) {
        var behavior = this.scrollTop ? 'smooth' : 'auto';
        this.scrollTo({
          'top': 0,
          behavior: behavior
        });
      } else {
        this.scrollTop = 0;
      }
      /**
       * Triggered once the converse-chat-content element has been scrolled down to the bottom.
       * @event _converse#chatBoxScrolledDown
       * @type {object}
       * @property { _converse.ChatBox | _converse.ChatRoom } chatbox - The chat model
       * @example _converse.api.listen.on('chatBoxScrolledDown', obj => { ... });
       */
      shared_api.trigger('chatBoxScrolledDown', {
        'chatbox': this.model
      });
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        jid: {
          type: String
        }
      };
    }
  }]);
  return ChatContent;
}(CustomElement);

shared_api.elements.define('converse-chat-content', ChatContent);
;// CONCATENATED MODULE: ./node_modules/lit/node_modules/lit-html/directives/unsafe-html.js
function unsafe_html_typeof(obj) {
  "@babel/helpers - typeof";

  return unsafe_html_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;
  }, unsafe_html_typeof(obj);
}
function unsafe_html_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function unsafe_html_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, unsafe_html_toPropertyKey(descriptor.key), descriptor);
  }
}
function unsafe_html_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) unsafe_html_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) unsafe_html_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function unsafe_html_toPropertyKey(arg) {
  var key = unsafe_html_toPrimitive(arg, "string");
  return unsafe_html_typeof(key) === "symbol" ? key : String(key);
}
function unsafe_html_toPrimitive(input, hint) {
  if (unsafe_html_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (unsafe_html_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function unsafe_html_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) unsafe_html_setPrototypeOf(subClass, superClass);
}
function unsafe_html_setPrototypeOf(o, p) {
  unsafe_html_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return unsafe_html_setPrototypeOf(o, p);
}
function unsafe_html_createSuper(Derived) {
  var hasNativeReflectConstruct = unsafe_html_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = unsafe_html_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = unsafe_html_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return unsafe_html_possibleConstructorReturn(this, result);
  };
}
function unsafe_html_possibleConstructorReturn(self, call) {
  if (call && (unsafe_html_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 unsafe_html_assertThisInitialized(self);
}
function unsafe_html_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function unsafe_html_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 unsafe_html_getPrototypeOf(o) {
  unsafe_html_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return unsafe_html_getPrototypeOf(o);
}


/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
var unsafe_html_e = /*#__PURE__*/function (_r) {
  unsafe_html_inherits(e, _r);
  var _super = unsafe_html_createSuper(e);
  function e(i) {
    var _this;
    unsafe_html_classCallCheck(this, e);
    if (_this = _super.call(this, i), _this.it = E, i.type !== directive_t.CHILD) throw Error(_this.constructor.directiveName + "() can only be used in child bindings");
    return unsafe_html_possibleConstructorReturn(_this);
  }
  unsafe_html_createClass(e, [{
    key: "render",
    value: function render(r) {
      if (r === E || null == r) return this._t = void 0, this.it = r;
      if (r === T) return r;
      if ("string" != typeof r) throw Error(this.constructor.directiveName + "() called with a non-string value");
      if (r === this.it) return this._t;
      this.it = r;
      var s = [r];
      return s.raw = s, this._t = {
        _$litType$: this.constructor.resultType,
        strings: s,
        values: []
      };
    }
  }]);
  return e;
}(directive_i);
unsafe_html_e.directiveName = "unsafeHTML", unsafe_html_e.resultType = 1;
var unsafe_html_o = directive_e(unsafe_html_e);

;// CONCATENATED MODULE: ./node_modules/lit/directives/unsafe-html.js

;// CONCATENATED MODULE: ./src/shared/chat/help-messages.js
function help_messages_typeof(obj) {
  "@babel/helpers - typeof";

  return help_messages_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;
  }, help_messages_typeof(obj);
}
var help_messages_templateObject, help_messages_templateObject2;
function help_messages_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function help_messages_toConsumableArray(arr) {
  return help_messages_arrayWithoutHoles(arr) || help_messages_iterableToArray(arr) || help_messages_unsupportedIterableToArray(arr) || help_messages_nonIterableSpread();
}
function help_messages_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function help_messages_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return help_messages_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 help_messages_arrayLikeToArray(o, minLen);
}
function help_messages_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function help_messages_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return help_messages_arrayLikeToArray(arr);
}
function help_messages_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 help_messages_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function help_messages_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, help_messages_toPropertyKey(descriptor.key), descriptor);
  }
}
function help_messages_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) help_messages_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) help_messages_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function help_messages_toPropertyKey(arg) {
  var key = help_messages_toPrimitive(arg, "string");
  return help_messages_typeof(key) === "symbol" ? key : String(key);
}
function help_messages_toPrimitive(input, hint) {
  if (help_messages_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (help_messages_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function help_messages_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) help_messages_setPrototypeOf(subClass, superClass);
}
function help_messages_setPrototypeOf(o, p) {
  help_messages_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return help_messages_setPrototypeOf(o, p);
}
function help_messages_createSuper(Derived) {
  var hasNativeReflectConstruct = help_messages_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = help_messages_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = help_messages_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return help_messages_possibleConstructorReturn(this, result);
  };
}
function help_messages_possibleConstructorReturn(self, call) {
  if (call && (help_messages_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 help_messages_assertThisInitialized(self);
}
function help_messages_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function help_messages_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 help_messages_getPrototypeOf(o) {
  help_messages_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return help_messages_getPrototypeOf(o);
}






var ChatHelp = /*#__PURE__*/function (_CustomElement) {
  help_messages_inherits(ChatHelp, _CustomElement);
  var _super = help_messages_createSuper(ChatHelp);
  function ChatHelp() {
    help_messages_classCallCheck(this, ChatHelp);
    return _super.apply(this, arguments);
  }
  help_messages_createClass(ChatHelp, [{
    key: "render",
    value: function render() {
      var _this = this;
      var isodate = new Date().toISOString();
      return [(0,external_lit_namespaceObject.html)(help_messages_templateObject || (help_messages_templateObject = help_messages_taggedTemplateLiteral(["<converse-icon class=\"fas fa-times close-chat-help\"\n                    @click=", "\n                    path-prefix=\"", "\"\n                    size=\"1em\"></converse-icon>"])), this.close, shared_api.settings.get("assets_path"))].concat(help_messages_toConsumableArray(this.messages.map(function (m) {
        return _this.renderHelpMessage({
          isodate: isodate,
          'markup': purify_default().sanitize(m, {
            'ALLOWED_TAGS': ['strong']
          })
        });
      })));
    }
  }, {
    key: "close",
    value: function close() {
      this.model.set({
        'show_help_messages': false
      });
    }
  }, {
    key: "renderHelpMessage",
    value: function renderHelpMessage(o) {
      return (0,external_lit_namespaceObject.html)(help_messages_templateObject2 || (help_messages_templateObject2 = help_messages_taggedTemplateLiteral(["<div class=\"message chat-", "\" data-isodate=\"", "\">", "</div>"])), this.type, o.isodate, unsafe_html_o(o.markup));
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        chat_type: {
          type: String
        },
        messages: {
          type: Array
        },
        model: {
          type: Object
        },
        type: {
          type: String
        }
      };
    }
  }]);
  return ChatHelp;
}(CustomElement);

shared_api.elements.define('converse-chat-help', ChatHelp);
;// CONCATENATED MODULE: ./src/shared/chat/templates/emoji-picker.js
var emoji_picker_templateObject, emoji_picker_templateObject2, emoji_picker_templateObject3, emoji_picker_templateObject4, emoji_picker_templateObject5, emoji_picker_templateObject6, emoji_picker_templateObject7, emoji_picker_templateObject8, emoji_picker_templateObject9;
function emoji_picker_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



var emoji_picker_u = public_converse.env.utils;
var emoji_category = function emoji_category(o) {
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject || (emoji_picker_templateObject = emoji_picker_taggedTemplateLiteral(["\n        <li data-category=\"", "\"\n            class=\"emoji-category ", " ", "\"\n            title=\"", "\">\n\n            <a class=\"pick-category\"\n               @click=", "\n               href=\"#emoji-picker-", "\"\n               data-category=\"", "\">", " </a>\n        </li>\n    "])), o.category, o.category, o.current_category === o.category ? 'picked' : '', __(shared_api.settings.get('emoji_category_labels')[o.category]), o.onCategoryPicked, o.category, o.category, o.emoji);
};
var emoji_picker_header = function emoji_picker_header(o) {
  var cats = shared_api.settings.get('emoji_categories');
  var transform = function transform(c) {
    return cats[c] ? emoji_category(Object.assign({
      'category': c,
      'emoji': o.sn2Emoji(cats[c])
    }, o)) : '';
  };
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject2 || (emoji_picker_templateObject2 = emoji_picker_taggedTemplateLiteral(["<ul>", "</ul>"])), Object.keys(cats).map(transform));
};
var emoji_item = function emoji_item(o) {
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject3 || (emoji_picker_templateObject3 = emoji_picker_taggedTemplateLiteral(["\n        <li class=\"emoji insert-emoji ", "\" data-emoji=\"", "\" title=\"", "\">\n            <a href=\"#\" @click=", " data-emoji=\"", "\">", "</a>\n        </li>\n    "])), o.shouldBeHidden(o.emoji.sn) ? 'hidden' : '', o.emoji.sn, o.emoji.sn, o.insertEmoji, o.emoji.sn, emoji_picker_u.shortnamesToEmojis(o.emoji.sn));
};
var tplSearchResults = function tplSearchResults(o) {
  var i18n_search_results = __('Search results');
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject4 || (emoji_picker_templateObject4 = emoji_picker_taggedTemplateLiteral(["\n        <span ?hidden=", " class=\"emoji-lists__container emojis-lists__container--search\">\n        <a id=\"emoji-picker-search-results\" class=\"emoji-category__heading\">", "</a>\n        <ul class=\"emoji-picker\">\n            ", "\n        </ul>\n        </span>\n    "])), !o.query, i18n_search_results, o.search_results.map(function (emoji) {
    return emoji_item(Object.assign({
      emoji: emoji
    }, o));
  }));
};
var emojis_for_category = function emojis_for_category(o) {
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject5 || (emoji_picker_templateObject5 = emoji_picker_taggedTemplateLiteral(["\n        <a id=\"emoji-picker-", "\" class=\"emoji-category__heading\" data-category=\"", "\">", "</a>\n        <ul class=\"emoji-picker\" data-category=\"", "\">\n            ", "\n        </ul>"])), o.category, o.category, __(shared_api.settings.get('emoji_category_labels')[o.category]), o.category, Object.values(public_converse.emojis.json[o.category]).map(function (emoji) {
    return emoji_item(Object.assign({
      emoji: emoji
    }, o));
  }));
};
var tplAllEmojis = function tplAllEmojis(o) {
  var cats = shared_api.settings.get('emoji_categories');
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject6 || (emoji_picker_templateObject6 = emoji_picker_taggedTemplateLiteral(["\n        <span ?hidden=", " class=\"emoji-lists__container emoji-lists__container--browse\">\n            ", "\n        </span>"])), o.query, Object.keys(cats).map(function (c) {
    return cats[c] ? emojis_for_category(Object.assign({
      'category': c
    }, o)) : '';
  }));
};
var skintone_emoji = function skintone_emoji(o) {
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject7 || (emoji_picker_templateObject7 = emoji_picker_taggedTemplateLiteral(["\n        <li data-skintone=\"", "\" class=\"emoji-skintone ", "\">\n            <a class=\"pick-skintone\" href=\"#\" data-skintone=\"", "\" @click=", ">", "</a>\n        </li>"])), o.skintone, o.current_skintone === o.skintone ? 'picked' : '', o.skintone, o.onSkintonePicked, emoji_picker_u.shortnamesToEmojis(':' + o.skintone + ':'));
};
var tplEmojiPicker = function tplEmojiPicker(o) {
  var i18n_search = __('Search');
  var skintones = ['tone1', 'tone2', 'tone3', 'tone4', 'tone5'];
  return (0,external_lit_namespaceObject.html)(emoji_picker_templateObject8 || (emoji_picker_templateObject8 = emoji_picker_taggedTemplateLiteral(["\n        <div class=\"emoji-picker__header\">\n            <input class=\"form-control emoji-search\" name=\"emoji-search\" placeholder=\"", "\"\n                .value=", "\n                @keydown=", "\n                @blur=", "\n                @focus=", ">\n            ", "\n        </div>\n        ", "\n\n        <div class=\"emoji-skintone-picker\">\n            <ul>", "</ul>\n        </div>"])), i18n_search, o.query || '', o.onSearchInputKeyDown, o.onSearchInputBlurred, o.onSearchInputFocus, o.query ? '' : emoji_picker_header(o), o.render_emojis ? (0,external_lit_namespaceObject.html)(emoji_picker_templateObject9 || (emoji_picker_templateObject9 = emoji_picker_taggedTemplateLiteral(["<converse-emoji-picker-content\n                .chatview=", "\n                .model=", "\n                .search_results=\"", "\"\n                current_skintone=\"", "\"\n                query=\"", "\"></converse-emoji-picker-content>"])), o.chatview, o.model, o.search_results, o.current_skintone, o.query) : '', skintones.map(function (skintone) {
    return skintone_emoji(Object.assign({
      skintone: skintone
    }, o));
  }));
};
;// CONCATENATED MODULE: ./src/shared/chat/emoji-picker-content.js
function emoji_picker_content_typeof(obj) {
  "@babel/helpers - typeof";

  return emoji_picker_content_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;
  }, emoji_picker_content_typeof(obj);
}
var emoji_picker_content_templateObject;
function emoji_picker_content_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function emoji_picker_content_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function emoji_picker_content_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, emoji_picker_content_toPropertyKey(descriptor.key), descriptor);
  }
}
function emoji_picker_content_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) emoji_picker_content_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) emoji_picker_content_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function emoji_picker_content_toPropertyKey(arg) {
  var key = emoji_picker_content_toPrimitive(arg, "string");
  return emoji_picker_content_typeof(key) === "symbol" ? key : String(key);
}
function emoji_picker_content_toPrimitive(input, hint) {
  if (emoji_picker_content_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (emoji_picker_content_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function emoji_picker_content_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) emoji_picker_content_setPrototypeOf(subClass, superClass);
}
function emoji_picker_content_setPrototypeOf(o, p) {
  emoji_picker_content_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return emoji_picker_content_setPrototypeOf(o, p);
}
function emoji_picker_content_createSuper(Derived) {
  var hasNativeReflectConstruct = emoji_picker_content_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = emoji_picker_content_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = emoji_picker_content_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return emoji_picker_content_possibleConstructorReturn(this, result);
  };
}
function emoji_picker_content_possibleConstructorReturn(self, call) {
  if (call && (emoji_picker_content_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 emoji_picker_content_assertThisInitialized(self);
}
function emoji_picker_content_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function emoji_picker_content_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 emoji_picker_content_getPrototypeOf(o) {
  emoji_picker_content_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return emoji_picker_content_getPrototypeOf(o);
}





var emoji_picker_content_sizzle = public_converse.env.sizzle;
var EmojiPickerContent = /*#__PURE__*/function (_CustomElement) {
  emoji_picker_content_inherits(EmojiPickerContent, _CustomElement);
  var _super = emoji_picker_content_createSuper(EmojiPickerContent);
  function EmojiPickerContent() {
    emoji_picker_content_classCallCheck(this, EmojiPickerContent);
    return _super.apply(this, arguments);
  }
  emoji_picker_content_createClass(EmojiPickerContent, [{
    key: "render",
    value: function render() {
      var _this = this;
      var props = {
        'current_skintone': this.current_skintone,
        'insertEmoji': function insertEmoji(ev) {
          return _this.insertEmoji(ev);
        },
        'query': this.query,
        'search_results': this.search_results,
        'shouldBeHidden': function shouldBeHidden(shortname) {
          return _this.shouldBeHidden(shortname);
        }
      };
      return (0,external_lit_namespaceObject.html)(emoji_picker_content_templateObject || (emoji_picker_content_templateObject = emoji_picker_content_taggedTemplateLiteral(["\n          <div class=\"emoji-picker__lists\">\n              ", "\n              ", "\n          </div>\n      "])), tplSearchResults(props), tplAllEmojis(props));
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      this.initIntersectionObserver();
    }
  }, {
    key: "initIntersectionObserver",
    value: function initIntersectionObserver() {
      var _this2 = this;
      if (!window.IntersectionObserver) {
        return;
      }
      if (this.observer) {
        this.observer.disconnect();
      } else {
        var options = {
          root: this.querySelector('.emoji-picker__lists'),
          threshold: [0.1]
        };
        var handler = function handler(ev) {
          return _this2.setCategoryOnVisibilityChange(ev);
        };
        this.observer = new IntersectionObserver(handler, options);
      }
      emoji_picker_content_sizzle('.emoji-picker', this).forEach(function (a) {
        return _this2.observer.observe(a);
      });
    }
  }, {
    key: "setCategoryOnVisibilityChange",
    value: function setCategoryOnVisibilityChange(entries) {
      var selected = this.parentElement.navigator.selected;
      var intersection_with_selected = entries.filter(function (i) {
        return i.target.contains(selected);
      }).pop();
      var current;
      // Choose the intersection that contains the currently selected
      // element, or otherwise the one with the largest ratio.
      if (intersection_with_selected) {
        current = intersection_with_selected;
      } else {
        current = entries.reduce(function (p, c) {
          return c.intersectionRatio >= ((p === null || p === void 0 ? void 0 : p.intersectionRatio) || 0) ? c : p;
        }, null);
      }
      if (current && current.isIntersecting) {
        var category = current.target.getAttribute('data-category');
        if (category !== this.model.get('current_category')) {
          this.parentElement.preserve_scroll = true;
          this.model.save({
            'current_category': category
          });
        }
      }
    }
  }, {
    key: "insertEmoji",
    value: function insertEmoji(ev) {
      ev.preventDefault();
      ev.stopPropagation();
      var target = ev.target.nodeName === 'IMG' ? ev.target.parentElement : ev.target;
      this.parentElement.insertIntoTextArea(target.getAttribute('data-emoji'));
    }
  }, {
    key: "shouldBeHidden",
    value: function shouldBeHidden(shortname) {
      // Helper method for the template which decides whether an
      // emoji should be hidden, based on which skin tone is
      // currently being applied.
      if (shortname.includes('_tone')) {
        if (!this.current_skintone || !shortname.includes(this.current_skintone)) {
          return true;
        }
      } else {
        if (this.current_skintone && getTonedEmojis().includes(shortname)) {
          return true;
        }
      }
      if (this.query && !shared_converse.FILTER_CONTAINS(shortname, this.query)) {
        return true;
      }
      return false;
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'chatview': {
          type: Object
        },
        'search_results': {
          type: Array
        },
        'current_skintone': {
          type: String
        },
        'model': {
          type: Object
        },
        'query': {
          type: String
        }
      };
    }
  }]);
  return EmojiPickerContent;
}(CustomElement);

shared_api.elements.define('converse-emoji-picker-content', EmojiPickerContent);
;// CONCATENATED MODULE: ./src/shared/chat/emoji-dropdown.js
function emoji_dropdown_typeof(obj) {
  "@babel/helpers - typeof";

  return emoji_dropdown_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;
  }, emoji_dropdown_typeof(obj);
}
var emoji_dropdown_templateObject, emoji_dropdown_templateObject2;
function emoji_dropdown_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function emoji_dropdown_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  emoji_dropdown_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" == emoji_dropdown_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 emoji_dropdown_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 emoji_dropdown_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        emoji_dropdown_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        emoji_dropdown_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function emoji_dropdown_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function emoji_dropdown_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, emoji_dropdown_toPropertyKey(descriptor.key), descriptor);
  }
}
function emoji_dropdown_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) emoji_dropdown_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) emoji_dropdown_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function emoji_dropdown_toPropertyKey(arg) {
  var key = emoji_dropdown_toPrimitive(arg, "string");
  return emoji_dropdown_typeof(key) === "symbol" ? key : String(key);
}
function emoji_dropdown_toPrimitive(input, hint) {
  if (emoji_dropdown_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (emoji_dropdown_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function emoji_dropdown_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    emoji_dropdown_get = Reflect.get.bind();
  } else {
    emoji_dropdown_get = function _get(target, property, receiver) {
      var base = emoji_dropdown_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return emoji_dropdown_get.apply(this, arguments);
}
function emoji_dropdown_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = emoji_dropdown_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function emoji_dropdown_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) emoji_dropdown_setPrototypeOf(subClass, superClass);
}
function emoji_dropdown_setPrototypeOf(o, p) {
  emoji_dropdown_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return emoji_dropdown_setPrototypeOf(o, p);
}
function emoji_dropdown_createSuper(Derived) {
  var hasNativeReflectConstruct = emoji_dropdown_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = emoji_dropdown_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = emoji_dropdown_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return emoji_dropdown_possibleConstructorReturn(this, result);
  };
}
function emoji_dropdown_possibleConstructorReturn(self, call) {
  if (call && (emoji_dropdown_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 emoji_dropdown_assertThisInitialized(self);
}
function emoji_dropdown_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function emoji_dropdown_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 emoji_dropdown_getPrototypeOf(o) {
  emoji_dropdown_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return emoji_dropdown_getPrototypeOf(o);
}






var emoji_dropdown_u = public_converse.env.utils;
var EmojiDropdown = /*#__PURE__*/function (_DropdownBase) {
  emoji_dropdown_inherits(EmojiDropdown, _DropdownBase);
  var _super = emoji_dropdown_createSuper(EmojiDropdown);
  function EmojiDropdown() {
    var _this;
    emoji_dropdown_classCallCheck(this, EmojiDropdown);
    _this = _super.call(this);
    // This is an optimization, we lazily render the emoji picker, otherwise tests slow to a crawl.
    _this.render_emojis = false;
    return _this;
  }
  emoji_dropdown_createClass(EmojiDropdown, [{
    key: "initModel",
    value: function initModel() {
      var _this2 = this;
      if (!this.init_promise) {
        this.init_promise = emoji_dropdown_asyncToGenerator( /*#__PURE__*/emoji_dropdown_regeneratorRuntime().mark(function _callee() {
          var id;
          return emoji_dropdown_regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return shared_api.emojis.initialize();
              case 2:
                id = "converse.emoji-".concat(shared_converse.bare_jid, "-").concat(_this2.chatview.model.get('jid'));
                _this2.model = new shared_converse.EmojiPicker({
                  'id': id
                });
                initStorage(_this2.model, id);
                _context.next = 7;
                return new Promise(function (resolve) {
                  return _this2.model.fetch({
                    'success': resolve,
                    'error': resolve
                  });
                });
              case 7:
                // We never want still be in the autocompleting state upon page load
                _this2.model.set({
                  'autocompleting': null,
                  'ac_position': null
                });
              case 8:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }))();
      }
      return this.init_promise;
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      var is_groupchat = this.chatview.model.get('type') === shared_converse.CHATROOMS_TYPE;
      var color = is_groupchat ? '--muc-toolbar-btn-color' : '--chat-toolbar-btn-color';
      return (0,external_lit_namespaceObject.html)(emoji_dropdown_templateObject || (emoji_dropdown_templateObject = emoji_dropdown_taggedTemplateLiteral(["\n            <div class=\"dropup\">\n                <button class=\"toggle-emojis\"\n                        title=\"", "\"\n                        data-toggle=\"dropdown\"\n                        aria-haspopup=\"true\"\n                        aria-expanded=\"false\">\n                    <converse-icon\n                        color=\"var(", ")\"\n                        class=\"fa fa-smile \"\n                        path-prefix=\"", "\"\n                        size=\"1em\"></converse-icon>\n                </button>\n                <div class=\"dropdown-menu\">\n                    ", "\n                </div>\n            </div>"])), __('Insert emojis'), color, shared_api.settings.get('assets_path'), until_m(this.initModel().then(function () {
        return (0,external_lit_namespaceObject.html)(emoji_dropdown_templateObject2 || (emoji_dropdown_templateObject2 = emoji_dropdown_taggedTemplateLiteral(["\n                        <converse-emoji-picker\n                                .chatview=", "\n                                .model=", "\n                                @emojiSelected=", "\n                                ?render_emojis=", "\n                                current_category=\"", "\"\n                                current_skintone=\"", "\"\n                                query=\"", "\"\n                        ></converse-emoji-picker>"])), _this3.chatview, _this3.model, function () {
          return _this3.hideMenu();
        }, _this3.render_emojis, _this3.model.get('current_category') || '', _this3.model.get('current_skintone') || '', _this3.model.get('query') || '');
      }), ''));
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      emoji_dropdown_get(emoji_dropdown_getPrototypeOf(EmojiDropdown.prototype), "connectedCallback", this).call(this);
      this.render_emojis = false;
    }
  }, {
    key: "toggleMenu",
    value: function toggleMenu(ev) {
      ev.stopPropagation();
      ev.preventDefault();
      if (emoji_dropdown_u.hasClass('show', this.menu)) {
        if (emoji_dropdown_u.ancestor(ev.target, '.toggle-emojis')) {
          this.hideMenu();
        }
      } else {
        this.showMenu();
      }
    }
  }, {
    key: "showMenu",
    value: function () {
      var _showMenu = emoji_dropdown_asyncToGenerator( /*#__PURE__*/emoji_dropdown_regeneratorRuntime().mark(function _callee2() {
        var _this4 = this;
        return emoji_dropdown_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return this.initModel();
            case 2:
              if (this.render_emojis) {
                _context2.next = 7;
                break;
              }
              // Trigger an update so that emojis are rendered
              this.render_emojis = true;
              this.requestUpdate();
              _context2.next = 7;
              return this.updateComplete;
            case 7:
              emoji_dropdown_get(emoji_dropdown_getPrototypeOf(EmojiDropdown.prototype), "showMenu", this).call(this);
              setTimeout(function () {
                var _this4$querySelector;
                return (_this4$querySelector = _this4.querySelector('.emoji-search')) === null || _this4$querySelector === void 0 ? void 0 : _this4$querySelector.focus();
              });
            case 9:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function showMenu() {
        return _showMenu.apply(this, arguments);
      }
      return showMenu;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        chatview: {
          type: Object
        }
      };
    }
  }]);
  return EmojiDropdown;
}(Dropdown);

shared_api.elements.define('converse-emoji-dropdown', EmojiDropdown);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/emoji.scss
var emoji = __webpack_require__(2543);
;// CONCATENATED MODULE: ./src/shared/chat/styles/emoji.scss

      
      
      
      
      
      
      
      
      

var emoji_options = {};

emoji_options.styleTagTransform = (styleTagTransform_default());
emoji_options.setAttributes = (setAttributesWithoutAttributes_default());

      emoji_options.insert = insertBySelector_default().bind(null, "head");
    
emoji_options.domAPI = (styleDomAPI_default());
emoji_options.insertStyleElement = (insertStyleElement_default());

var emoji_update = injectStylesIntoStyleTag_default()(emoji/* default */.Z, emoji_options);




       /* harmony default export */ const styles_emoji = (emoji/* default */.Z && emoji/* default */.Z.locals ? emoji/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/emoji-picker.js
function emoji_picker_typeof(obj) {
  "@babel/helpers - typeof";

  return emoji_picker_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;
  }, emoji_picker_typeof(obj);
}
function emoji_picker_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function emoji_picker_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, emoji_picker_toPropertyKey(descriptor.key), descriptor);
  }
}
function emoji_picker_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) emoji_picker_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) emoji_picker_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function emoji_picker_toPropertyKey(arg) {
  var key = emoji_picker_toPrimitive(arg, "string");
  return emoji_picker_typeof(key) === "symbol" ? key : String(key);
}
function emoji_picker_toPrimitive(input, hint) {
  if (emoji_picker_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (emoji_picker_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function emoji_picker_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) emoji_picker_setPrototypeOf(subClass, superClass);
}
function emoji_picker_setPrototypeOf(o, p) {
  emoji_picker_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return emoji_picker_setPrototypeOf(o, p);
}
function emoji_picker_createSuper(Derived) {
  var hasNativeReflectConstruct = emoji_picker_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = emoji_picker_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = emoji_picker_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return emoji_picker_possibleConstructorReturn(this, result);
  };
}
function emoji_picker_possibleConstructorReturn(self, call) {
  if (call && (emoji_picker_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 emoji_picker_assertThisInitialized(self);
}
function emoji_picker_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function emoji_picker_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 emoji_picker_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    emoji_picker_get = Reflect.get.bind();
  } else {
    emoji_picker_get = function _get(target, property, receiver) {
      var base = emoji_picker_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return emoji_picker_get.apply(this, arguments);
}
function emoji_picker_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = emoji_picker_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function emoji_picker_getPrototypeOf(o) {
  emoji_picker_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return emoji_picker_getPrototypeOf(o);
}










var chat_emoji_picker_u = public_converse.env.utils;
var EmojiPicker = /*#__PURE__*/function (_CustomElement) {
  emoji_picker_inherits(EmojiPicker, _CustomElement);
  var _super = emoji_picker_createSuper(EmojiPicker);
  function EmojiPicker() {
    var _this;
    emoji_picker_classCallCheck(this, EmojiPicker);
    _this = _super.call(this);
    _this.query = '';
    _this._search_results = [];
    _this.debouncedFilter = lodash_es_debounce(function (input) {
      return _this.model.set({
        'query': input.value
      });
    }, 250);
    return _this;
  }
  emoji_picker_createClass(EmojiPicker, [{
    key: "firstUpdated",
    value: function firstUpdated() {
      var _this2 = this;
      emoji_picker_get(emoji_picker_getPrototypeOf(EmojiPicker.prototype), "firstUpdated", this).call(this);
      this.listenTo(this.model, 'change', function (o) {
        return _this2.onModelChanged(o.changed);
      });
      this.initArrowNavigation();
    }
  }, {
    key: "search_results",
    get: function get() {
      return this._search_results;
    },
    set: function set(value) {
      this._search_results = value;
      this.requestUpdate();
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      return tplEmojiPicker({
        'chatview': this.chatview,
        'current_category': this.current_category,
        'current_skintone': this.current_skintone,
        'model': this.model,
        'onCategoryPicked': function onCategoryPicked(ev) {
          return _this3.chooseCategory(ev);
        },
        'onSearchInputBlurred': function onSearchInputBlurred(ev) {
          return _this3.chatview.emitFocused(ev);
        },
        'onSearchInputFocus': function onSearchInputFocus(ev) {
          return _this3.onSearchInputFocus(ev);
        },
        'onSearchInputKeyDown': function onSearchInputKeyDown(ev) {
          return _this3.onSearchInputKeyDown(ev);
        },
        'onSkintonePicked': function onSkintonePicked(ev) {
          return _this3.chooseSkinTone(ev);
        },
        'query': this.query,
        'search_results': this.search_results,
        'render_emojis': this.render_emojis,
        'sn2Emoji': function sn2Emoji(shortname) {
          return chat_emoji_picker_u.shortnamesToEmojis(_this3.getTonedShortname(shortname));
        }
      });
    }
  }, {
    key: "updated",
    value: function updated(changed) {
      changed.has('query') && this.updateSearchResults(changed);
      changed.has('current_category') && this.setScrollPosition();
    }
  }, {
    key: "onModelChanged",
    value: function onModelChanged(changed) {
      if ('current_category' in changed) this.current_category = changed.current_category;
      if ('current_skintone' in changed) this.current_skintone = changed.current_skintone;
      if ('query' in changed) this.query = changed.query;
    }
  }, {
    key: "setScrollPosition",
    value: function setScrollPosition() {
      if (this.preserve_scroll) {
        this.preserve_scroll = false;
        return;
      }
      var el = this.querySelector('.emoji-lists__container--browse');
      var heading = this.querySelector("#emoji-picker-".concat(this.current_category));
      if (heading) {
        // +4 due to 2px padding on list elements
        el.scrollTop = heading.offsetTop - heading.offsetHeight * 3 + 4;
      }
    }
  }, {
    key: "updateSearchResults",
    value: function updateSearchResults(changed) {
      var _this4 = this;
      var old_query = changed.get('query');
      var contains = shared_converse.FILTER_CONTAINS;
      if (this.query) {
        if (this.query === old_query) {
          return this.search_results;
        } else if (old_query && this.query.includes(old_query)) {
          this.search_results = this.search_results.filter(function (e) {
            return contains(e.sn, _this4.query);
          });
        } else {
          this.search_results = public_converse.emojis.list.filter(function (e) {
            return contains(e.sn, _this4.query);
          });
        }
      } else if (this.search_results.length) {
        // Avoid re-rendering by only setting to new empty array if it wasn't empty before
        this.search_results = [];
      }
    }
  }, {
    key: "registerEvents",
    value: function registerEvents() {
      var _this5 = this;
      this.onGlobalKeyDown = function (ev) {
        return _this5._onGlobalKeyDown(ev);
      };
      var body = document.querySelector('body');
      body.addEventListener('keydown', this.onGlobalKeyDown);
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      emoji_picker_get(emoji_picker_getPrototypeOf(EmojiPicker.prototype), "connectedCallback", this).call(this);
      this.registerEvents();
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      var body = document.querySelector('body');
      body.removeEventListener('keydown', this.onGlobalKeyDown);
      this.disableArrowNavigation();
      emoji_picker_get(emoji_picker_getPrototypeOf(EmojiPicker.prototype), "disconnectedCallback", this).call(this);
    }
  }, {
    key: "_onGlobalKeyDown",
    value: function _onGlobalKeyDown(ev) {
      var _this6 = this;
      if (!this.navigator) {
        return;
      }
      if (ev.keyCode === KEYCODES.ENTER && chat_emoji_picker_u.isVisible(this)) {
        this.onEnterPressed(ev);
      } else if (ev.keyCode === KEYCODES.DOWN_ARROW && !this.navigator.enabled && chat_emoji_picker_u.isVisible(this)) {
        this.enableArrowNavigation(ev);
      } else if (ev.keyCode === KEYCODES.ESCAPE) {
        this.disableArrowNavigation();
        setTimeout(function () {
          return _this6.chatview.querySelector('.chat-textarea').focus();
        }, 50);
      }
    }
  }, {
    key: "setCategoryForElement",
    value: function setCategoryForElement(el) {
      var old_category = this.current_category;
      var category = (el === null || el === void 0 ? void 0 : el.getAttribute('data-category')) || old_category;
      if (old_category !== category) {
        this.model.save({
          'current_category': category
        });
      }
    }
  }, {
    key: "insertIntoTextArea",
    value: function insertIntoTextArea(value) {
      var autocompleting = this.model.get('autocompleting');
      var ac_position = this.model.get('ac_position');
      this.model.set({
        'autocompleting': null,
        'query': '',
        'ac_position': null
      });
      this.disableArrowNavigation();
      var jid = this.chatview.model.get('jid');
      var options = {
        'bubbles': true,
        'detail': {
          value: value,
          autocompleting: autocompleting,
          ac_position: ac_position,
          jid: jid
        }
      };
      this.dispatchEvent(new CustomEvent("emojiSelected", options));
    }
  }, {
    key: "chooseSkinTone",
    value: function chooseSkinTone(ev) {
      ev.preventDefault();
      ev.stopPropagation();
      var target = ev.target.nodeName === 'IMG' ? ev.target.parentElement : ev.target;
      var skintone = target.getAttribute("data-skintone").trim();
      if (this.current_skintone === skintone) {
        this.model.save({
          'current_skintone': ''
        });
      } else {
        this.model.save({
          'current_skintone': skintone
        });
      }
    }
  }, {
    key: "chooseCategory",
    value: function chooseCategory(ev) {
      ev.preventDefault && ev.preventDefault();
      ev.stopPropagation && ev.stopPropagation();
      var el = ev.target.matches('li') ? ev.target : chat_emoji_picker_u.ancestor(ev.target, 'li');
      this.setCategoryForElement(el);
      this.navigator.select(el);
      !this.navigator.enabled && this.navigator.enable();
    }
  }, {
    key: "onSearchInputKeyDown",
    value: function onSearchInputKeyDown(ev) {
      if (ev.keyCode === KEYCODES.TAB) {
        if (ev.target.value) {
          ev.preventDefault();
          var match = public_converse.emojis.shortnames.find(function (sn) {
            return shared_converse.FILTER_CONTAINS(sn, ev.target.value);
          });
          match && this.model.set({
            'query': match
          });
        } else if (!this.navigator.enabled) {
          this.enableArrowNavigation(ev);
        }
      } else if (ev.keyCode === KEYCODES.DOWN_ARROW && !this.navigator.enabled) {
        this.enableArrowNavigation(ev);
      } else if (ev.keyCode !== KEYCODES.ENTER && ev.keyCode !== KEYCODES.DOWN_ARROW) {
        this.debouncedFilter(ev.target);
      }
    }
  }, {
    key: "onEnterPressed",
    value: function onEnterPressed(ev) {
      ev.preventDefault();
      ev.stopPropagation();
      if (public_converse.emojis.shortnames.includes(ev.target.value)) {
        this.insertIntoTextArea(ev.target.value);
      } else if (this.search_results.length === 1) {
        this.insertIntoTextArea(this.search_results[0].sn);
      } else if (this.navigator.selected && this.navigator.selected.matches('.insert-emoji')) {
        this.insertIntoTextArea(this.navigator.selected.getAttribute('data-emoji'));
      } else if (this.navigator.selected && this.navigator.selected.matches('.emoji-category')) {
        this.chooseCategory({
          'target': this.navigator.selected
        });
      }
    }
  }, {
    key: "onSearchInputFocus",
    value: function onSearchInputFocus(ev) {
      this.chatview.emitBlurred(ev);
      this.disableArrowNavigation();
    }
  }, {
    key: "getTonedShortname",
    value: function getTonedShortname(shortname) {
      if (getTonedEmojis().includes(shortname) && this.current_skintone) {
        return "".concat(shortname.slice(0, shortname.length - 1), "_").concat(this.current_skintone, ":");
      }
      return shortname;
    }
  }, {
    key: "initArrowNavigation",
    value: function initArrowNavigation() {
      var _this7 = this;
      if (!this.navigator) {
        var default_selector = 'li:not(.hidden):not(.emoji-skintone), .emoji-search';
        var options = {
          'jump_to_picked': '.emoji-category',
          'jump_to_picked_selector': '.emoji-category.picked',
          'jump_to_picked_direction': dom_navigator.DIRECTION.down,
          'picked_selector': '.picked',
          'scroll_container': this.querySelector('.emoji-picker__lists'),
          'getSelector': function getSelector(direction) {
            if (direction === dom_navigator.DIRECTION.down) {
              var c = _this7.navigator.selected && _this7.navigator.selected.getAttribute('data-category');
              return c ? "ul[data-category=\"".concat(c, "\"] li:not(.hidden):not(.emoji-skintone), .emoji-search") : default_selector;
            } else {
              return default_selector;
            }
          },
          'onSelected': function onSelected(el) {
            el.matches('.insert-emoji') && _this7.setCategoryForElement(el.parentElement);
            el.matches('.insert-emoji, .emoji-category') && el.firstElementChild.focus();
            el.matches('.emoji-search') && el.focus();
          }
        };
        this.navigator = new dom_navigator(this, options);
      }
    }
  }, {
    key: "disableArrowNavigation",
    value: function disableArrowNavigation() {
      var _this$navigator;
      (_this$navigator = this.navigator) === null || _this$navigator === void 0 ? void 0 : _this$navigator.disable();
    }
  }, {
    key: "enableArrowNavigation",
    value: function enableArrowNavigation(ev) {
      var _ev$preventDefault, _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      this.disableArrowNavigation();
      this.navigator.enable();
      this.navigator.handleKeydown(ev);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'chatview': {
          type: Object
        },
        'current_category': {
          type: String,
          'reflect': true
        },
        'current_skintone': {
          type: String,
          'reflect': true
        },
        'model': {
          type: Object
        },
        'query': {
          type: String,
          'reflect': true
        },
        // This is an optimization, we lazily render the emoji picker, otherwise tests slow to a crawl.
        'render_emojis': {
          type: Boolean
        }
      };
    }
  }]);
  return EmojiPicker;
}(CustomElement);

shared_api.elements.define('converse-emoji-picker', EmojiPicker);
;// CONCATENATED MODULE: ./src/shared/chat/templates/message-limit.js
var message_limit_templateObject;
function message_limit_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const message_limit = (function (counter) {
  var i18n_chars_remaining = __('Message characters remaining');
  return (0,external_lit_namespaceObject.html)(message_limit_templateObject || (message_limit_templateObject = message_limit_taggedTemplateLiteral(["<span class=\"message-limit ", "\" title=\"", "\">", "</span>"])), counter < 1 ? 'error' : '', i18n_chars_remaining, counter);
});
;// CONCATENATED MODULE: ./src/shared/chat/message-limit.js
function message_limit_typeof(obj) {
  "@babel/helpers - typeof";

  return message_limit_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;
  }, message_limit_typeof(obj);
}
function message_limit_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_limit_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, message_limit_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_limit_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_limit_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_limit_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_limit_toPropertyKey(arg) {
  var key = message_limit_toPrimitive(arg, "string");
  return message_limit_typeof(key) === "symbol" ? key : String(key);
}
function message_limit_toPrimitive(input, hint) {
  if (message_limit_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_limit_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_limit_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    message_limit_get = Reflect.get.bind();
  } else {
    message_limit_get = function _get(target, property, receiver) {
      var base = message_limit_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return message_limit_get.apply(this, arguments);
}
function message_limit_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = message_limit_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function message_limit_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) message_limit_setPrototypeOf(subClass, superClass);
}
function message_limit_setPrototypeOf(o, p) {
  message_limit_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_limit_setPrototypeOf(o, p);
}
function message_limit_createSuper(Derived) {
  var hasNativeReflectConstruct = message_limit_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_limit_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_limit_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_limit_possibleConstructorReturn(this, result);
  };
}
function message_limit_possibleConstructorReturn(self, call) {
  if (call && (message_limit_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 message_limit_assertThisInitialized(self);
}
function message_limit_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_limit_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 message_limit_getPrototypeOf(o) {
  message_limit_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_limit_getPrototypeOf(o);
}



var MessageLimitIndicator = /*#__PURE__*/function (_CustomElement) {
  message_limit_inherits(MessageLimitIndicator, _CustomElement);
  var _super = message_limit_createSuper(MessageLimitIndicator);
  function MessageLimitIndicator() {
    message_limit_classCallCheck(this, MessageLimitIndicator);
    return _super.apply(this, arguments);
  }
  message_limit_createClass(MessageLimitIndicator, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this = this;
      message_limit_get(message_limit_getPrototypeOf(MessageLimitIndicator.prototype), "connectedCallback", this).call(this);
      this.listenTo(this.model, 'change:draft', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      var limit = shared_api.settings.get('message_limit');
      if (!limit) return '';
      var chars = this.model.get('draft') || '';
      return message_limit(limit - chars.length);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        model: {
          type: Object
        }
      };
    }
  }]);
  return MessageLimitIndicator;
}(CustomElement);

shared_api.elements.define('converse-message-limit-indicator', MessageLimitIndicator);
;// CONCATENATED MODULE: ./src/shared/chat/templates/toolbar.js
var toolbar_templateObject, toolbar_templateObject2;
function toolbar_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



function tplSendButton() {
  var i18n_send_message = __('Send the message');
  return (0,external_lit_namespaceObject.html)(toolbar_templateObject || (toolbar_templateObject = toolbar_taggedTemplateLiteral(["<button type=\"submit\" class=\"btn send-button\" title=\"", "\">\n        <converse-icon color=\"var(--toolbar-btn-text-color)\" class=\"fa fa-paper-plane\" size=\"1em\"></converse-icon>\n    </button>"])), i18n_send_message);
}
/* harmony default export */ const toolbar = (function (el) {
  return (0,external_lit_namespaceObject.html)(toolbar_templateObject2 || (toolbar_templateObject2 = toolbar_taggedTemplateLiteral(["\n        <span class=\"toolbar-buttons\">", "</span>\n        ", "\n    "])), until_m(el.getButtons(), ''), el.show_send_button ? tplSendButton() : '');
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/chat/styles/toolbar.scss
var styles_toolbar = __webpack_require__(9769);
;// CONCATENATED MODULE: ./src/shared/chat/styles/toolbar.scss

      
      
      
      
      
      
      
      
      

var toolbar_options = {};

toolbar_options.styleTagTransform = (styleTagTransform_default());
toolbar_options.setAttributes = (setAttributesWithoutAttributes_default());

      toolbar_options.insert = insertBySelector_default().bind(null, "head");
    
toolbar_options.domAPI = (styleDomAPI_default());
toolbar_options.insertStyleElement = (insertStyleElement_default());

var toolbar_update = injectStylesIntoStyleTag_default()(styles_toolbar/* default */.Z, toolbar_options);




       /* harmony default export */ const chat_styles_toolbar = (styles_toolbar/* default */.Z && styles_toolbar/* default */.Z.locals ? styles_toolbar/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/chat/toolbar.js
function toolbar_typeof(obj) {
  "@babel/helpers - typeof";

  return toolbar_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;
  }, toolbar_typeof(obj);
}
var chat_toolbar_templateObject, chat_toolbar_templateObject2, toolbar_templateObject3, toolbar_templateObject4, toolbar_templateObject5, toolbar_templateObject6, toolbar_templateObject7, toolbar_templateObject8;
function chat_toolbar_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function toolbar_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function toolbar_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, toolbar_toPropertyKey(descriptor.key), descriptor);
  }
}
function toolbar_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) toolbar_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) toolbar_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function toolbar_toPropertyKey(arg) {
  var key = toolbar_toPrimitive(arg, "string");
  return toolbar_typeof(key) === "symbol" ? key : String(key);
}
function toolbar_toPrimitive(input, hint) {
  if (toolbar_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (toolbar_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function toolbar_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    toolbar_get = Reflect.get.bind();
  } else {
    toolbar_get = function _get(target, property, receiver) {
      var base = toolbar_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return toolbar_get.apply(this, arguments);
}
function toolbar_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = toolbar_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function toolbar_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) toolbar_setPrototypeOf(subClass, superClass);
}
function toolbar_setPrototypeOf(o, p) {
  toolbar_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return toolbar_setPrototypeOf(o, p);
}
function toolbar_createSuper(Derived) {
  var hasNativeReflectConstruct = toolbar_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = toolbar_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = toolbar_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return toolbar_possibleConstructorReturn(this, result);
  };
}
function toolbar_possibleConstructorReturn(self, call) {
  if (call && (toolbar_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 toolbar_assertThisInitialized(self);
}
function toolbar_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function toolbar_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 toolbar_getPrototypeOf(o) {
  toolbar_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return toolbar_getPrototypeOf(o);
}









var toolbar_Strophe = public_converse.env.Strophe;
var ChatToolbar = /*#__PURE__*/function (_CustomElement) {
  toolbar_inherits(ChatToolbar, _CustomElement);
  var _super = toolbar_createSuper(ChatToolbar);
  function ChatToolbar() {
    toolbar_classCallCheck(this, ChatToolbar);
    return _super.apply(this, arguments);
  }
  toolbar_createClass(ChatToolbar, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this = this;
      toolbar_get(toolbar_getPrototypeOf(ChatToolbar.prototype), "connectedCallback", this).call(this);
      this.listenTo(this.model, 'change:composing_spoiler', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      return toolbar(this);
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      /**
       * Triggered once the _converse.ChatBoxView's toolbar has been rendered
       * @event _converse#renderToolbar
       * @type { _converse.ChatBoxView }
       * @example _converse.api.listen.on('renderToolbar', this => { ... });
       */
      shared_api.trigger('renderToolbar', this);
    }
  }, {
    key: "getButtons",
    value: function getButtons() {
      var _this2 = this,
        _api$settings$get;
      var buttons = [];
      if (this.show_emoji_button) {
        var chatview = shared_converse.chatboxviews.get(this.model.get('jid'));
        buttons.push((0,external_lit_namespaceObject.html)(chat_toolbar_templateObject || (chat_toolbar_templateObject = chat_toolbar_taggedTemplateLiteral(["<converse-emoji-dropdown .chatview=", "></converse-emoji-dropdown>"])), chatview));
      }
      if (this.show_call_button) {
        var color = this.is_groupchat ? '--muc-toolbar-btn-color' : '--chat-toolbar-btn-color';
        var i18n_start_call = __('Start a call');
        buttons.push((0,external_lit_namespaceObject.html)(chat_toolbar_templateObject2 || (chat_toolbar_templateObject2 = chat_toolbar_taggedTemplateLiteral(["\n                <button class=\"toggle-call\" @click=", " title=\"", "\">\n                    <converse-icon color=\"var(", ")\" class=\"fa fa-phone\" size=\"1em\"></converse-icon>\n                </button>"])), this.toggleCall, i18n_start_call, color));
      }
      var message_limit = shared_api.settings.get('message_limit');
      if (message_limit) {
        buttons.push((0,external_lit_namespaceObject.html)(toolbar_templateObject3 || (toolbar_templateObject3 = chat_toolbar_taggedTemplateLiteral(["\n                <converse-message-limit-indicator .model=", " class=\"right\">\n                </converse-message-limit-indicator>"])), this.model));
      }
      if (this.show_spoiler_button) {
        buttons.push(this.getSpoilerButton());
      }
      var http_upload_promise = shared_api.disco.supports(toolbar_Strophe.NS.HTTPUPLOAD, shared_converse.domain);
      buttons.push((0,external_lit_namespaceObject.html)(toolbar_templateObject4 || (toolbar_templateObject4 = chat_toolbar_taggedTemplateLiteral(["", ""])), until_m(http_upload_promise.then(function (is_supported) {
        return _this2.getHTTPUploadButton(is_supported);
      }), '')));
      if (this.is_groupchat && (_api$settings$get = shared_api.settings.get('visible_toolbar_buttons')) !== null && _api$settings$get !== void 0 && _api$settings$get.toggle_occupants) {
        var i18n_hide_occupants = __('Hide participants');
        var i18n_show_occupants = __('Show participants');
        buttons.push((0,external_lit_namespaceObject.html)(toolbar_templateObject5 || (toolbar_templateObject5 = chat_toolbar_taggedTemplateLiteral(["\n                <button class=\"toggle_occupants right\"\n                        title=\"", "\"\n                        @click=", ">\n                    <converse-icon\n                        color=\"var(--muc-toolbar-btn-color)\"\n                        class=\"fa ", "\"\n                        size=\"1em\"></converse-icon>\n                </button>"])), this.hidden_occupants ? i18n_show_occupants : i18n_hide_occupants, this.toggleOccupants, this.hidden_occupants ? "fa-angle-double-left" : "fa-angle-double-right"));
      }

      /**
       * *Hook* which allows plugins to add more buttons to a chat's toolbar
       * @event _converse#getToolbarButtons
       * @example
       *  api.listen.on('getToolbarButtons', (toolbar_el, buttons) {
       *      buttons.push(html`
       *          <button @click=${() => alert('Foo!')}>Foo</button>`
       *      );
       *      return buttons;
       *  }
       */
      return shared_converse.api.hook('getToolbarButtons', this, buttons);
    }
  }, {
    key: "getHTTPUploadButton",
    value: function getHTTPUploadButton(is_supported) {
      if (is_supported) {
        var i18n_choose_file = __('Choose a file to send');
        var color = this.is_groupchat ? '--muc-toolbar-btn-color' : '--chat-toolbar-btn-color';
        return (0,external_lit_namespaceObject.html)(toolbar_templateObject6 || (toolbar_templateObject6 = chat_toolbar_taggedTemplateLiteral(["\n                <button title=\"", "\" @click=", ">\n                    <converse-icon\n                        color=\"var(", ")\"\n                        class=\"fa fa-paperclip\"\n                        size=\"1em\"></converse-icon>\n                </button>\n                <input type=\"file\" @change=", " class=\"fileupload\" multiple=\"\" style=\"display:none\"/>"])), i18n_choose_file, this.toggleFileUpload, color, this.onFileSelection);
      } else {
        return '';
      }
    }
  }, {
    key: "getSpoilerButton",
    value: function getSpoilerButton() {
      var _model$presence;
      var model = this.model;
      if (!this.is_groupchat && !((_model$presence = model.presence) !== null && _model$presence !== void 0 && _model$presence.resources.length)) {
        return;
      }
      var i18n_toggle_spoiler;
      if (model.get('composing_spoiler')) {
        i18n_toggle_spoiler = __("Click to write as a normal (non-spoiler) message");
      } else {
        i18n_toggle_spoiler = __("Click to write your message as a spoiler");
      }
      var color = this.is_groupchat ? '--muc-toolbar-btn-color' : '--chat-toolbar-btn-color';
      var markup = (0,external_lit_namespaceObject.html)(toolbar_templateObject7 || (toolbar_templateObject7 = chat_toolbar_taggedTemplateLiteral(["\n            <button class=\"toggle-compose-spoiler\"\n                    title=\"", "\"\n                    @click=", ">\n                <converse-icon\n                    color=\"var(", ")\"\n                    class=\"fa ", "\"\n                    size=\"1em\"></converse-icon>\n            </button>"])), i18n_toggle_spoiler, this.toggleComposeSpoilerMessage, color, model.get('composing_spoiler') ? 'fa-eye-slash' : 'fa-eye');
      if (this.is_groupchat) {
        return markup;
      } else {
        var contact_jid = model.get('jid');
        var spoilers_promise = Promise.all(model.presence.resources.map(function (r) {
          return shared_api.disco.supports(toolbar_Strophe.NS.SPOILER, "".concat(contact_jid, "/").concat(r.get('name')));
        })).then(function (results) {
          return results.reduce(function (acc, val) {
            return acc && val;
          }, true);
        });
        return (0,external_lit_namespaceObject.html)(toolbar_templateObject8 || (toolbar_templateObject8 = chat_toolbar_taggedTemplateLiteral(["", ""])), until_m(spoilers_promise.then(function () {
          return markup;
        }), ''));
      }
    }
  }, {
    key: "toggleFileUpload",
    value: function toggleFileUpload(ev) {
      var _ev$preventDefault, _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      this.querySelector('.fileupload').click();
    }
  }, {
    key: "onFileSelection",
    value: function onFileSelection(evt) {
      this.model.sendFiles(evt.target.files);
    }
  }, {
    key: "toggleComposeSpoilerMessage",
    value: function toggleComposeSpoilerMessage(ev) {
      var _ev$preventDefault2, _ev$stopPropagation2;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation2 = ev.stopPropagation) === null || _ev$stopPropagation2 === void 0 ? void 0 : _ev$stopPropagation2.call(ev);
      this.model.set('composing_spoiler', !this.model.get('composing_spoiler'));
    }
  }, {
    key: "toggleOccupants",
    value: function toggleOccupants(ev) {
      var _ev$preventDefault3, _ev$stopPropagation3;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault3 = ev.preventDefault) === null || _ev$preventDefault3 === void 0 ? void 0 : _ev$preventDefault3.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation3 = ev.stopPropagation) === null || _ev$stopPropagation3 === void 0 ? void 0 : _ev$stopPropagation3.call(ev);
      this.model.save({
        'hidden_occupants': !this.model.get('hidden_occupants')
      });
    }
  }, {
    key: "toggleCall",
    value: function toggleCall(ev) {
      var _ev$preventDefault4, _ev$stopPropagation4;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault4 = ev.preventDefault) === null || _ev$preventDefault4 === void 0 ? void 0 : _ev$preventDefault4.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation4 = ev.stopPropagation) === null || _ev$stopPropagation4 === void 0 ? void 0 : _ev$stopPropagation4.call(ev);
      /**
       * When a call button (i.e. with class .toggle-call) on a chatbox has been clicked.
       * @event _converse#callButtonClicked
       * @type { object }
       * @property { Strophe.Connection } _converse.connection - The XMPP Connection object
       * @property { _converse.ChatBox | _converse.ChatRoom } _converse.connection - The XMPP Connection object
       * @example _converse.api.listen.on('callButtonClicked', (connection, model) => { ... });
       */
      shared_api.trigger('callButtonClicked', {
        connection: shared_converse.connection,
        model: this.model
      });
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        hidden_occupants: {
          type: Boolean
        },
        is_groupchat: {
          type: Boolean
        },
        message_limit: {
          type: Number
        },
        model: {
          type: Object
        },
        show_call_button: {
          type: Boolean
        },
        show_emoji_button: {
          type: Boolean
        },
        show_send_button: {
          type: Boolean
        },
        show_spoiler_button: {
          type: Boolean
        }
      };
    }
  }]);
  return ChatToolbar;
}(CustomElement);
shared_api.elements.define('converse-chat-toolbar', ChatToolbar);
;// CONCATENATED MODULE: ./src/plugins/chatview/templates/chat-head.js
var chat_head_templateObject, chat_head_templateObject2, chat_head_templateObject3, chat_head_templateObject4, chat_head_templateObject5, chat_head_templateObject6;
function chat_head_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





/* harmony default export */ const chat_head = (function (o) {
  var _o$model$vcard, _o$model$vcard2;
  var i18n_profile = __("The User's Profile Image");
  var avatar = (0,external_lit_namespaceObject.html)(chat_head_templateObject || (chat_head_templateObject = chat_head_taggedTemplateLiteral(["<span title=\"", "\">\n        <converse-avatar\n            class=\"avatar chat-msg__avatar\"\n            .data=", "\n            nonce=", "\n            height=\"40\" width=\"40\"></converse-avatar></span>"])), i18n_profile, (_o$model$vcard = o.model.vcard) === null || _o$model$vcard === void 0 ? void 0 : _o$model$vcard.attributes, (_o$model$vcard2 = o.model.vcard) === null || _o$model$vcard2 === void 0 ? void 0 : _o$model$vcard2.get('vcard_updated'));
  var display_name = o.model.getDisplayName();
  return (0,external_lit_namespaceObject.html)(chat_head_templateObject2 || (chat_head_templateObject2 = chat_head_taggedTemplateLiteral(["\n        <div class=\"chatbox-title ", "\">\n            <div class=\"chatbox-title--row\">\n                ", "\n                ", "\n                <div class=\"chatbox-title__text\" title=\"", "\">\n                    ", "\n                </div>\n            </div>\n            <div class=\"chatbox-title__buttons row no-gutters\">\n                ", "\n                ", "\n            </div>\n        </div>\n        ", "\n    "])), o.status ? '' : "chatbox-title--no-desc", !shared_converse.api.settings.get("singleton") ? (0,external_lit_namespaceObject.html)(chat_head_templateObject3 || (chat_head_templateObject3 = chat_head_taggedTemplateLiteral(["<converse-controlbox-navback jid=\"", "\"></converse-controlbox-navback>"])), o.jid) : '', o.type !== shared_converse.HEADLINES_TYPE ? (0,external_lit_namespaceObject.html)(chat_head_templateObject4 || (chat_head_templateObject4 = chat_head_taggedTemplateLiteral(["<a class=\"show-msg-author-modal\" @click=", ">", "</a>"])), o.showUserDetailsModal, avatar) : '', o.jid, o.type !== shared_converse.HEADLINES_TYPE ? (0,external_lit_namespaceObject.html)(chat_head_templateObject5 || (chat_head_templateObject5 = chat_head_taggedTemplateLiteral(["<a class=\"user show-msg-author-modal\" @click=", ">", "</a>"])), o.showUserDetailsModal, display_name) : display_name, until_m(getDropdownButtons(o.heading_buttons_promise), ''), until_m(getStandaloneButtons(o.heading_buttons_promise), ''), o.status ? (0,external_lit_namespaceObject.html)(chat_head_templateObject6 || (chat_head_templateObject6 = chat_head_taggedTemplateLiteral(["<p class=\"chat-head__desc\">", "</p>"])), o.status) : '');
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/chatview/styles/chat-head.scss
var styles_chat_head = __webpack_require__(3015);
;// CONCATENATED MODULE: ./src/plugins/chatview/styles/chat-head.scss

      
      
      
      
      
      
      
      
      

var chat_head_options = {};

chat_head_options.styleTagTransform = (styleTagTransform_default());
chat_head_options.setAttributes = (setAttributesWithoutAttributes_default());

      chat_head_options.insert = insertBySelector_default().bind(null, "head");
    
chat_head_options.domAPI = (styleDomAPI_default());
chat_head_options.insertStyleElement = (insertStyleElement_default());

var chat_head_update = injectStylesIntoStyleTag_default()(styles_chat_head/* default */.Z, chat_head_options);




       /* harmony default export */ const chatview_styles_chat_head = (styles_chat_head/* default */.Z && styles_chat_head/* default */.Z.locals ? styles_chat_head/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/chatview/heading.js
function heading_typeof(obj) {
  "@babel/helpers - typeof";

  return heading_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;
  }, heading_typeof(obj);
}
function heading_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function heading_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, heading_toPropertyKey(descriptor.key), descriptor);
  }
}
function heading_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) heading_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) heading_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function heading_toPropertyKey(arg) {
  var key = heading_toPrimitive(arg, "string");
  return heading_typeof(key) === "symbol" ? key : String(key);
}
function heading_toPrimitive(input, hint) {
  if (heading_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (heading_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function heading_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) heading_setPrototypeOf(subClass, superClass);
}
function heading_setPrototypeOf(o, p) {
  heading_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return heading_setPrototypeOf(o, p);
}
function heading_createSuper(Derived) {
  var hasNativeReflectConstruct = heading_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = heading_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = heading_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return heading_possibleConstructorReturn(this, result);
  };
}
function heading_possibleConstructorReturn(self, call) {
  if (call && (heading_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 heading_assertThisInitialized(self);
}
function heading_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function heading_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 heading_getPrototypeOf(o) {
  heading_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return heading_getPrototypeOf(o);
}






var ChatHeading = /*#__PURE__*/function (_CustomElement) {
  heading_inherits(ChatHeading, _CustomElement);
  var _super = heading_createSuper(ChatHeading);
  function ChatHeading() {
    heading_classCallCheck(this, ChatHeading);
    return _super.apply(this, arguments);
  }
  heading_createClass(ChatHeading, [{
    key: "initialize",
    value: function initialize() {
      var _this = this,
        _this$model$rosterCon;
      this.model = shared_converse.chatboxes.get(this.jid);
      this.listenTo(this.model, 'change:status', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'vcard:add', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'vcard:change', function () {
        return _this.requestUpdate();
      });
      if (this.model.contact) {
        this.listenTo(this.model.contact, 'destroy', function () {
          return _this.requestUpdate();
        });
      }
      (_this$model$rosterCon = this.model.rosterContactAdded) === null || _this$model$rosterCon === void 0 ? void 0 : _this$model$rosterCon.then(function () {
        _this.listenTo(_this.model.contact, 'change:nickname', function () {
          return _this.requestUpdate();
        });
        _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      return chat_head(Object.assign(this.model.toJSON(), {
        'heading_buttons_promise': this.getHeadingButtons(),
        'model': this.model,
        'showUserDetailsModal': function showUserDetailsModal(ev) {
          return _this2.showUserDetailsModal(ev);
        }
      }));
    }
  }, {
    key: "showUserDetailsModal",
    value: function showUserDetailsModal(ev) {
      ev.preventDefault();
      shared_api.modal.show('converse-user-details-modal', {
        model: this.model
      }, ev);
    }
  }, {
    key: "close",
    value: function close(ev) {
      ev.preventDefault();
      this.model.close();
    }

    /**
     * Returns a list of objects which represent buttons for the chat's header.
     * @async
     * @emits _converse#getHeadingButtons
     */
  }, {
    key: "getHeadingButtons",
    value: function getHeadingButtons() {
      var _this3 = this;
      var buttons = [
      /**
       * @typedef { Object } HeadingButtonAttributes
       * An object representing a chat heading button
       * @property { Boolean } standalone
       *  True if shown on its own, false if it must be in the dropdown menu.
       * @property { Function } handler
       *  A handler function to be called when the button is clicked.
       * @property { String } a_class - HTML classes to show on the button
       * @property { String } i18n_text - The user-visiible name of the button
       * @property { String } i18n_title - The tooltip text for this button
       * @property { String } icon_class - What kind of CSS class to use for the icon
       * @property { String } name - The internal name of the button
       */
      {
        'a_class': 'show-user-details-modal',
        'handler': function handler(ev) {
          return _this3.showUserDetailsModal(ev);
        },
        'i18n_text': __('Details'),
        'i18n_title': __('See more information about this person'),
        'icon_class': 'fa-id-card',
        'name': 'details',
        'standalone': shared_api.settings.get('view_mode') === 'overlayed'
      }];
      if (!shared_api.settings.get('singleton')) {
        buttons.push({
          'a_class': 'close-chatbox-button',
          'handler': function handler(ev) {
            return _this3.close(ev);
          },
          'i18n_text': __('Close'),
          'i18n_title': __('Close and end this conversation'),
          'icon_class': 'fa-times',
          'name': 'close',
          'standalone': shared_api.settings.get('view_mode') === 'overlayed'
        });
      }
      var el = shared_converse.chatboxviews.get(this.getAttribute('jid'));
      if (el) {
        /**
         * *Hook* which allows plugins to add more buttons to a chat's heading.
         *
         * Note: This hook is fired for both 1 on 1 chats and groupchats.
         * If you only care about one, you need to add a check in your code.
         *
         * @event _converse#getHeadingButtons
         * @param { HTMLElement } el
         *      The `converse-chat` (or `converse-muc`) DOM element that represents the chat
         * @param { Array.<HeadingButtonAttributes> }
         *      An array of the existing buttons. New buttons may be added,
         *      and existing ones removed or modified.
         * @example
         *  api.listen.on('getHeadingButtons', (el, buttons) => {
         *      buttons.push({
         *          'i18n_title': __('Foo'),
         *          'i18n_text': __('Foo Bar'),
         *          'handler': ev => alert('Foo!'),
         *          'a_class': 'toggle-foo',
         *          'icon_class': 'fa-foo',
         *          'name': 'foo'
         *      });
         *      return buttons;
         *  });
         */
        return shared_converse.api.hook('getHeadingButtons', el, buttons);
      } else {
        return buttons; // Happens during tests
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return ChatHeading;
}(CustomElement);

shared_api.elements.define('converse-chat-heading', ChatHeading);
;// CONCATENATED MODULE: ./src/plugins/chatview/utils.js
function chatview_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return chatview_utils_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;
  }, chatview_utils_typeof(obj);
}
function chatview_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chatview_utils_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" == chatview_utils_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 chatview_utils_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 chatview_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chatview_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chatview_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


function utils_clearHistory(jid) {
  if (shared_converse.router.history.getFragment() === "converse/chat?jid=".concat(jid)) {
    shared_converse.router.navigate('');
  }
}
function utils_clearMessages(_x) {
  return _clearMessages.apply(this, arguments);
}
function _clearMessages() {
  _clearMessages = chatview_utils_asyncToGenerator( /*#__PURE__*/chatview_utils_regeneratorRuntime().mark(function _callee(chat) {
    var result;
    return chatview_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return shared_api.confirm(__('Are you sure you want to clear the messages from this conversation?'));
        case 2:
          result = _context.sent;
          if (!result) {
            _context.next = 6;
            break;
          }
          _context.next = 6;
          return chat.clearMessages();
        case 6:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _clearMessages.apply(this, arguments);
}
function parseMessageForCommands(_x2, _x3) {
  return _parseMessageForCommands.apply(this, arguments);
}
function _parseMessageForCommands() {
  _parseMessageForCommands = chatview_utils_asyncToGenerator( /*#__PURE__*/chatview_utils_regeneratorRuntime().mark(function _callee2(chat, text) {
    var match, handled, _converse$chatboxview;
    return chatview_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          match = text.replace(/^\s*/, '').match(/^\/(.*)\s*$/);
          if (!match) {
            _context2.next = 22;
            break;
          }
          handled = false;
          /**
           * *Hook* which allows plugins to add more commands to a chat's textbox.
           * Data provided is the chatbox model and the text typed - {model, text}.
           * Check `handled` to see if the hook was already handled.
           * @event _converse#parseMessageForCommands
           * @example
           *  api.listen.on('parseMessageForCommands', (data, handled) {
           *      if (!handled) {
           *         const command = (data.text.match(/^\/([a-zA-Z]*) ?/) || ['']).pop().toLowerCase();
           *         // custom code comes here
           *      }
           *      return handled;
           *  }
           */
          _context2.next = 5;
          return shared_api.hook('parseMessageForCommands', {
            model: chat,
            text: text
          }, handled);
        case 5:
          handled = _context2.sent;
          if (!handled) {
            _context2.next = 8;
            break;
          }
          return _context2.abrupt("return", true);
        case 8:
          if (!(match[1] === 'clear')) {
            _context2.next = 13;
            break;
          }
          utils_clearMessages(chat);
          return _context2.abrupt("return", true);
        case 13:
          if (!(match[1] === 'close')) {
            _context2.next = 18;
            break;
          }
          (_converse$chatboxview = shared_converse.chatboxviews.get(chat.get('jid'))) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.close();
          return _context2.abrupt("return", true);
        case 18:
          if (!(match[1] === 'help')) {
            _context2.next = 22;
            break;
          }
          chat.set({
            'show_help_messages': false
          }, {
            'silent': true
          });
          chat.set({
            'show_help_messages': true
          });
          return _context2.abrupt("return", true);
        case 22:
          return _context2.abrupt("return", false);
        case 23:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _parseMessageForCommands.apply(this, arguments);
}
function resetElementHeight(ev) {
  if (ev.target.value) {
    var height = ev.target.scrollHeight + 'px';
    if (ev.target.style.height != height) {
      ev.target.style.height = 'auto';
      ev.target.style.height = height;
    }
  } else {
    ev.target.style = '';
  }
}
;// CONCATENATED MODULE: ./src/plugins/chatview/templates/message-form.js
var message_form_templateObject;
function message_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const message_form = (function (o) {
  var label_message = o.composing_spoiler ? __('Hidden message') : __('Message');
  var label_spoiler_hint = __('Optional hint');
  var show_send_button = shared_api.settings.get('show_send_button');
  return (0,external_lit_namespaceObject.html)(message_form_templateObject || (message_form_templateObject = message_form_taggedTemplateLiteral(["\n        <form class=\"sendXMPPMessage\">\n            <input type=\"text\"\n                   enterkeyhint=\"send\"\n                   placeholder=\"", "\"i\n                   value=\"", "\"\n                   class=\"", " spoiler-hint\"/>\n            <textarea\n                autofocus\n                type=\"text\"\n                enterkeyhint=\"send\"\n                @drop=", "\n                @input=", "\n                @keydown=", "\n                @keyup=", "\n                @paste=", "\n                @change=", "\n                class=\"chat-textarea\n                    ", "\n                    ", "\"\n                placeholder=\"", "\">", "</textarea>\n        </form>"])), label_spoiler_hint || '', o.hint_value || '', o.composing_spoiler ? '' : 'hidden', o.onDrop, resetElementHeight, o.onKeyDown, o.onKeyUp, o.onPaste, o.onChange, show_send_button ? 'chat-textarea-send-button' : '', o.composing_spoiler ? 'spoiler' : '', label_message, o.message_value || '');
});
;// CONCATENATED MODULE: ./src/plugins/chatview/message-form.js
function message_form_typeof(obj) {
  "@babel/helpers - typeof";

  return message_form_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;
  }, message_form_typeof(obj);
}
function message_form_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  message_form_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" == message_form_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 message_form_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 message_form_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        message_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        message_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function message_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function message_form_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, message_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function message_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) message_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) message_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function message_form_toPropertyKey(arg) {
  var key = message_form_toPrimitive(arg, "string");
  return message_form_typeof(key) === "symbol" ? key : String(key);
}
function message_form_toPrimitive(input, hint) {
  if (message_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (message_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function message_form_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    message_form_get = Reflect.get.bind();
  } else {
    message_form_get = function _get(target, property, receiver) {
      var base = message_form_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return message_form_get.apply(this, arguments);
}
function message_form_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = message_form_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function message_form_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) message_form_setPrototypeOf(subClass, superClass);
}
function message_form_setPrototypeOf(o, p) {
  message_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return message_form_setPrototypeOf(o, p);
}
function message_form_createSuper(Derived) {
  var hasNativeReflectConstruct = message_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = message_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = message_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return message_form_possibleConstructorReturn(this, result);
  };
}
function message_form_possibleConstructorReturn(self, call) {
  if (call && (message_form_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 message_form_assertThisInitialized(self);
}
function message_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function message_form_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 message_form_getPrototypeOf(o) {
  message_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return message_form_getPrototypeOf(o);
}






var message_form_u = public_converse.env.u;
var MessageForm = /*#__PURE__*/function (_ElementView) {
  message_form_inherits(MessageForm, _ElementView);
  var _super = message_form_createSuper(MessageForm);
  function MessageForm() {
    message_form_classCallCheck(this, MessageForm);
    return _super.apply(this, arguments);
  }
  message_form_createClass(MessageForm, [{
    key: "connectedCallback",
    value: function () {
      var _connectedCallback = message_form_asyncToGenerator( /*#__PURE__*/message_form_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return message_form_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              message_form_get(message_form_getPrototypeOf(MessageForm.prototype), "connectedCallback", this).call(this);
              this.model = shared_converse.chatboxes.get(this.getAttribute('jid'));
              _context.next = 4;
              return this.model.initialized;
            case 4:
              this.listenTo(this.model.messages, 'change:correcting', this.onMessageCorrecting);
              this.listenTo(this.model, 'change:composing_spoiler', function () {
                return _this.render();
              });
              this.handleEmojiSelection = function (_ref) {
                var detail = _ref.detail;
                if (_this.model.get('jid') === detail.jid) {
                  _this.insertIntoTextArea(detail.value, detail.autocompleting, false, detail.ac_position);
                }
              };
              document.addEventListener("emojiSelected", this.handleEmojiSelection);
              this.render();
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function connectedCallback() {
        return _connectedCallback.apply(this, arguments);
      }
      return connectedCallback;
    }()
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      message_form_get(message_form_getPrototypeOf(MessageForm.prototype), "disconnectedCallback", this).call(this);
      document.removeEventListener("emojiSelected", this.handleEmojiSelection);
    }
  }, {
    key: "toHTML",
    value: function toHTML() {
      var _this2 = this,
        _this$querySelector,
        _this$querySelector2;
      return message_form(Object.assign(this.model.toJSON(), {
        'onDrop': function onDrop(ev) {
          return _this2.onDrop(ev);
        },
        'hint_value': (_this$querySelector = this.querySelector('.spoiler-hint')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.value,
        'message_value': (_this$querySelector2 = this.querySelector('.chat-textarea')) === null || _this$querySelector2 === void 0 ? void 0 : _this$querySelector2.value,
        'onChange': function onChange(ev) {
          return _this2.model.set({
            'draft': ev.target.value
          });
        },
        'onKeyDown': function onKeyDown(ev) {
          return _this2.onKeyDown(ev);
        },
        'onKeyUp': function onKeyUp(ev) {
          return _this2.onKeyUp(ev);
        },
        'onPaste': function onPaste(ev) {
          return _this2.onPaste(ev);
        },
        'viewUnreadMessages': function viewUnreadMessages(ev) {
          return _this2.viewUnreadMessages(ev);
        }
      }));
    }

    /**
     * Insert a particular string value into the textarea of this chat box.
     * @param { string } value - The value to be inserted.
     * @param {(boolean|string)} [replace] - Whether an existing value
     *  should be replaced. If set to `true`, the entire textarea will
     *  be replaced with the new value. If set to a string, then only
     *  that string will be replaced *if* a position is also specified.
     * @param { number } [position] - The end index of the string to be
     *  replaced with the new value.
     */
  }, {
    key: "insertIntoTextArea",
    value: function insertIntoTextArea(value) {
      var replace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var correcting = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var position = arguments.length > 3 ? arguments[3] : undefined;
      var textarea = this.querySelector('.chat-textarea');
      if (correcting) {
        message_form_u.addClass('correcting', textarea);
      } else {
        message_form_u.removeClass('correcting', textarea);
      }
      if (replace) {
        if (position && typeof replace == 'string') {
          textarea.value = textarea.value.replace(new RegExp(replace, 'g'), function (match, offset) {
            return offset == position - replace.length ? value + ' ' : match;
          });
        } else {
          textarea.value = value;
        }
      } else {
        var existing = textarea.value;
        if (existing && existing[existing.length - 1] !== ' ') {
          existing = existing + ' ';
        }
        textarea.value = existing + value + ' ';
      }
      var ev = document.createEvent('HTMLEvents');
      ev.initEvent('change', false, true);
      textarea.dispatchEvent(ev);
      message_form_u.placeCaretAtEnd(textarea);
    }
  }, {
    key: "onMessageCorrecting",
    value: function onMessageCorrecting(message) {
      if (message.get('correcting')) {
        this.insertIntoTextArea(prefixMentions(message), true, true);
      } else {
        var currently_correcting = this.model.messages.findWhere('correcting');
        if (currently_correcting && currently_correcting !== message) {
          this.insertIntoTextArea(prefixMentions(message), true, true);
        } else {
          this.insertIntoTextArea('', true, false);
        }
      }
    }
  }, {
    key: "onEscapePressed",
    value: function onEscapePressed(ev) {
      var idx = this.model.messages.findLastIndex('correcting');
      var message = idx >= 0 ? this.model.messages.at(idx) : null;
      if (message) {
        ev.preventDefault();
        message.save('correcting', false);
        this.insertIntoTextArea('', true, false);
      }
    }
  }, {
    key: "onPaste",
    value: function onPaste(ev) {
      ev.stopPropagation();
      if (ev.clipboardData.files.length !== 0) {
        ev.preventDefault();
        // Workaround for quirk in at least Firefox 60.7 ESR:
        // It seems that pasted files disappear from the event payload after
        // the event has finished, which apparently happens during async
        // processing in sendFiles(). So we copy the array here.
        this.model.sendFiles(Array.from(ev.clipboardData.files));
        return;
      }
      this.model.set({
        'draft': ev.clipboardData.getData('text/plain')
      });
    }
  }, {
    key: "onKeyUp",
    value: function onKeyUp(ev) {
      this.model.set({
        'draft': ev.target.value
      });
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(ev) {
      if (ev.ctrlKey) {
        // When ctrl is pressed, no chars are entered into the textarea.
        return;
      }
      if (!ev.shiftKey && !ev.altKey && !ev.metaKey) {
        if (ev.keyCode === public_converse.keycodes.TAB) {
          var value = message_form_u.getCurrentWord(ev.target, null, /(:.*?:)/g);
          if (value.startsWith(':')) {
            ev.preventDefault();
            ev.stopPropagation();
            this.model.trigger('emoji-picker-autocomplete', ev.target, value);
          }
        } else if (ev.keyCode === public_converse.keycodes.FORWARD_SLASH) {
          // Forward slash is used to run commands. Nothing to do here.
          return;
        } else if (ev.keyCode === public_converse.keycodes.ESCAPE) {
          return this.onEscapePressed(ev, this);
        } else if (ev.keyCode === public_converse.keycodes.ENTER) {
          return this.onFormSubmitted(ev);
        } else if (ev.keyCode === public_converse.keycodes.UP_ARROW && !ev.target.selectionEnd) {
          var textarea = this.querySelector('.chat-textarea');
          if (!textarea.value || message_form_u.hasClass('correcting', textarea)) {
            return this.model.editEarlierMessage();
          }
        } else if (ev.keyCode === public_converse.keycodes.DOWN_ARROW && ev.target.selectionEnd === ev.target.value.length && message_form_u.hasClass('correcting', this.querySelector('.chat-textarea'))) {
          return this.model.editLaterMessage();
        }
      }
      if ([public_converse.keycodes.SHIFT, public_converse.keycodes.META, public_converse.keycodes.META_RIGHT, public_converse.keycodes.ESCAPE, public_converse.keycodes.ALT].includes(ev.keyCode)) {
        return;
      }
      if (this.model.get('chat_state') !== shared_converse.COMPOSING) {
        // Set chat state to composing if keyCode is not a forward-slash
        // (which would imply an internal command and not a message).
        this.model.setChatState(shared_converse.COMPOSING);
      }
    }
  }, {
    key: "onFormSubmitted",
    value: function () {
      var _onFormSubmitted = message_form_asyncToGenerator( /*#__PURE__*/message_form_regeneratorRuntime().mark(function _callee2(ev) {
        var _ev$preventDefault, _this$querySelector3;
        var textarea, message_text, err_msg, spoiler_hint, hint_el, is_command, message, chatview, msgs_container, _chatview, _msgs_container;
        return message_form_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
              textarea = this.querySelector('.chat-textarea');
              message_text = textarea.value.trim();
              if (!(shared_api.settings.get('message_limit') && message_text.length > shared_api.settings.get('message_limit') || !message_text.replace(/\s/g, '').length)) {
                _context2.next = 5;
                break;
              }
              return _context2.abrupt("return");
            case 5:
              if (shared_converse.connection.authenticated) {
                _context2.next = 10;
                break;
              }
              err_msg = __('Sorry, the connection has been lost, and your message could not be sent');
              shared_api.alert('error', __('Error'), err_msg);
              shared_api.connection.reconnect();
              return _context2.abrupt("return");
            case 10:
              hint_el = {};
              if (this.model.get('composing_spoiler')) {
                hint_el = this.querySelector('form.sendXMPPMessage input.spoiler-hint');
                spoiler_hint = hint_el.value;
              }
              message_form_u.addClass('disabled', textarea);
              textarea.setAttribute('disabled', 'disabled');
              (_this$querySelector3 = this.querySelector('converse-emoji-dropdown')) === null || _this$querySelector3 === void 0 ? void 0 : _this$querySelector3.hideMenu();
              _context2.next = 17;
              return parseMessageForCommands(this.model, message_text);
            case 17:
              is_command = _context2.sent;
              if (!is_command) {
                _context2.next = 22;
                break;
              }
              _context2.t0 = null;
              _context2.next = 25;
              break;
            case 22:
              _context2.next = 24;
              return this.model.sendMessage({
                'body': message_text,
                spoiler_hint: spoiler_hint
              });
            case 24:
              _context2.t0 = _context2.sent;
            case 25:
              message = _context2.t0;
              if (is_command || message) {
                hint_el.value = '';
                textarea.value = '';
                message_form_u.removeClass('correcting', textarea);
                textarea.style.height = 'auto';
                this.model.set({
                  'draft': ''
                });
              }
              if (shared_api.settings.get('view_mode') === 'overlayed') {
                // XXX: Chrome flexbug workaround. The .chat-content area
                // doesn't resize when the textarea is resized to its original size.
                chatview = shared_converse.chatboxviews.get(this.getAttribute('jid'));
                msgs_container = chatview.querySelector('.chat-content__messages');
                msgs_container.parentElement.style.display = 'none';
              }
              textarea.removeAttribute('disabled');
              message_form_u.removeClass('disabled', textarea);
              if (shared_api.settings.get('view_mode') === 'overlayed') {
                // XXX: Chrome flexbug workaround.
                _chatview = shared_converse.chatboxviews.get(this.getAttribute('jid'));
                _msgs_container = _chatview.querySelector('.chat-content__messages');
                _msgs_container.parentElement.style.display = '';
              }
              // Suppress events, otherwise superfluous CSN gets set
              // immediately after the message, causing rate-limiting issues.
              this.model.setChatState(shared_converse.ACTIVE, {
                'silent': true
              });
              textarea.focus();
            case 33:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function onFormSubmitted(_x) {
        return _onFormSubmitted.apply(this, arguments);
      }
      return onFormSubmitted;
    }()
  }]);
  return MessageForm;
}(ElementView);

shared_api.elements.define('converse-message-form', MessageForm);
;// CONCATENATED MODULE: ./src/plugins/chatview/templates/bottom-panel.js
var bottom_panel_templateObject, bottom_panel_templateObject2, bottom_panel_templateObject3;
function bottom_panel_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const bottom_panel = (function (o) {
  var unread_msgs = __('You have unread messages');
  var message_limit = shared_api.settings.get('message_limit');
  var show_call_button = shared_api.settings.get('visible_toolbar_buttons').call;
  var show_emoji_button = shared_api.settings.get('visible_toolbar_buttons').emoji;
  var show_send_button = shared_api.settings.get('show_send_button');
  var show_spoiler_button = shared_api.settings.get('visible_toolbar_buttons').spoiler;
  var show_toolbar = shared_api.settings.get('show_toolbar');
  return (0,external_lit_namespaceObject.html)(bottom_panel_templateObject || (bottom_panel_templateObject = bottom_panel_taggedTemplateLiteral(["\n        ", "\n        ", "\n        <converse-message-form jid=\"", "\"></converse-message-form>\n    "])), o.model.ui.get('scrolled') && o.model.get('num_unread') ? (0,external_lit_namespaceObject.html)(bottom_panel_templateObject2 || (bottom_panel_templateObject2 = bottom_panel_taggedTemplateLiteral(["<div class=\"new-msgs-indicator\" @click=", ">\u25BC ", " \u25BC</div>"])), function (ev) {
    return o.viewUnreadMessages(ev);
  }, unread_msgs) : '', shared_api.settings.get('show_toolbar') ? (0,external_lit_namespaceObject.html)(bottom_panel_templateObject3 || (bottom_panel_templateObject3 = bottom_panel_taggedTemplateLiteral(["\n            <converse-chat-toolbar\n                class=\"chat-toolbar no-text-select\"\n                .model=", "\n                ?composing_spoiler=\"", "\"\n                ?show_call_button=\"", "\"\n                ?show_emoji_button=\"", "\"\n                ?show_send_button=\"", "\"\n                ?show_spoiler_button=\"", "\"\n                ?show_toolbar=\"", "\"\n                message_limit=\"", "\"></converse-chat-toolbar>"])), o.model, o.model.get('composing_spoiler'), show_call_button, show_emoji_button, show_send_button, show_spoiler_button, show_toolbar, message_limit) : '', o.model.get('jid'));
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/chatview/styles/chat-bottom-panel.scss
var chat_bottom_panel = __webpack_require__(6160);
;// CONCATENATED MODULE: ./src/plugins/chatview/styles/chat-bottom-panel.scss

      
      
      
      
      
      
      
      
      

var chat_bottom_panel_options = {};

chat_bottom_panel_options.styleTagTransform = (styleTagTransform_default());
chat_bottom_panel_options.setAttributes = (setAttributesWithoutAttributes_default());

      chat_bottom_panel_options.insert = insertBySelector_default().bind(null, "head");
    
chat_bottom_panel_options.domAPI = (styleDomAPI_default());
chat_bottom_panel_options.insertStyleElement = (insertStyleElement_default());

var chat_bottom_panel_update = injectStylesIntoStyleTag_default()(chat_bottom_panel/* default */.Z, chat_bottom_panel_options);




       /* harmony default export */ const styles_chat_bottom_panel = (chat_bottom_panel/* default */.Z && chat_bottom_panel/* default */.Z.locals ? chat_bottom_panel/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/chatview/bottom-panel.js
function bottom_panel_typeof(obj) {
  "@babel/helpers - typeof";

  return bottom_panel_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;
  }, bottom_panel_typeof(obj);
}
function bottom_panel_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  bottom_panel_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" == bottom_panel_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 bottom_panel_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 bottom_panel_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        bottom_panel_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        bottom_panel_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function bottom_panel_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function bottom_panel_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, bottom_panel_toPropertyKey(descriptor.key), descriptor);
  }
}
function bottom_panel_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) bottom_panel_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) bottom_panel_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function bottom_panel_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    bottom_panel_get = Reflect.get.bind();
  } else {
    bottom_panel_get = function _get(target, property, receiver) {
      var base = bottom_panel_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return bottom_panel_get.apply(this, arguments);
}
function bottom_panel_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = bottom_panel_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function bottom_panel_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) bottom_panel_setPrototypeOf(subClass, superClass);
}
function bottom_panel_setPrototypeOf(o, p) {
  bottom_panel_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return bottom_panel_setPrototypeOf(o, p);
}
function bottom_panel_createSuper(Derived) {
  var hasNativeReflectConstruct = bottom_panel_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = bottom_panel_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = bottom_panel_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return bottom_panel_possibleConstructorReturn(this, result);
  };
}
function bottom_panel_possibleConstructorReturn(self, call) {
  if (call && (bottom_panel_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 bottom_panel_assertThisInitialized(self);
}
function bottom_panel_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function bottom_panel_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 bottom_panel_getPrototypeOf(o) {
  bottom_panel_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return bottom_panel_getPrototypeOf(o);
}
function bottom_panel_defineProperty(obj, key, value) {
  key = bottom_panel_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 bottom_panel_toPropertyKey(arg) {
  var key = bottom_panel_toPrimitive(arg, "string");
  return bottom_panel_typeof(key) === "symbol" ? key : String(key);
}
function bottom_panel_toPrimitive(input, hint) {
  if (bottom_panel_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (bottom_panel_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}








var ChatBottomPanel = /*#__PURE__*/function (_ElementView) {
  bottom_panel_inherits(ChatBottomPanel, _ElementView);
  var _super = bottom_panel_createSuper(ChatBottomPanel);
  function ChatBottomPanel() {
    var _this;
    bottom_panel_classCallCheck(this, ChatBottomPanel);
    _this = _super.call(this);
    bottom_panel_defineProperty(bottom_panel_assertThisInitialized(_this), "events", {
      'click .send-button': 'sendButtonClicked',
      'click .toggle-clear': 'clearMessages'
    });
    _this.debouncedRender = lodash_es_debounce(_this.render, 100);
    return _this;
  }
  bottom_panel_createClass(ChatBottomPanel, [{
    key: "connectedCallback",
    value: function () {
      var _connectedCallback = bottom_panel_asyncToGenerator( /*#__PURE__*/bottom_panel_regeneratorRuntime().mark(function _callee() {
        return bottom_panel_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              bottom_panel_get(bottom_panel_getPrototypeOf(ChatBottomPanel.prototype), "connectedCallback", this).call(this);
              _context.next = 3;
              return this.initialize();
            case 3:
              this.render();
            // don't call in initialize, since the MUCBottomPanel subclasses it
            // and we want to render after it has finished as wel.
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function connectedCallback() {
        return _connectedCallback.apply(this, arguments);
      }
      return connectedCallback;
    }()
  }, {
    key: "initialize",
    value: function () {
      var _initialize = bottom_panel_asyncToGenerator( /*#__PURE__*/bottom_panel_regeneratorRuntime().mark(function _callee2() {
        var _this2 = this;
        return bottom_panel_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return shared_api.chatboxes.get(this.getAttribute('jid'));
            case 2:
              this.model = _context2.sent;
              _context2.next = 5;
              return this.model.initialized;
            case 5:
              this.listenTo(this.model, 'change:num_unread', this.debouncedRender);
              this.listenTo(this.model, 'emoji-picker-autocomplete', this.autocompleteInPicker);
              this.addEventListener('focusin', function (ev) {
                return _this2.emitFocused(ev);
              });
              this.addEventListener('focusout', function (ev) {
                return _this2.emitBlurred(ev);
              });
            case 9:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      (0,external_lit_namespaceObject.render)(bottom_panel({
        'model': this.model,
        'viewUnreadMessages': function viewUnreadMessages(ev) {
          return _this3.viewUnreadMessages(ev);
        }
      }), this);
    }
  }, {
    key: "sendButtonClicked",
    value: function sendButtonClicked(ev) {
      var _this$querySelector;
      (_this$querySelector = this.querySelector('converse-message-form')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.onFormSubmitted(ev);
    }
  }, {
    key: "viewUnreadMessages",
    value: function viewUnreadMessages(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      this.model.ui.set({
        'scrolled': false
      });
    }
  }, {
    key: "emitFocused",
    value: function emitFocused(ev) {
      var _converse$chatboxview;
      (_converse$chatboxview = shared_converse.chatboxviews.get(this.getAttribute('jid'))) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.emitFocused(ev);
    }
  }, {
    key: "emitBlurred",
    value: function emitBlurred(ev) {
      var _converse$chatboxview2;
      (_converse$chatboxview2 = shared_converse.chatboxviews.get(this.getAttribute('jid'))) === null || _converse$chatboxview2 === void 0 ? void 0 : _converse$chatboxview2.emitBlurred(ev);
    }
  }, {
    key: "onDrop",
    value: function onDrop(evt) {
      if (evt.dataTransfer.files.length == 0) {
        // There are no files to be dropped, so this isn’t a file
        // transfer operation.
        return;
      }
      evt.preventDefault();
      this.model.sendFiles(evt.dataTransfer.files);
    }
  }, {
    key: "onDragOver",
    value: function onDragOver(ev) {
      // eslint-disable-line class-methods-use-this
      ev.preventDefault();
    }
  }, {
    key: "clearMessages",
    value: function clearMessages(ev) {
      var _ev$preventDefault2;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      utils_clearMessages(this.model);
    }
  }, {
    key: "autocompleteInPicker",
    value: function () {
      var _autocompleteInPicker = bottom_panel_asyncToGenerator( /*#__PURE__*/bottom_panel_regeneratorRuntime().mark(function _callee3(input, value) {
        var emoji_picker, emoji_dropdown;
        return bottom_panel_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return shared_api.emojis.initialize();
            case 2:
              emoji_picker = this.querySelector('converse-emoji-picker');
              if (emoji_picker) {
                emoji_picker.model.set({
                  'ac_position': input.selectionStart,
                  'autocompleting': value,
                  'query': value
                });
                emoji_dropdown = this.querySelector('converse-emoji-dropdown');
                emoji_dropdown === null || emoji_dropdown === void 0 ? void 0 : emoji_dropdown.showMenu();
              }
            case 4:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function autocompleteInPicker(_x, _x2) {
        return _autocompleteInPicker.apply(this, arguments);
      }
      return autocompleteInPicker;
    }()
  }]);
  return ChatBottomPanel;
}(ElementView);

shared_api.elements.define('converse-chat-bottom-panel', ChatBottomPanel);
;// CONCATENATED MODULE: ./src/shared/chat/baseview.js
function baseview_typeof(obj) {
  "@babel/helpers - typeof";

  return baseview_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;
  }, baseview_typeof(obj);
}
function baseview_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function baseview_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, baseview_toPropertyKey(descriptor.key), descriptor);
  }
}
function baseview_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) baseview_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) baseview_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function baseview_toPropertyKey(arg) {
  var key = baseview_toPrimitive(arg, "string");
  return baseview_typeof(key) === "symbol" ? key : String(key);
}
function baseview_toPrimitive(input, hint) {
  if (baseview_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (baseview_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function baseview_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    baseview_get = Reflect.get.bind();
  } else {
    baseview_get = function _get(target, property, receiver) {
      var base = baseview_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return baseview_get.apply(this, arguments);
}
function baseview_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = baseview_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function baseview_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) baseview_setPrototypeOf(subClass, superClass);
}
function baseview_setPrototypeOf(o, p) {
  baseview_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return baseview_setPrototypeOf(o, p);
}
function baseview_createSuper(Derived) {
  var hasNativeReflectConstruct = baseview_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = baseview_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = baseview_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return baseview_possibleConstructorReturn(this, result);
  };
}
function baseview_possibleConstructorReturn(self, call) {
  if (call && (baseview_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 baseview_assertThisInitialized(self);
}
function baseview_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function baseview_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 baseview_getPrototypeOf(o) {
  baseview_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return baseview_getPrototypeOf(o);
}



var BaseChatView = /*#__PURE__*/function (_CustomElement) {
  baseview_inherits(BaseChatView, _CustomElement);
  var _super = baseview_createSuper(BaseChatView);
  function BaseChatView() {
    baseview_classCallCheck(this, BaseChatView);
    return _super.apply(this, arguments);
  }
  baseview_createClass(BaseChatView, [{
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      baseview_get(baseview_getPrototypeOf(BaseChatView.prototype), "disconnectedCallback", this).call(this);
      shared_converse.chatboxviews.remove(this.jid, this);
    }
  }, {
    key: "updated",
    value: function updated() {
      if (this.model && this.jid !== this.model.get('jid')) {
        this.stopListening();
        shared_converse.chatboxviews.remove(this.model.get('jid'), this);
        delete this.model;
        this.requestUpdate();
        this.initialize();
      }
    }
  }, {
    key: "close",
    value: function close(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      return this.model.close(ev);
    }
  }, {
    key: "maybeFocus",
    value: function maybeFocus() {
      shared_api.settings.get('auto_focus') && this.focus();
    }
  }, {
    key: "focus",
    value: function focus() {
      var textarea_el = this.getElementsByClassName('chat-textarea')[0];
      if (textarea_el && document.activeElement !== textarea_el) {
        textarea_el.focus();
      }
      return this;
    }
  }, {
    key: "emitBlurred",
    value: function emitBlurred(ev) {
      if (this.contains(document.activeElement) || this.contains(ev.relatedTarget)) {
        // Something else in this chatbox is still focused
        return;
      }
      /**
       * Triggered when the focus has been removed from a particular chat.
       * @event _converse#chatBoxBlurred
       * @type { _converse.ChatBoxView | _converse.ChatRoomView }
       * @example _converse.api.listen.on('chatBoxBlurred', (view, event) => { ... });
       */
      shared_api.trigger('chatBoxBlurred', this, ev);
    }
  }, {
    key: "emitFocused",
    value: function emitFocused(ev) {
      if (this.contains(ev.relatedTarget)) {
        // Something else in this chatbox was already focused
        return;
      }
      /**
       * Triggered when the focus has been moved to a particular chat.
       * @event _converse#chatBoxFocused
       * @type { _converse.ChatBoxView | _converse.ChatRoomView }
       * @example _converse.api.listen.on('chatBoxFocused', (view, event) => { ... });
       */
      shared_api.trigger('chatBoxFocused', this, ev);
    }
  }, {
    key: "getBottomPanel",
    value: function getBottomPanel() {
      if (this.model.get('type') === shared_converse.CHATROOMS_TYPE) {
        return this.querySelector('converse-muc-bottom-panel');
      } else {
        return this.querySelector('converse-chat-bottom-panel');
      }
    }
  }, {
    key: "getMessageForm",
    value: function getMessageForm() {
      if (this.model.get('type') === shared_converse.CHATROOMS_TYPE) {
        return this.querySelector('converse-muc-message-form');
      } else {
        return this.querySelector('converse-message-form');
      }
    }

    /**
     * Scrolls the chat down.
     *
     * This method will always scroll the chat down, regardless of
     * whether the user scrolled up manually or not.
     * @param { Event } [ev] - An optional event that is the cause for needing to scroll down.
     */
  }, {
    key: "scrollDown",
    value: function scrollDown(ev) {
      var _ev$preventDefault2, _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      if (this.model.ui.get('scrolled')) {
        this.model.ui.set({
          'scrolled': false
        });
      }
      onScrolledDown(this.model);
    }
  }, {
    key: "onWindowStateChanged",
    value: function onWindowStateChanged(data) {
      if (data.state === 'visible') {
        if (!this.model.isHidden()) {
          this.model.clearUnreadMsgCounter();
        }
      } else if (data.state === 'hidden') {
        this.model.setChatState(shared_converse.INACTIVE, {
          'silent': true
        });
        this.model.sendChatState();
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        jid: {
          type: String
        }
      };
    }
  }]);
  return BaseChatView;
}(CustomElement);

;// CONCATENATED MODULE: ./src/plugins/chatview/templates/chat.js
var chat_templateObject, chat_templateObject2, chat_templateObject3;
function chat_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const chat = (function (o) {
  return (0,external_lit_namespaceObject.html)(chat_templateObject || (chat_templateObject = chat_taggedTemplateLiteral(["\n    <div class=\"flyout box-flyout\">\n        <converse-dragresize></converse-dragresize>\n        ", "\n    </div>\n"])), o.model ? (0,external_lit_namespaceObject.html)(chat_templateObject2 || (chat_templateObject2 = chat_taggedTemplateLiteral(["\n            <converse-chat-heading jid=\"", "\" class=\"chat-head chat-head-chatbox row no-gutters\"></converse-chat-heading>\n            <div class=\"chat-body\">\n                <div class=\"chat-content ", "\" aria-live=\"polite\">\n                    <converse-chat-content\n                        class=\"chat-content__messages\"\n                        jid=\"", "\"></converse-chat-content>\n\n                    ", "\n                </div>\n                <converse-chat-bottom-panel jid=\"", "\" class=\"bottom-panel\"> </converse-chat-bottom-panel>\n            </div>\n        "])), o.jid, o.show_send_button ? 'chat-content-sendbutton' : '', o.jid, o.show_help_messages ? (0,external_lit_namespaceObject.html)(chat_templateObject3 || (chat_templateObject3 = chat_taggedTemplateLiteral(["<div class=\"chat-content__help\">\n                            <converse-chat-help\n                                .model=", "\n                                .messages=", "\n                                ?hidden=", "\n                                type=\"info\"\n                                chat_type=\"", "\"\n                            ></converse-chat-help></div>"])), o.model, o.help_messages, !o.show_help_messages, shared_converse.CHATROOMS_TYPE) : '', o.jid) : '');
});
;// CONCATENATED MODULE: ./src/plugins/chatview/chat.js
function chat_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_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;
  }, chat_typeof(obj);
}
function chat_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chat_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" == chat_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 chat_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 chat_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chat_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chat_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function chat_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function chat_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, chat_toPropertyKey(descriptor.key), descriptor);
  }
}
function chat_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) chat_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) chat_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function chat_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) chat_setPrototypeOf(subClass, superClass);
}
function chat_setPrototypeOf(o, p) {
  chat_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return chat_setPrototypeOf(o, p);
}
function chat_createSuper(Derived) {
  var hasNativeReflectConstruct = chat_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = chat_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = chat_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return chat_possibleConstructorReturn(this, result);
  };
}
function chat_possibleConstructorReturn(self, call) {
  if (call && (chat_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 chat_assertThisInitialized(self);
}
function chat_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function chat_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 chat_getPrototypeOf(o) {
  chat_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return chat_getPrototypeOf(o);
}
function chat_defineProperty(obj, key, value) {
  key = chat_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 chat_toPropertyKey(arg) {
  var key = chat_toPrimitive(arg, "string");
  return chat_typeof(key) === "symbol" ? key : String(key);
}
function chat_toPrimitive(input, hint) {
  if (chat_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chat_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}







/**
 * The view of an open/ongoing chat conversation.
 * @class
 * @namespace _converse.ChatBoxView
 * @memberOf _converse
 */
var ChatView = /*#__PURE__*/function (_BaseChatView) {
  chat_inherits(ChatView, _BaseChatView);
  var _super = chat_createSuper(ChatView);
  function ChatView() {
    var _this;
    chat_classCallCheck(this, ChatView);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    chat_defineProperty(chat_assertThisInitialized(_this), "length", 200);
    return _this;
  }
  chat_createClass(ChatView, [{
    key: "initialize",
    value: function () {
      var _initialize = chat_asyncToGenerator( /*#__PURE__*/chat_regeneratorRuntime().mark(function _callee() {
        var _this2 = this;
        return chat_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              shared_converse.chatboxviews.add(this.jid, this);
              this.model = shared_converse.chatboxes.get(this.jid);
              this.listenTo(shared_converse, 'windowStateChanged', this.onWindowStateChanged);
              this.listenTo(this.model, 'change:hidden', function () {
                return !_this2.model.get('hidden') && _this2.afterShown();
              });
              this.listenTo(this.model, 'change:show_help_messages', function () {
                return _this2.requestUpdate();
              });
              _context.next = 7;
              return this.model.messages.fetched;
            case 7:
              !this.model.get('hidden') && this.afterShown();
              /**
               * Triggered once the {@link _converse.ChatBoxView} has been initialized
               * @event _converse#chatBoxViewInitialized
               * @type { _converse.ChatBoxView }
               * @example _converse.api.listen.on('chatBoxViewInitialized', view => { ... });
               */
              shared_api.trigger('chatBoxViewInitialized', this);
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return chat(Object.assign({
        'model': this.model,
        'help_messages': this.getHelpMessages(),
        'show_help_messages': this.model.get('show_help_messages')
      }, this.model.toJSON()));
    }
  }, {
    key: "getHelpMessages",
    value: function getHelpMessages() {
      // eslint-disable-line class-methods-use-this
      return ["<strong>/clear</strong>: ".concat(__('Remove messages')), "<strong>/close</strong>: ".concat(__('Close this chat')), "<strong>/me</strong>: ".concat(__('Write in the third person')), "<strong>/help</strong>: ".concat(__('Show this menu'))];
    }
  }, {
    key: "afterShown",
    value: function afterShown() {
      this.model.setChatState(shared_converse.ACTIVE);
      this.model.clearUnreadMsgCounter();
      this.maybeFocus();
    }
  }]);
  return ChatView;
}(BaseChatView);

shared_api.elements.define('converse-chat', ChatView);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/chatview/styles/index.scss
var chatview_styles = __webpack_require__(6172);
;// CONCATENATED MODULE: ./src/plugins/chatview/styles/index.scss

      
      
      
      
      
      
      
      
      

var styles_options = {};

styles_options.styleTagTransform = (styleTagTransform_default());
styles_options.setAttributes = (setAttributesWithoutAttributes_default());

      styles_options.insert = insertBySelector_default().bind(null, "head");
    
styles_options.domAPI = (styleDomAPI_default());
styles_options.insertStyleElement = (insertStyleElement_default());

var styles_update = injectStylesIntoStyleTag_default()(chatview_styles/* default */.Z, styles_options);




       /* harmony default export */ const plugins_chatview_styles = (chatview_styles/* default */.Z && chatview_styles/* default */.Z.locals ? chatview_styles/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/chatview/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */








var chatview_Strophe = public_converse.env.Strophe;
public_converse.plugins.add('converse-chatview', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ['converse-chatboxviews', 'converse-chat', 'converse-disco', 'converse-modal'],
  initialize: function initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    shared_api.settings.extend({
      'allowed_audio_domains': null,
      'allowed_image_domains': null,
      'allowed_video_domains': null,
      'auto_focus': true,
      'debounced_content_rendering': true,
      'filter_url_query_params': null,
      'image_urls_regex': null,
      'message_limit': 0,
      'muc_hats': ['xep317'],
      'render_media': true,
      'show_message_avatar': true,
      'show_retraction_warning': true,
      'show_send_button': true,
      'show_toolbar': true,
      'time_format': 'HH:mm',
      'use_system_emojis': true,
      'visible_toolbar_buttons': {
        'call': false,
        'clear': true,
        'emoji': true,
        'spoiler': true
      }
    });
    shared_converse.ChatBoxView = ChatView;
    shared_api.listen.on('connected', function () {
      return shared_api.disco.own.features.add(chatview_Strophe.NS.SPOILER);
    });
    shared_api.listen.on('chatBoxClosed', function (model) {
      return utils_clearHistory(model.get('jid'));
    });
  }
});
;// CONCATENATED MODULE: ./src/shared/components/brand-byline.js
function brand_byline_typeof(obj) {
  "@babel/helpers - typeof";

  return brand_byline_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;
  }, brand_byline_typeof(obj);
}
var brand_byline_templateObject, brand_byline_templateObject2;
function brand_byline_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function brand_byline_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function brand_byline_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, brand_byline_toPropertyKey(descriptor.key), descriptor);
  }
}
function brand_byline_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) brand_byline_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) brand_byline_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function brand_byline_toPropertyKey(arg) {
  var key = brand_byline_toPrimitive(arg, "string");
  return brand_byline_typeof(key) === "symbol" ? key : String(key);
}
function brand_byline_toPrimitive(input, hint) {
  if (brand_byline_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (brand_byline_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function brand_byline_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) brand_byline_setPrototypeOf(subClass, superClass);
}
function brand_byline_setPrototypeOf(o, p) {
  brand_byline_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return brand_byline_setPrototypeOf(o, p);
}
function brand_byline_createSuper(Derived) {
  var hasNativeReflectConstruct = brand_byline_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = brand_byline_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = brand_byline_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return brand_byline_possibleConstructorReturn(this, result);
  };
}
function brand_byline_possibleConstructorReturn(self, call) {
  if (call && (brand_byline_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 brand_byline_assertThisInitialized(self);
}
function brand_byline_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function brand_byline_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 brand_byline_getPrototypeOf(o) {
  brand_byline_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return brand_byline_getPrototypeOf(o);
}



var ConverseBrandByline = /*#__PURE__*/function (_CustomElement) {
  brand_byline_inherits(ConverseBrandByline, _CustomElement);
  var _super = brand_byline_createSuper(ConverseBrandByline);
  function ConverseBrandByline() {
    brand_byline_classCallCheck(this, ConverseBrandByline);
    return _super.apply(this, arguments);
  }
  brand_byline_createClass(ConverseBrandByline, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      var is_fullscreen = shared_api.settings.get('view_mode') === 'fullscreen';
      return (0,external_lit_namespaceObject.html)(brand_byline_templateObject || (brand_byline_templateObject = brand_byline_taggedTemplateLiteral(["\n            ", "\n            "])), is_fullscreen ? (0,external_lit_namespaceObject.html)(brand_byline_templateObject2 || (brand_byline_templateObject2 = brand_byline_taggedTemplateLiteral(["\n                    <p class=\"brand-subtitle\">", "</p>\n                    <p class=\"brand-subtitle\">\n                        <a target=\"_blank\" rel=\"nofollow\" href=\"https://conversejs.org\">Open Source</a> XMPP chat client\n                        brought to you by <a target=\"_blank\" rel=\"nofollow\" href=\"https://opkode.com\">Opkode</a>\n                    </p>\n                    <p class=\"brand-subtitle\">\n                        <a target=\"_blank\" rel=\"nofollow\" href=\"https://hosted.weblate.org/projects/conversejs/#languages\"\n                            >Translate</a\n                        >\n                        it into your own language\n                    </p>\n                "])), shared_converse.VERSION_NAME) : '');
    }
  }]);
  return ConverseBrandByline;
}(CustomElement);
shared_api.elements.define('converse-brand-byline', ConverseBrandByline);
;// CONCATENATED MODULE: ./src/shared/components/brand-logo.js
function brand_logo_typeof(obj) {
  "@babel/helpers - typeof";

  return brand_logo_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;
  }, brand_logo_typeof(obj);
}
var brand_logo_templateObject, brand_logo_templateObject2;
function brand_logo_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function brand_logo_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function brand_logo_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, brand_logo_toPropertyKey(descriptor.key), descriptor);
  }
}
function brand_logo_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) brand_logo_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) brand_logo_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function brand_logo_toPropertyKey(arg) {
  var key = brand_logo_toPrimitive(arg, "string");
  return brand_logo_typeof(key) === "symbol" ? key : String(key);
}
function brand_logo_toPrimitive(input, hint) {
  if (brand_logo_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (brand_logo_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function brand_logo_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) brand_logo_setPrototypeOf(subClass, superClass);
}
function brand_logo_setPrototypeOf(o, p) {
  brand_logo_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return brand_logo_setPrototypeOf(o, p);
}
function brand_logo_createSuper(Derived) {
  var hasNativeReflectConstruct = brand_logo_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = brand_logo_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = brand_logo_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return brand_logo_possibleConstructorReturn(this, result);
  };
}
function brand_logo_possibleConstructorReturn(self, call) {
  if (call && (brand_logo_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 brand_logo_assertThisInitialized(self);
}
function brand_logo_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function brand_logo_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 brand_logo_getPrototypeOf(o) {
  brand_logo_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return brand_logo_getPrototypeOf(o);
}



var ConverseBrandLogo = /*#__PURE__*/function (_CustomElement) {
  brand_logo_inherits(ConverseBrandLogo, _CustomElement);
  var _super = brand_logo_createSuper(ConverseBrandLogo);
  function ConverseBrandLogo() {
    brand_logo_classCallCheck(this, ConverseBrandLogo);
    return _super.apply(this, arguments);
  }
  brand_logo_createClass(ConverseBrandLogo, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      var is_fullscreen = shared_api.settings.get('view_mode') === 'fullscreen';
      return (0,external_lit_namespaceObject.html)(brand_logo_templateObject || (brand_logo_templateObject = brand_logo_taggedTemplateLiteral(["\n            <a class=\"brand-heading\" href=\"https://conversejs.org\" target=\"_blank\" rel=\"noopener\">\n                <span class=\"brand-name-wrapper ", "\">\n                    <svg\n                        class=\"converse-svg-logo\"\n                        xmlns:svg=\"http://www.w3.org/2000/svg\"\n                        xmlns=\"http://www.w3.org/2000/svg\"\n                        xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n                        viewBox=\"0 0 364 364\">\n\n                        <title>Converse</title>\n                        <g class=\"cls-1\" id=\"g904\">\n                            <g data-name=\"Layer 2\">\n                                <g data-name=\"Layer 7\">\n                                    <path\n                                        class=\"cls-3\"\n                                        d=\"M221.46,103.71c0,18.83-29.36,18.83-29.12,0C192.1,84.88,221.46,84.88,221.46,103.71Z\"\n                                    />\n                                    <path\n                                        class=\"cls-4\"\n                                        d=\"M179.9,4.15A175.48,175.48,0,1,0,355.38,179.63,175.48,175.48,0,0,0,179.9,4.15Zm-40.79,264.5c-.23-17.82,27.58-17.82,27.58,0S138.88,286.48,139.11,268.65ZM218.6,168.24A79.65,79.65,0,0,1,205.15,174a12.76,12.76,0,0,0-6.29,4.65L167.54,222a1.36,1.36,0,0,1-2.46-.8v-35.8a2.58,2.58,0,0,0-3.06-2.53c-15.43,3-30.23,7.7-42.73,19.94-38.8,38-29.42,105.69,16.09,133.16a162.25,162.25,0,0,1-91.47-67.27C-3.86,182.26,34.5,47.25,138.37,25.66c46.89-9.75,118.25,5.16,123.73,62.83C265.15,120.64,246.56,152.89,218.6,168.24Z\"\n                                    />\n                                </g>\n                            </g>\n                        </g>\n                    </svg>\n                    <span class=\"brand-name\">\n                        <span class=\"brand-name__text\">converse<span class=\"subdued\">.js</span></span>\n                        ", "\n                    </span>\n                </span>\n            </a>\n        "])), is_fullscreen ? 'brand-name-wrapper--fullscreen' : '', is_fullscreen ? (0,external_lit_namespaceObject.html)(brand_logo_templateObject2 || (brand_logo_templateObject2 = brand_logo_taggedTemplateLiteral(["\n                                <p class=\"byline\">messaging freedom</p>\n                            "]))) : '');
    }
  }]);
  return ConverseBrandLogo;
}(CustomElement);
shared_api.elements.define('converse-brand-logo', ConverseBrandLogo);
;// CONCATENATED MODULE: ./node_modules/lit/html.js

;// CONCATENATED MODULE: ./src/shared/components/brand-heading.js
function brand_heading_typeof(obj) {
  "@babel/helpers - typeof";

  return brand_heading_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;
  }, brand_heading_typeof(obj);
}
var brand_heading_templateObject;
function brand_heading_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function brand_heading_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function brand_heading_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, brand_heading_toPropertyKey(descriptor.key), descriptor);
  }
}
function brand_heading_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) brand_heading_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) brand_heading_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function brand_heading_toPropertyKey(arg) {
  var key = brand_heading_toPrimitive(arg, "string");
  return brand_heading_typeof(key) === "symbol" ? key : String(key);
}
function brand_heading_toPrimitive(input, hint) {
  if (brand_heading_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (brand_heading_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function brand_heading_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) brand_heading_setPrototypeOf(subClass, superClass);
}
function brand_heading_setPrototypeOf(o, p) {
  brand_heading_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return brand_heading_setPrototypeOf(o, p);
}
function brand_heading_createSuper(Derived) {
  var hasNativeReflectConstruct = brand_heading_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = brand_heading_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = brand_heading_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return brand_heading_possibleConstructorReturn(this, result);
  };
}
function brand_heading_possibleConstructorReturn(self, call) {
  if (call && (brand_heading_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 brand_heading_assertThisInitialized(self);
}
function brand_heading_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function brand_heading_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 brand_heading_getPrototypeOf(o) {
  brand_heading_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return brand_heading_getPrototypeOf(o);
}





var ConverseBrandHeading = /*#__PURE__*/function (_CustomElement) {
  brand_heading_inherits(ConverseBrandHeading, _CustomElement);
  var _super = brand_heading_createSuper(ConverseBrandHeading);
  function ConverseBrandHeading() {
    brand_heading_classCallCheck(this, ConverseBrandHeading);
    return _super.apply(this, arguments);
  }
  brand_heading_createClass(ConverseBrandHeading, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      return (0,external_lit_html_namespaceObject.html)(brand_heading_templateObject || (brand_heading_templateObject = brand_heading_taggedTemplateLiteral(["\n            <converse-brand-logo></converse-brand-logo>\n            <converse-brand-byline></converse-brand-byline>\n        "])));
    }
  }]);
  return ConverseBrandHeading;
}(CustomElement);
shared_api.elements.define('converse-brand-heading', ConverseBrandHeading);
;// CONCATENATED MODULE: ./src/plugins/controlbox/constants.js

var constants_Strophe = public_converse.env.Strophe;
var REPORTABLE_STATUSES = [constants_Strophe.Status.ERROR, constants_Strophe.Status.CONNECTING, constants_Strophe.Status.CONNFAIL, constants_Strophe.Status.AUTHENTICATING, constants_Strophe.Status.AUTHFAIL, constants_Strophe.Status.DISCONNECTING, constants_Strophe.Status.RECONNECTING];
var PRETTY_CONNECTION_STATUS = Object.fromEntries([[constants_Strophe.Status.ERROR, 'Error'], [constants_Strophe.Status.CONNECTING, 'Connecting'], [constants_Strophe.Status.CONNFAIL, 'Connection failure'], [constants_Strophe.Status.AUTHENTICATING, 'Authenticating'], [constants_Strophe.Status.AUTHFAIL, 'Authentication failure'], [constants_Strophe.Status.CONNECTED, 'Connected'], [constants_Strophe.Status.DISCONNECTED, 'Disconnected'], [constants_Strophe.Status.DISCONNECTING, 'Disconnecting'], [constants_Strophe.Status.ATTACHED, 'Attached'], [constants_Strophe.Status.REDIRECT, 'Redirect'], [constants_Strophe.Status.CONNTIMEOUT, 'Connection timeout'], [constants_Strophe.Status.RECONNECTING, 'Reconnecting']]);
var CONNECTION_STATUS_CSS_CLASS = Object.fromEntries([[constants_Strophe.Status.ERROR, 'error'], [constants_Strophe.Status.CONNECTING, 'info'], [constants_Strophe.Status.CONNFAIL, 'error'], [constants_Strophe.Status.AUTHENTICATING, 'info'], [constants_Strophe.Status.AUTHFAIL, 'error'], [constants_Strophe.Status.CONNECTED, 'info'], [constants_Strophe.Status.DISCONNECTED, 'error'], [constants_Strophe.Status.DISCONNECTING, 'warn'], [constants_Strophe.Status.ATTACHED, 'info'], [constants_Strophe.Status.REDIRECT, 'info'], [constants_Strophe.Status.RECONNECTING, 'warn']]);
;// CONCATENATED MODULE: ./src/plugins/controlbox/templates/loginform.js
var loginform_templateObject, loginform_templateObject2, loginform_templateObject3, loginform_templateObject4, loginform_templateObject5, loginform_templateObject6, loginform_templateObject7, loginform_templateObject8, loginform_templateObject9;
function loginform_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}







var trust_checkbox = function trust_checkbox(checked) {
  var i18n_hint_trusted = __('To improve performance, we cache your data in this browser. ' + 'Uncheck this box if this is a public computer or if you want your data to be deleted when you log out. ' + "It's important that you explicitly log out, otherwise not all cached data might be deleted. " + 'Please note, when using an untrusted device, OMEMO encryption is NOT available.');
  var i18n_trusted = __('This is a trusted device');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject || (loginform_templateObject = loginform_taggedTemplateLiteral(["\n        <div class=\"form-group form-check login-trusted\">\n            <input\n                id=\"converse-login-trusted\"\n                type=\"checkbox\"\n                class=\"form-check-input\"\n                name=\"trusted\"\n                ?checked=", "\n            />\n            <label for=\"converse-login-trusted\" class=\"form-check-label login-trusted__desc\">", "</label>\n\n            <converse-icon\n                class=\"fa fa-info-circle\"\n                data-toggle=\"popover\"\n                data-title=\"Trusted device?\"\n                data-content=\"", "\"\n                size=\"1.2em\"\n                title=\"", "\"\n            ></converse-icon>\n        </div>\n    "])), checked, i18n_trusted, i18n_hint_trusted, i18n_hint_trusted);
};
var connection_url_input = function connection_url_input() {
  var i18n_connection_url = __('Connection URL');
  var i18n_form_help = __('HTTP or websocket URL that is used to connect to your XMPP server');
  var i18n_placeholder = __('e.g. wss://example.org/xmpp-websocket');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject2 || (loginform_templateObject2 = loginform_taggedTemplateLiteral(["\n        <div class=\"form-group fade-in\">\n            <label for=\"converse-conn-url\">", "</label>\n            <p class=\"form-help instructions\">", "</p>\n            <input\n                id=\"converse-conn-url\"\n                class=\"form-control\"\n                type=\"url\"\n                name=\"connection-url\"\n                placeholder=\"", "\"\n            />\n        </div>\n    "])), i18n_connection_url, i18n_form_help, i18n_placeholder);
};
var password_input = function password_input() {
  var _api$settings$get;
  var i18n_password = __('Password');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject3 || (loginform_templateObject3 = loginform_taggedTemplateLiteral(["\n        <div class=\"form-group\">\n            <label for=\"converse-login-password\">", "</label>\n            <input\n                id=\"converse-login-password\"\n                class=\"form-control\"\n                required=\"required\"\n                value=\"", "\"\n                type=\"password\"\n                name=\"password\"\n                placeholder=\"", "\"\n            />\n        </div>\n    "])), i18n_password, (_api$settings$get = shared_api.settings.get('password')) !== null && _api$settings$get !== void 0 ? _api$settings$get : '', i18n_password);
};
var tplRegisterLink = function tplRegisterLink() {
  var i18n_create_account = __('Create an account');
  var i18n_hint_no_account = __("Don't have a chat account?");
  return (0,external_lit_namespaceObject.html)(loginform_templateObject4 || (loginform_templateObject4 = loginform_taggedTemplateLiteral(["\n        <fieldset class=\"switch-form\">\n            <p>", "</p>\n            <p>\n                <a class=\"register-account toggle-register-login\" href=\"#converse/register\">", "</a>\n            </p>\n        </fieldset>\n    "])), i18n_hint_no_account, i18n_create_account);
};
var tplShowRegisterLink = function tplShowRegisterLink() {
  return shared_api.settings.get('allow_registration') && !shared_api.settings.get('auto_login') && shared_converse.pluggable.plugins['converse-register'].enabled(shared_converse);
};
var auth_fields = function auth_fields(el) {
  var _api$settings$get2;
  var authentication = shared_api.settings.get('authentication');
  var i18n_login = __('Log in');
  var i18n_xmpp_address = __('XMPP Address');
  var locked_domain = shared_api.settings.get('locked_domain');
  var default_domain = shared_api.settings.get('default_domain');
  var placeholder_username = (locked_domain || default_domain) && __('Username') || __('user@domain');
  var show_trust_checkbox = shared_api.settings.get('allow_user_trust_override');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject5 || (loginform_templateObject5 = loginform_taggedTemplateLiteral(["\n        <div class=\"form-group\">\n            <label for=\"converse-login-jid\">", ":</label>\n            <input\n                id=\"converse-login-jid\"\n                ?autofocus=", "\n                @changed=", "\n                value=\"", "\"\n                required\n                class=\"form-control\"\n                type=\"text\"\n                name=\"jid\"\n                placeholder=\"", "\"\n            />\n        </div>\n        ", "\n        ", "\n        ", "\n        <fieldset class=\"form-group buttons\">\n            <input class=\"btn btn-primary\" type=\"submit\" value=\"", "\" />\n        </fieldset>\n        ", "\n    "])), i18n_xmpp_address, shared_api.settings.get('auto_focus') ? true : false, el.validate, (_api$settings$get2 = shared_api.settings.get('jid')) !== null && _api$settings$get2 !== void 0 ? _api$settings$get2 : '', placeholder_username, authentication !== EXTERNAL ? password_input() : '', shared_api.settings.get('show_connection_url_input') ? connection_url_input() : '', show_trust_checkbox ? trust_checkbox(show_trust_checkbox === 'off' ? false : true) : '', i18n_login, tplShowRegisterLink() ? tplRegisterLink() : '');
};
var form_fields = function form_fields(el) {
  var authentication = shared_api.settings.get('authentication');
  var i18n_disconnected = __('Disconnected');
  var i18n_anon_login = __('Click here to log in anonymously');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject6 || (loginform_templateObject6 = loginform_taggedTemplateLiteral(["\n        ", "\n        ", "\n        ", "\n    "])), authentication == LOGIN || authentication == EXTERNAL ? auth_fields(el) : '', authentication == ANONYMOUS ? (0,external_lit_namespaceObject.html)(loginform_templateObject7 || (loginform_templateObject7 = loginform_taggedTemplateLiteral(["<input class=\"btn btn-primary login-anon\" type=\"submit\" value=\"", "\" />"])), i18n_anon_login) : '', authentication == PREBIND ? (0,external_lit_namespaceObject.html)(loginform_templateObject8 || (loginform_templateObject8 = loginform_taggedTemplateLiteral(["<p>", "</p>"])), i18n_disconnected) : '');
};
/* harmony default export */ const loginform = (function (el) {
  var connection_status = shared_converse.connfeedback.get('connection_status');
  var feedback_class, pretty_status;
  if (REPORTABLE_STATUSES.includes(connection_status)) {
    pretty_status = PRETTY_CONNECTION_STATUS[connection_status];
    feedback_class = CONNECTION_STATUS_CSS_CLASS[connection_status];
  }
  var conn_feedback_message = shared_converse.connfeedback.get('message');
  return (0,external_lit_namespaceObject.html)(loginform_templateObject9 || (loginform_templateObject9 = loginform_taggedTemplateLiteral([" <converse-brand-heading></converse-brand-heading>\n        <form id=\"converse-login\" class=\"converse-form\" method=\"post\" @submit=", ">\n            <div class=\"conn-feedback fade-in ", "\">\n                <p class=\"feedback-subject\">", "</p>\n                <p class=\"feedback-message ", "\">", "</p>\n            </div>\n            ", "\n        </form>"])), el.onLoginFormSubmitted, !pretty_status ? 'hidden' : feedback_class, pretty_status, !conn_feedback_message ? 'hidden' : '', conn_feedback_message, CONNECTION_STATUS[connection_status] === 'CONNECTING' ? spinner({
    'classes': 'hor_centered'
  }) : form_fields(el));
});
;// CONCATENATED MODULE: ./src/plugins/controlbox/utils.js


var controlbox_utils_converse$env = public_converse.env,
  controlbox_utils_Strophe = controlbox_utils_converse$env.Strophe,
  controlbox_utils_u = controlbox_utils_converse$env.u;
function addControlBox() {
  var _converse$chatboxview;
  var m = shared_converse.chatboxes.add(new shared_converse.ControlBox({
    'id': 'controlbox'
  }));
  (_converse$chatboxview = shared_converse.chatboxviews.get('controlbox')) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.setModel();
  return m;
}
function showControlBox(ev) {
  var _ev$preventDefault;
  ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
  var controlbox = shared_converse.chatboxes.get('controlbox') || addControlBox();
  controlbox_utils_u.safeSave(controlbox, {
    'closed': false
  });
}
function navigateToControlBox(jid) {
  showControlBox();
  var model = shared_converse.chatboxes.get(jid);
  controlbox_utils_u.safeSave(model, {
    'hidden': true
  });
}
function disconnect() {
  /* Upon disconnection, set connected to `false`, so that if
   * we reconnect, "onConnected" will be called,
   * to fetch the roster again and to send out a presence stanza.
   */
  var view = shared_converse.chatboxviews.get('controlbox');
  view.model.set({
    'connected': false
  });
  return view;
}
function controlbox_utils_clearSession() {
  var chatboxviews = shared_converse === null || shared_converse === void 0 ? void 0 : shared_converse.chatboxviews;
  var view = chatboxviews && chatboxviews.get('controlbox');
  if (view) {
    controlbox_utils_u.safeSave(view.model, {
      'connected': false
    });
    if (view !== null && view !== void 0 && view.controlbox_pane) {
      view.controlbox_pane.remove();
      delete view.controlbox_pane;
    }
  }
}
function onChatBoxesFetched() {
  var controlbox = shared_converse.chatboxes.get('controlbox') || addControlBox();
  controlbox.save({
    'connected': true
  });
}

/**
 * Given the login `<form>` element, parse its data and update the
 * converse settings with the supplied JID, password and connection URL.
 * @param { HTMLElement } form
 * @param { Object } settings - Extra settings that may be passed in and will
 *  also be set together with the form settings.
 */
function updateSettingsWithFormData(form) {
  var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var form_data = new FormData(form);
  var connection_url = form_data.get('connection-url');
  if (connection_url !== null && connection_url !== void 0 && connection_url.startsWith('ws')) {
    settings['websocket_url'] = connection_url;
  } else if (connection_url !== null && connection_url !== void 0 && connection_url.startsWith('http')) {
    settings['bosh_service_url'] = connection_url;
  }
  var jid = form_data.get('jid');
  if (shared_api.settings.get('locked_domain')) {
    var last_part = '@' + shared_api.settings.get('locked_domain');
    if (jid.endsWith(last_part)) {
      jid = jid.substr(0, jid.length - last_part.length);
    }
    jid = controlbox_utils_Strophe.escapeNode(jid) + last_part;
  } else if (shared_api.settings.get('default_domain') && !jid.includes('@')) {
    jid = jid + '@' + shared_api.settings.get('default_domain');
  }
  settings['jid'] = jid;
  settings['password'] = form_data.get('password');
  shared_api.settings.set(settings);
  shared_converse.config.save({
    'trusted': form_data.get('trusted') && true || false
  });
}
function validateJID(form) {
  var jid_element = form.querySelector('input[name=jid]');
  if (jid_element.value && !shared_api.settings.get('locked_domain') && !shared_api.settings.get('default_domain') && !controlbox_utils_u.isValidJID(jid_element.value)) {
    jid_element.setCustomValidity(__('Please enter a valid XMPP address'));
    return false;
  }
  jid_element.setCustomValidity('');
  return true;
}
;// CONCATENATED MODULE: ./src/plugins/controlbox/loginform.js
function loginform_typeof(obj) {
  "@babel/helpers - typeof";

  return loginform_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;
  }, loginform_typeof(obj);
}
function loginform_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  loginform_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" == loginform_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 loginform_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 loginform_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        loginform_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        loginform_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function loginform_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function loginform_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, loginform_toPropertyKey(descriptor.key), descriptor);
  }
}
function loginform_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) loginform_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) loginform_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function loginform_toPropertyKey(arg) {
  var key = loginform_toPrimitive(arg, "string");
  return loginform_typeof(key) === "symbol" ? key : String(key);
}
function loginform_toPrimitive(input, hint) {
  if (loginform_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (loginform_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function loginform_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    loginform_get = Reflect.get.bind();
  } else {
    loginform_get = function _get(target, property, receiver) {
      var base = loginform_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return loginform_get.apply(this, arguments);
}
function loginform_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = loginform_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function loginform_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) loginform_setPrototypeOf(subClass, superClass);
}
function loginform_setPrototypeOf(o, p) {
  loginform_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return loginform_setPrototypeOf(o, p);
}
function loginform_createSuper(Derived) {
  var hasNativeReflectConstruct = loginform_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = loginform_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = loginform_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return loginform_possibleConstructorReturn(this, result);
  };
}
function loginform_possibleConstructorReturn(self, call) {
  if (call && (loginform_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 loginform_assertThisInitialized(self);
}
function loginform_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function loginform_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 loginform_getPrototypeOf(o) {
  loginform_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return loginform_getPrototypeOf(o);
}







var loginform_converse$env = public_converse.env,
  loginform_Strophe = loginform_converse$env.Strophe,
  loginform_u = loginform_converse$env.u;
var LoginForm = /*#__PURE__*/function (_CustomElement) {
  loginform_inherits(LoginForm, _CustomElement);
  var _super = loginform_createSuper(LoginForm);
  function LoginForm() {
    loginform_classCallCheck(this, LoginForm);
    return _super.apply(this, arguments);
  }
  loginform_createClass(LoginForm, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.listenTo(shared_converse.connfeedback, 'change', function () {
        return _this.requestUpdate();
      });
      this.handler = function () {
        return _this.requestUpdate();
      };
    }
  }, {
    key: "connectedCallback",
    value: function connectedCallback() {
      loginform_get(loginform_getPrototypeOf(LoginForm.prototype), "connectedCallback", this).call(this);
      shared_api.settings.listen.on('change', this.handler);
    }
  }, {
    key: "disconnectedCallback",
    value: function disconnectedCallback() {
      loginform_get(loginform_getPrototypeOf(LoginForm.prototype), "disconnectedCallback", this).call(this);
      shared_api.settings.listen.not('change', this.handler);
    }
  }, {
    key: "render",
    value: function render() {
      return loginform(this);
    }
  }, {
    key: "firstUpdated",
    value: function firstUpdated() {
      this.initPopovers();
    }
  }, {
    key: "onLoginFormSubmitted",
    value: function () {
      var _onLoginFormSubmitted = loginform_asyncToGenerator( /*#__PURE__*/loginform_regeneratorRuntime().mark(function _callee(ev) {
        return loginform_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : ev.preventDefault();
              if (!(shared_api.settings.get('authentication') === ANONYMOUS)) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return", this.connect(shared_converse.jid));
            case 3:
              if (validateJID(ev.target)) {
                _context.next = 5;
                break;
              }
              return _context.abrupt("return");
            case 5:
              updateSettingsWithFormData(ev.target);
              if (!(!shared_api.settings.get('bosh_service_url') && !shared_api.settings.get('websocket_url'))) {
                _context.next = 9;
                break;
              }
              _context.next = 9;
              return this.discoverConnectionMethods(ev);
            case 9:
              if (shared_api.settings.get('bosh_service_url') || shared_api.settings.get('websocket_url')) {
                // FIXME: The connection class will still try to discover XEP-0156 connection methods
                this.connect();
              } else {
                shared_api.settings.set('show_connection_url_input', true);
              }
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function onLoginFormSubmitted(_x) {
        return _onLoginFormSubmitted.apply(this, arguments);
      }
      return onLoginFormSubmitted;
    }() // eslint-disable-next-line class-methods-use-this
  }, {
    key: "discoverConnectionMethods",
    value: function discoverConnectionMethods(ev) {
      var _converse$connection;
      if (!shared_api.settings.get("discover_connection_methods")) {
        return;
      }
      var form_data = new FormData(ev.target);
      var jid = form_data.get('jid');
      var domain = loginform_Strophe.getDomainFromJid(jid);
      if (!((_converse$connection = shared_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.jid) || jid && !loginform_u.isSameDomain(shared_converse.connection.jid, jid)) {
        initConnection();
      }
      return shared_converse.connection.discoverConnectionMethods(domain);
    }
  }, {
    key: "initPopovers",
    value: function initPopovers() {
      var _this2 = this;
      Array.from(this.querySelectorAll('[data-title]')).forEach(function (el) {
        new (bootstrap_native_default()).Popover(el, {
          'trigger': shared_api.settings.get('view_mode') === 'mobile' && 'click' || 'hover',
          'dismissible': shared_api.settings.get('view_mode') === 'mobile' && true || false,
          'container': _this2.parentElement.parentElement.parentElement
        });
      });
    }

    // eslint-disable-next-line class-methods-use-this
  }, {
    key: "connect",
    value: function connect(jid) {
      var _converse$connection2;
      if (['converse/login', 'converse/register'].includes(shared_converse.router.history.getFragment())) {
        shared_converse.router.navigate('', {
          'replace': true
        });
      }
      (_converse$connection2 = shared_converse.connection) === null || _converse$connection2 === void 0 ? void 0 : _converse$connection2.reset();
      shared_api.user.login(jid);
    }
  }]);
  return LoginForm;
}(CustomElement);
shared_api.elements.define('converse-login-form', LoginForm);
;// CONCATENATED MODULE: ./src/plugins/controlbox/templates/navback.js
var navback_templateObject;
function navback_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const navback = (function (jid) {
  return (0,external_lit_namespaceObject.html)(navback_templateObject || (navback_templateObject = navback_taggedTemplateLiteral(["<converse-icon size=\"1em\" class=\"fa fa-arrow-left\" @click=", "></converse-icon>"])), function () {
    return navigateToControlBox(jid);
  });
});
;// CONCATENATED MODULE: ./src/plugins/controlbox/navback.js
function navback_typeof(obj) {
  "@babel/helpers - typeof";

  return navback_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;
  }, navback_typeof(obj);
}
function navback_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function navback_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, navback_toPropertyKey(descriptor.key), descriptor);
  }
}
function navback_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) navback_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) navback_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function navback_toPropertyKey(arg) {
  var key = navback_toPrimitive(arg, "string");
  return navback_typeof(key) === "symbol" ? key : String(key);
}
function navback_toPrimitive(input, hint) {
  if (navback_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (navback_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function navback_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) navback_setPrototypeOf(subClass, superClass);
}
function navback_setPrototypeOf(o, p) {
  navback_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return navback_setPrototypeOf(o, p);
}
function navback_createSuper(Derived) {
  var hasNativeReflectConstruct = navback_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = navback_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = navback_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return navback_possibleConstructorReturn(this, result);
  };
}
function navback_possibleConstructorReturn(self, call) {
  if (call && (navback_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 navback_assertThisInitialized(self);
}
function navback_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function navback_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 navback_getPrototypeOf(o) {
  navback_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return navback_getPrototypeOf(o);
}



var ControlBoxNavback = /*#__PURE__*/function (_CustomElement) {
  navback_inherits(ControlBoxNavback, _CustomElement);
  var _super = navback_createSuper(ControlBoxNavback);
  function ControlBoxNavback() {
    navback_classCallCheck(this, ControlBoxNavback);
    return _super.apply(this, arguments);
  }
  navback_createClass(ControlBoxNavback, [{
    key: "render",
    value: function render() {
      return navback(this.jid);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return ControlBoxNavback;
}(CustomElement);
shared_api.elements.define('converse-controlbox-navback', ControlBoxNavback);
/* harmony default export */ const controlbox_navback = ((/* unused pure expression or super */ null && (ControlBoxNavback)));
;// CONCATENATED MODULE: ./src/plugins/controlbox/model.js


var model_dayjs = public_converse.env.dayjs;

/**
 * The ControlBox is the section of the chat that contains the open groupchats,
 * bookmarks and roster.
 *
 * In `overlayed` `view_mode` it's a box like the chat boxes, in `fullscreen`
 * `view_mode` it's a left-aligned sidebar.
 * @mixin
 */
var ControlBox = Model.extend({
  defaults: function defaults() {
    return {
      'bookmarked': false,
      'box_id': 'controlbox',
      'chat_state': undefined,
      'closed': !shared_api.settings.get('show_controlbox_by_default'),
      'num_unread': 0,
      'time_opened': model_dayjs(0).valueOf(),
      'type': shared_converse.CONTROLBOX_TYPE,
      'url': ''
    };
  },
  validate: function validate(attrs) {
    if (attrs.type === shared_converse.CONTROLBOX_TYPE) {
      if (shared_api.settings.get('view_mode') === 'embedded' && shared_api.settings.get('singleton')) {
        return 'Controlbox not relevant in embedded view mode';
      }
      return;
    }
    return shared_converse.ChatBox.prototype.validate.call(this, attrs);
  },
  maybeShow: function maybeShow(force) {
    if (!force && this.get('id') === 'controlbox') {
      // Must return the chatbox
      return this;
    }
    return shared_converse.ChatBox.prototype.maybeShow.call(this, force);
  },
  onReconnection: function onReconnection() {
    this.save('connected', true);
  }
});
/* harmony default export */ const controlbox_model = (ControlBox);
;// CONCATENATED MODULE: ./src/plugins/controlbox/templates/toggle.js
var toggle_templateObject;
function toggle_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const toggle = (function (o) {
  var i18n_toggle = shared_api.connection.connected() ? __('Chat Contacts') : __('Toggle chat');
  return (0,external_lit_namespaceObject.html)(toggle_templateObject || (toggle_templateObject = toggle_taggedTemplateLiteral(["<a id=\"toggle-controlbox\" class=\"toggle-controlbox ", "\" @click=", "><span class=\"toggle-feedback\">", "</span></a>"])), o.hide ? 'hidden' : '', o.onClick, i18n_toggle);
});
;// CONCATENATED MODULE: ./src/plugins/controlbox/toggle.js
function toggle_typeof(obj) {
  "@babel/helpers - typeof";

  return toggle_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;
  }, toggle_typeof(obj);
}
function toggle_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  toggle_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" == toggle_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 toggle_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 toggle_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        toggle_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        toggle_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function toggle_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function toggle_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, toggle_toPropertyKey(descriptor.key), descriptor);
  }
}
function toggle_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) toggle_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) toggle_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function toggle_toPropertyKey(arg) {
  var key = toggle_toPrimitive(arg, "string");
  return toggle_typeof(key) === "symbol" ? key : String(key);
}
function toggle_toPrimitive(input, hint) {
  if (toggle_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (toggle_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function toggle_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    toggle_get = Reflect.get.bind();
  } else {
    toggle_get = function _get(target, property, receiver) {
      var base = toggle_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return toggle_get.apply(this, arguments);
}
function toggle_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = toggle_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function toggle_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) toggle_setPrototypeOf(subClass, superClass);
}
function toggle_setPrototypeOf(o, p) {
  toggle_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return toggle_setPrototypeOf(o, p);
}
function toggle_createSuper(Derived) {
  var hasNativeReflectConstruct = toggle_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = toggle_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = toggle_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return toggle_possibleConstructorReturn(this, result);
  };
}
function toggle_possibleConstructorReturn(self, call) {
  if (call && (toggle_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 toggle_assertThisInitialized(self);
}
function toggle_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function toggle_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 toggle_getPrototypeOf(o) {
  toggle_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return toggle_getPrototypeOf(o);
}




var ControlBoxToggle = /*#__PURE__*/function (_CustomElement) {
  toggle_inherits(ControlBoxToggle, _CustomElement);
  var _super = toggle_createSuper(ControlBoxToggle);
  function ControlBoxToggle() {
    toggle_classCallCheck(this, ControlBoxToggle);
    return _super.apply(this, arguments);
  }
  toggle_createClass(ControlBoxToggle, [{
    key: "connectedCallback",
    value: function () {
      var _connectedCallback = toggle_asyncToGenerator( /*#__PURE__*/toggle_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return toggle_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              toggle_get(toggle_getPrototypeOf(ControlBoxToggle.prototype), "connectedCallback", this).call(this);
              _context.next = 3;
              return shared_api.waitUntil('initialized');
            case 3:
              this.model = shared_converse.chatboxes.get('controlbox');
              this.listenTo(this.model, 'change:closed', function () {
                return _this.requestUpdate();
              });
              this.requestUpdate();
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function connectedCallback() {
        return _connectedCallback.apply(this, arguments);
      }
      return connectedCallback;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this$model;
      return toggle({
        'onClick': showControlBox,
        'hide': !((_this$model = this.model) !== null && _this$model !== void 0 && _this$model.get('closed'))
      });
    }
  }]);
  return ControlBoxToggle;
}(CustomElement);
shared_api.elements.define('converse-controlbox-toggle', ControlBoxToggle);
/* harmony default export */ const controlbox_toggle = (ControlBoxToggle);
;// CONCATENATED MODULE: ./src/plugins/controlbox/templates/controlbox.js
var controlbox_templateObject, controlbox_templateObject2, controlbox_templateObject3, controlbox_templateObject4, controlbox_templateObject5, controlbox_templateObject6;
function controlbox_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



var controlbox_Strophe = public_converse.env.Strophe;
function whenNotConnected(o) {
  var connection_status = shared_converse.connfeedback.get('connection_status');
  if ([controlbox_Strophe.Status.RECONNECTING, controlbox_Strophe.Status.CONNECTING].includes(connection_status)) {
    return spinner();
  }
  if (o['active-form'] === 'register') {
    return (0,external_lit_namespaceObject.html)(controlbox_templateObject || (controlbox_templateObject = controlbox_taggedTemplateLiteral(["<converse-register-panel></converse-register-panel>"])));
  }
  return (0,external_lit_namespaceObject.html)(controlbox_templateObject2 || (controlbox_templateObject2 = controlbox_taggedTemplateLiteral(["<converse-login-form id=\"converse-login-panel\" class=\"controlbox-pane fade-in row no-gutters\"></converse-login-form>"])));
}
/* harmony default export */ const controlbox = (function (el) {
  var o = el.model.toJSON();
  var sticky_controlbox = shared_api.settings.get('sticky_controlbox');
  return (0,external_lit_namespaceObject.html)(controlbox_templateObject3 || (controlbox_templateObject3 = controlbox_taggedTemplateLiteral(["\n        <div class=\"flyout box-flyout\">\n            <converse-dragresize></converse-dragresize>\n            <div class=\"chat-head controlbox-head\">\n                ", "\n            </div>\n            <div class=\"controlbox-panes\">\n                <div class=\"controlbox-pane\">\n                    ", "\n                </div>\n            </div>\n        </div>"])), sticky_controlbox ? '' : (0,external_lit_namespaceObject.html)(controlbox_templateObject4 || (controlbox_templateObject4 = controlbox_taggedTemplateLiteral(["\n                        <a class=\"chatbox-btn close-chatbox-button\" @click=", ">\n                            <converse-icon class=\"fa fa-times\" size=\"1em\"></converse-icon>\n                        </a>\n                    "])), function (ev) {
    return el.close(ev);
  }), o.connected ? (0,external_lit_namespaceObject.html)(controlbox_templateObject5 || (controlbox_templateObject5 = controlbox_taggedTemplateLiteral(["\n                            <converse-user-profile></converse-user-profile>\n                            <converse-headlines-feeds-list class=\"controlbox-section\"></converse-headlines-feeds-list>\n                            <div id=\"chatrooms\" class=\"controlbox-section\"><converse-rooms-list></converse-rooms-list></div>\n                            ", ""])), shared_api.settings.get("authentication") === shared_converse.ANONYMOUS ? '' : (0,external_lit_namespaceObject.html)(controlbox_templateObject6 || (controlbox_templateObject6 = controlbox_taggedTemplateLiteral(["<div id=\"converse-roster\" class=\"controlbox-section\"><converse-roster></converse-roster></div>"])))) : whenNotConnected(o));
});
;// CONCATENATED MODULE: ./src/plugins/controlbox/controlbox.js
function controlbox_typeof(obj) {
  "@babel/helpers - typeof";

  return controlbox_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;
  }, controlbox_typeof(obj);
}
function controlbox_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function controlbox_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, controlbox_toPropertyKey(descriptor.key), descriptor);
  }
}
function controlbox_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) controlbox_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) controlbox_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function controlbox_toPropertyKey(arg) {
  var key = controlbox_toPrimitive(arg, "string");
  return controlbox_typeof(key) === "symbol" ? key : String(key);
}
function controlbox_toPrimitive(input, hint) {
  if (controlbox_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (controlbox_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function controlbox_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) controlbox_setPrototypeOf(subClass, superClass);
}
function controlbox_setPrototypeOf(o, p) {
  controlbox_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return controlbox_setPrototypeOf(o, p);
}
function controlbox_createSuper(Derived) {
  var hasNativeReflectConstruct = controlbox_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = controlbox_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = controlbox_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return controlbox_possibleConstructorReturn(this, result);
  };
}
function controlbox_possibleConstructorReturn(self, call) {
  if (call && (controlbox_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 controlbox_assertThisInitialized(self);
}
function controlbox_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function controlbox_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 controlbox_getPrototypeOf(o) {
  controlbox_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return controlbox_getPrototypeOf(o);
}




var controlbox_u = public_converse.env.utils;

/**
 * The ControlBox is the section of the chat that contains the open groupchats,
 * bookmarks and roster.
 *
 * In `overlayed` `view_mode` it's a box like the chat boxes, in `fullscreen`
 * `view_mode` it's a left-aligned sidebar.
 */
var controlbox_ControlBox = /*#__PURE__*/function (_CustomElement) {
  controlbox_inherits(ControlBox, _CustomElement);
  var _super = controlbox_createSuper(ControlBox);
  function ControlBox() {
    controlbox_classCallCheck(this, ControlBox);
    return _super.apply(this, arguments);
  }
  controlbox_createClass(ControlBox, [{
    key: "initialize",
    value: function initialize() {
      this.setModel();
      shared_converse.chatboxviews.add('controlbox', this);
      if (this.model.get('connected') && this.model.get('closed') === undefined) {
        this.model.set('closed', !shared_api.settings.get('show_controlbox_by_default'));
      }
      this.requestUpdate();

      /**
       * Triggered when the _converse.ControlBoxView has been initialized and therefore
       * exists. The controlbox contains the login and register forms when the user is
       * logged out and a list of the user's contacts and group chats when logged in.
       * @event _converse#controlBoxInitialized
       * @type { _converse.ControlBoxView }
       * @example _converse.api.listen.on('controlBoxInitialized', view => { ... });
       */
      shared_api.trigger('controlBoxInitialized', this);
    }
  }, {
    key: "setModel",
    value: function setModel() {
      var _this = this;
      this.model = shared_converse.chatboxes.get('controlbox');
      this.listenTo(shared_converse.connfeedback, 'change:connection_status', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:active-form', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:connected', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'change:closed', function () {
        return !_this.model.get('closed') && _this.afterShown();
      });
      this.requestUpdate();
    }
  }, {
    key: "render",
    value: function render() {
      return this.model ? controlbox(this) : '';
    }
  }, {
    key: "close",
    value: function close(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      if ((ev === null || ev === void 0 ? void 0 : ev.name) === 'closeAllChatBoxes' && (shared_converse.disconnection_cause !== LOGOUT || shared_api.settings.get('show_controlbox_by_default'))) {
        return;
      }
      if (shared_api.settings.get('sticky_controlbox')) {
        return;
      }
      controlbox_u.safeSave(this.model, {
        'closed': true
      });
      shared_api.trigger('controlBoxClosed', this);
      return this;
    }
  }, {
    key: "afterShown",
    value: function afterShown() {
      /**
       * Triggered once the controlbox has been opened
       * @event _converse#controlBoxOpened
       * @type {_converse.ControlBox}
       */
      shared_api.trigger('controlBoxOpened', this);
      return this;
    }
  }]);
  return ControlBox;
}(CustomElement);
shared_api.elements.define('converse-controlbox', controlbox_ControlBox);
/* harmony default export */ const controlbox_controlbox = (controlbox_ControlBox);
;// CONCATENATED MODULE: ./src/plugins/controlbox/api.js
function controlbox_api_typeof(obj) {
  "@babel/helpers - typeof";

  return controlbox_api_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;
  }, controlbox_api_typeof(obj);
}
function controlbox_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  controlbox_api_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" == controlbox_api_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 controlbox_api_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 controlbox_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        controlbox_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        controlbox_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

var controlbox_api_u = public_converse.env.u;
/* harmony default export */ const controlbox_api = ({
  /**
   * The "controlbox" namespace groups methods pertaining to the
   * controlbox view
   *
   * @namespace _converse.api.controlbox
   * @memberOf _converse.api
   */
  controlbox: {
    /**
     * Opens the controlbox
     * @method _converse.api.controlbox.open
     * @returns { Promise<_converse.ControlBox> }
     */
    open: function open() {
      return controlbox_api_asyncToGenerator( /*#__PURE__*/controlbox_api_regeneratorRuntime().mark(function _callee() {
        var model;
        return controlbox_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('chatBoxesFetched');
            case 2:
              _context.next = 4;
              return shared_api.chatboxes.get('controlbox');
            case 4:
              _context.t0 = _context.sent;
              if (_context.t0) {
                _context.next = 7;
                break;
              }
              _context.t0 = shared_api.chatboxes.create('controlbox', {}, shared_converse.Controlbox);
            case 7:
              model = _context.t0;
              controlbox_api_u.safeSave(model, {
                'closed': false
              });
              return _context.abrupt("return", model);
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * Returns the controlbox view.
     * @method _converse.api.controlbox.get
     * @returns { View } View representing the controlbox
     * @example const view = _converse.api.controlbox.get();
     */
    get: function get() {
      return shared_converse.chatboxviews.get('controlbox');
    }
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/controlbox/styles/_controlbox.scss
var _controlbox = __webpack_require__(7080);
;// CONCATENATED MODULE: ./src/plugins/controlbox/styles/_controlbox.scss

      
      
      
      
      
      
      
      
      

var _controlbox_options = {};

_controlbox_options.styleTagTransform = (styleTagTransform_default());
_controlbox_options.setAttributes = (setAttributesWithoutAttributes_default());

      _controlbox_options.insert = insertBySelector_default().bind(null, "head");
    
_controlbox_options.domAPI = (styleDomAPI_default());
_controlbox_options.insertStyleElement = (insertStyleElement_default());

var _controlbox_update = injectStylesIntoStyleTag_default()(_controlbox/* default */.Z, _controlbox_options);




       /* harmony default export */ const styles_controlbox = (_controlbox/* default */.Z && _controlbox/* default */.Z.locals ? _controlbox/* default */.Z.locals : undefined);

// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/controlbox/styles/controlbox-head.scss
var controlbox_head = __webpack_require__(2745);
;// CONCATENATED MODULE: ./src/plugins/controlbox/styles/controlbox-head.scss

      
      
      
      
      
      
      
      
      

var controlbox_head_options = {};

controlbox_head_options.styleTagTransform = (styleTagTransform_default());
controlbox_head_options.setAttributes = (setAttributesWithoutAttributes_default());

      controlbox_head_options.insert = insertBySelector_default().bind(null, "head");
    
controlbox_head_options.domAPI = (styleDomAPI_default());
controlbox_head_options.insertStyleElement = (insertStyleElement_default());

var controlbox_head_update = injectStylesIntoStyleTag_default()(controlbox_head/* default */.Z, controlbox_head_options);




       /* harmony default export */ const styles_controlbox_head = (controlbox_head/* default */.Z && controlbox_head/* default */.Z.locals ? controlbox_head/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/controlbox/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */













public_converse.plugins.add('converse-controlbox', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   */
  dependencies: ['converse-modal', 'converse-chatboxes', 'converse-chat', 'converse-rosterview', 'converse-chatview'],
  enabled: function enabled(_converse) {
    return !_converse.api.settings.get('singleton');
  },
  // Overrides mentioned here will be picked up by converse.js's
  // plugin architecture they will replace existing methods on the
  // relevant objects or classes.
  // New functions which don't exist yet can also be added.
  overrides: {
    ChatBoxes: {
      model: function model(attrs, options) {
        if (attrs && attrs.id == 'controlbox') {
          return new controlbox_model(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }
    }
  },
  initialize: function initialize() {
    shared_api.settings.extend({
      allow_logout: true,
      allow_user_trust_override: true,
      default_domain: undefined,
      locked_domain: undefined,
      show_connection_url_input: false,
      show_controlbox_by_default: false,
      sticky_controlbox: false
    });
    shared_api.promises.add('controlBoxInitialized', false);
    Object.assign(shared_api, controlbox_api);
    shared_converse.ControlBoxView = controlbox_controlbox;
    shared_converse.ControlBox = controlbox_model;
    shared_converse.ControlBoxToggle = controlbox_toggle;
    shared_api.listen.on('chatBoxesFetched', onChatBoxesFetched);
    shared_api.listen.on('clearSession', controlbox_utils_clearSession);
    shared_api.listen.on('will-reconnect', disconnect);
    shared_api.waitUntil('chatBoxViewsInitialized').then(addControlBox).catch(function (e) {
      return log.fatal(e);
    });
  }
});
;// CONCATENATED MODULE: ./src/plugins/headlines-view/templates/chat-head.js
var templates_chat_head_templateObject, templates_chat_head_templateObject2, templates_chat_head_templateObject3;
function templates_chat_head_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const templates_chat_head = (function (o) {
  return (0,external_lit_namespaceObject.html)(templates_chat_head_templateObject || (templates_chat_head_templateObject = templates_chat_head_taggedTemplateLiteral(["\n        <div class=\"chatbox-title ", "\">\n            <div class=\"chatbox-title--row\">\n                ", "\n                <div class=\"chatbox-title__text\" title=\"", "\">", "</div>\n            </div>\n            <div class=\"chatbox-title__buttons row no-gutters\">\n                ", "\n                ", "\n            </div>\n        </div>\n        ", "\n    "])), o.status ? '' : "chatbox-title--no-desc", !shared_converse.api.settings.get("singleton") ? (0,external_lit_namespaceObject.html)(templates_chat_head_templateObject2 || (templates_chat_head_templateObject2 = templates_chat_head_taggedTemplateLiteral(["<converse-controlbox-navback jid=\"", "\"></converse-controlbox-navback>"])), o.jid) : '', o.jid, o.display_name, until_m(getDropdownButtons(o.heading_buttons_promise), ''), until_m(getStandaloneButtons(o.heading_buttons_promise), ''), o.status ? (0,external_lit_namespaceObject.html)(templates_chat_head_templateObject3 || (templates_chat_head_templateObject3 = templates_chat_head_taggedTemplateLiteral(["<p class=\"chat-head__desc\">", "</p>"])), o.status) : '');
});
;// CONCATENATED MODULE: ./src/plugins/headlines-view/heading.js
function headlines_view_heading_typeof(obj) {
  "@babel/helpers - typeof";

  return headlines_view_heading_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;
  }, headlines_view_heading_typeof(obj);
}
function heading_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 heading_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? heading_ownKeys(Object(source), !0).forEach(function (key) {
      heading_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : heading_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function heading_defineProperty(obj, key, value) {
  key = headlines_view_heading_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 heading_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  heading_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" == headlines_view_heading_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 heading_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 heading_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        heading_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        heading_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function headlines_view_heading_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function headlines_view_heading_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, headlines_view_heading_toPropertyKey(descriptor.key), descriptor);
  }
}
function headlines_view_heading_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) headlines_view_heading_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) headlines_view_heading_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function headlines_view_heading_toPropertyKey(arg) {
  var key = headlines_view_heading_toPrimitive(arg, "string");
  return headlines_view_heading_typeof(key) === "symbol" ? key : String(key);
}
function headlines_view_heading_toPrimitive(input, hint) {
  if (headlines_view_heading_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (headlines_view_heading_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function headlines_view_heading_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) headlines_view_heading_setPrototypeOf(subClass, superClass);
}
function headlines_view_heading_setPrototypeOf(o, p) {
  headlines_view_heading_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return headlines_view_heading_setPrototypeOf(o, p);
}
function headlines_view_heading_createSuper(Derived) {
  var hasNativeReflectConstruct = headlines_view_heading_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = headlines_view_heading_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = headlines_view_heading_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return headlines_view_heading_possibleConstructorReturn(this, result);
  };
}
function headlines_view_heading_possibleConstructorReturn(self, call) {
  if (call && (headlines_view_heading_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 headlines_view_heading_assertThisInitialized(self);
}
function headlines_view_heading_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function headlines_view_heading_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 headlines_view_heading_getPrototypeOf(o) {
  headlines_view_heading_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return headlines_view_heading_getPrototypeOf(o);
}




var HeadlinesHeading = /*#__PURE__*/function (_CustomElement) {
  headlines_view_heading_inherits(HeadlinesHeading, _CustomElement);
  var _super = headlines_view_heading_createSuper(HeadlinesHeading);
  function HeadlinesHeading() {
    headlines_view_heading_classCallCheck(this, HeadlinesHeading);
    return _super.apply(this, arguments);
  }
  headlines_view_heading_createClass(HeadlinesHeading, [{
    key: "initialize",
    value: function () {
      var _initialize = heading_asyncToGenerator( /*#__PURE__*/heading_regeneratorRuntime().mark(function _callee() {
        return heading_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.model = shared_converse.chatboxes.get(this.jid);
              _context.next = 3;
              return this.model.initialized;
            case 3:
              this.requestUpdate();
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return templates_chat_head(heading_objectSpread(heading_objectSpread({}, this.model.toJSON()), {
        'display_name': this.model.getDisplayName(),
        'heading_buttons_promise': this.getHeadingButtons()
      }));
    }

    /**
     * Returns a list of objects which represent buttons for the headlines header.
     * @async
     * @emits _converse#getHeadingButtons
     * @method HeadlinesHeading#getHeadingButtons
     */
  }, {
    key: "getHeadingButtons",
    value: function getHeadingButtons() {
      var _this = this;
      var buttons = [];
      if (!shared_api.settings.get('singleton')) {
        buttons.push({
          'a_class': 'close-chatbox-button',
          'handler': function handler(ev) {
            return _this.close(ev);
          },
          'i18n_text': __('Close'),
          'i18n_title': __('Close these announcements'),
          'icon_class': 'fa-times',
          'name': 'close',
          'standalone': shared_api.settings.get('view_mode') === 'overlayed'
        });
      }
      return shared_converse.api.hook('getHeadingButtons', this, buttons);
    }
  }, {
    key: "close",
    value: function close(ev) {
      ev.preventDefault();
      this.model.close();
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return HeadlinesHeading;
}(CustomElement);

shared_api.elements.define('converse-headlines-heading', HeadlinesHeading);
;// CONCATENATED MODULE: ./src/plugins/headlines-view/templates/headlines.js
var headlines_templateObject, headlines_templateObject2;
function headlines_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const headlines = (function (model) {
  return (0,external_lit_namespaceObject.html)(headlines_templateObject || (headlines_templateObject = headlines_taggedTemplateLiteral(["\n    <div class=\"flyout box-flyout\">\n        <converse-dragresize></converse-dragresize>\n        ", "\n    </div>\n"])), model ? (0,external_lit_namespaceObject.html)(headlines_templateObject2 || (headlines_templateObject2 = headlines_taggedTemplateLiteral(["\n            <converse-headlines-heading jid=\"", "\" class=\"chat-head chat-head-chatbox row no-gutters\">\n            </converse-headlines-heading>\n            <div class=\"chat-body\">\n                <div class=\"chat-content\" aria-live=\"polite\">\n                    <converse-chat-content\n                        class=\"chat-content__messages\"\n                        jid=\"", "\"></converse-chat-content>\n                </div>\n            </div>"])), model.get('jid'), model.get('jid')) : '');
});
;// CONCATENATED MODULE: ./src/plugins/headlines-view/view.js
function headlines_view_view_typeof(obj) {
  "@babel/helpers - typeof";

  return headlines_view_view_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;
  }, headlines_view_view_typeof(obj);
}
function view_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  view_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" == headlines_view_view_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 view_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 view_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function headlines_view_view_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function headlines_view_view_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, headlines_view_view_toPropertyKey(descriptor.key), descriptor);
  }
}
function headlines_view_view_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) headlines_view_view_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) headlines_view_view_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function headlines_view_view_toPropertyKey(arg) {
  var key = headlines_view_view_toPrimitive(arg, "string");
  return headlines_view_view_typeof(key) === "symbol" ? key : String(key);
}
function headlines_view_view_toPrimitive(input, hint) {
  if (headlines_view_view_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (headlines_view_view_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function headlines_view_view_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) headlines_view_view_setPrototypeOf(subClass, superClass);
}
function headlines_view_view_setPrototypeOf(o, p) {
  headlines_view_view_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return headlines_view_view_setPrototypeOf(o, p);
}
function headlines_view_view_createSuper(Derived) {
  var hasNativeReflectConstruct = headlines_view_view_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = headlines_view_view_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = headlines_view_view_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return headlines_view_view_possibleConstructorReturn(this, result);
  };
}
function headlines_view_view_possibleConstructorReturn(self, call) {
  if (call && (headlines_view_view_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 headlines_view_view_assertThisInitialized(self);
}
function headlines_view_view_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function headlines_view_view_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 headlines_view_view_getPrototypeOf(o) {
  headlines_view_view_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return headlines_view_view_getPrototypeOf(o);
}



var HeadlinesFeedView = /*#__PURE__*/function (_BaseChatView) {
  headlines_view_view_inherits(HeadlinesFeedView, _BaseChatView);
  var _super = headlines_view_view_createSuper(HeadlinesFeedView);
  function HeadlinesFeedView() {
    headlines_view_view_classCallCheck(this, HeadlinesFeedView);
    return _super.apply(this, arguments);
  }
  headlines_view_view_createClass(HeadlinesFeedView, [{
    key: "initialize",
    value: function () {
      var _initialize = view_asyncToGenerator( /*#__PURE__*/view_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return view_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              shared_converse.chatboxviews.add(this.jid, this);
              this.model = shared_converse.chatboxes.get(this.jid);
              this.model.disable_mam = true; // Don't do MAM queries for this box
              this.listenTo(shared_converse, 'windowStateChanged', this.onWindowStateChanged);
              this.listenTo(this.model, 'change:hidden', function () {
                return _this.afterShown();
              });
              this.listenTo(this.model, 'destroy', this.remove);
              this.listenTo(this.model.messages, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.messages, 'reset', function () {
                return _this.requestUpdate();
              });
              _context.next = 11;
              return this.model.messages.fetched;
            case 11:
              this.model.maybeShow();
              /**
               * Triggered once the { @link _converse.HeadlinesFeedView } has been initialized
               * @event _converse#headlinesBoxViewInitialized
               * @type { _converse.HeadlinesFeedView }
               * @example _converse.api.listen.on('headlinesBoxViewInitialized', view => { ... });
               */
              shared_api.trigger('headlinesBoxViewInitialized', this);
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return headlines(this.model);
    }
  }, {
    key: "close",
    value: function () {
      var _close = view_asyncToGenerator( /*#__PURE__*/view_regeneratorRuntime().mark(function _callee2(ev) {
        var _ev$preventDefault;
        return view_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
              if (shared_converse.router.history.getFragment() === 'converse/chat?jid=' + this.model.get('jid')) {
                shared_converse.router.navigate('');
              }
              _context2.next = 4;
              return this.model.close(ev);
            case 4:
              return _context2.abrupt("return", this);
            case 5:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function close(_x) {
        return _close.apply(this, arguments);
      }
      return close;
    }()
  }, {
    key: "getNotifications",
    value: function getNotifications() {
      // eslint-disable-line class-methods-use-this
      // Override method in ChatBox. We don't show notifications for
      // headlines boxes.
      return [];
    }
  }, {
    key: "afterShown",
    value: function afterShown() {
      this.model.clearUnreadMsgCounter();
    }
  }]);
  return HeadlinesFeedView;
}(BaseChatView);
shared_api.elements.define('converse-headlines', HeadlinesFeedView);
;// CONCATENATED MODULE: ./src/plugins/headlines-view/templates/feeds-list.js
var feeds_list_templateObject, feeds_list_templateObject2;
function feeds_list_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



function tplHeadlinesFeedsListItem(el, feed) {
  var open_title = __('Click to open this server message');
  return (0,external_lit_namespaceObject.html)(feeds_list_templateObject || (feeds_list_templateObject = feeds_list_taggedTemplateLiteral(["\n        <div class=\"list-item controlbox-padded d-flex flex-row\"\n            data-headline-jid=\"", "\">\n        <a class=\"list-item-link open-headline available-room w-100\"\n            data-headline-jid=\"", "\"\n            title=\"", "\"\n            @click=", "\n            href=\"#\">", "</a>\n        </div>\n    "])), feed.get('jid'), feed.get('jid'), open_title, function (ev) {
    return el.openHeadline(ev);
  }, feed.get('jid'));
}
/* harmony default export */ const feeds_list = (function (el) {
  var feeds = el.model.filter(function (m) {
    return m.get('type') === shared_converse.HEADLINES_TYPE;
  });
  var heading_headline = __('Announcements');
  return (0,external_lit_namespaceObject.html)(feeds_list_templateObject2 || (feeds_list_templateObject2 = feeds_list_taggedTemplateLiteral(["\n        <div class=\"controlbox-section\" id=\"headline\">\n            <div class=\"d-flex controlbox-padded ", "\">\n                <span class=\"w-100 controlbox-heading controlbox-heading--headline\">", "</span>\n            </div>\n        </div>\n        <div class=\"list-container list-container--headline ", "\">\n            <div class=\"items-list rooms-list headline-list\">\n                ", "\n            </div>\n        </div>"])), feeds.length ? '' : 'hidden', heading_headline, feeds.length ? '' : 'hidden', feeds.map(function (feed) {
    return tplHeadlinesFeedsListItem(el, feed);
  }));
});
;// CONCATENATED MODULE: ./src/plugins/headlines-view/feed-list.js
function feed_list_typeof(obj) {
  "@babel/helpers - typeof";

  return feed_list_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;
  }, feed_list_typeof(obj);
}
function feed_list_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  feed_list_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" == feed_list_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 feed_list_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 feed_list_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        feed_list_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        feed_list_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function feed_list_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function feed_list_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, feed_list_toPropertyKey(descriptor.key), descriptor);
  }
}
function feed_list_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) feed_list_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) feed_list_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function feed_list_toPropertyKey(arg) {
  var key = feed_list_toPrimitive(arg, "string");
  return feed_list_typeof(key) === "symbol" ? key : String(key);
}
function feed_list_toPrimitive(input, hint) {
  if (feed_list_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (feed_list_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function feed_list_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) feed_list_setPrototypeOf(subClass, superClass);
}
function feed_list_setPrototypeOf(o, p) {
  feed_list_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return feed_list_setPrototypeOf(o, p);
}
function feed_list_createSuper(Derived) {
  var hasNativeReflectConstruct = feed_list_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = feed_list_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = feed_list_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return feed_list_possibleConstructorReturn(this, result);
  };
}
function feed_list_possibleConstructorReturn(self, call) {
  if (call && (feed_list_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 feed_list_assertThisInitialized(self);
}
function feed_list_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function feed_list_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 feed_list_getPrototypeOf(o) {
  feed_list_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return feed_list_getPrototypeOf(o);
}




/**
 * Custom element which renders a list of headline feeds
 * @class
 * @namespace _converse.HeadlinesFeedsList
 * @memberOf _converse
 */
var HeadlinesFeedsList = /*#__PURE__*/function (_CustomElement) {
  feed_list_inherits(HeadlinesFeedsList, _CustomElement);
  var _super = feed_list_createSuper(HeadlinesFeedsList);
  function HeadlinesFeedsList() {
    feed_list_classCallCheck(this, HeadlinesFeedsList);
    return _super.apply(this, arguments);
  }
  feed_list_createClass(HeadlinesFeedsList, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.model = shared_converse.chatboxes;
      this.listenTo(this.model, 'add', function (m) {
        return _this.renderIfHeadline(m);
      });
      this.listenTo(this.model, 'remove', function (m) {
        return _this.renderIfHeadline(m);
      });
      this.listenTo(this.model, 'destroy', function (m) {
        return _this.renderIfHeadline(m);
      });
      this.requestUpdate();
    }
  }, {
    key: "render",
    value: function render() {
      return feeds_list(this);
    }
  }, {
    key: "renderIfHeadline",
    value: function renderIfHeadline(model) {
      return (model === null || model === void 0 ? void 0 : model.get('type')) === shared_converse.HEADLINES_TYPE && this.requestUpdate();
    }
  }, {
    key: "openHeadline",
    value: function () {
      var _openHeadline = feed_list_asyncToGenerator( /*#__PURE__*/feed_list_regeneratorRuntime().mark(function _callee(ev) {
        var jid, feed;
        return feed_list_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              // eslint-disable-line class-methods-use-this
              ev.preventDefault();
              jid = ev.target.getAttribute('data-headline-jid');
              _context.next = 4;
              return shared_api.headlines.get(jid);
            case 4:
              feed = _context.sent;
              feed.maybeShow(true);
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      function openHeadline(_x) {
        return _openHeadline.apply(this, arguments);
      }
      return openHeadline;
    }()
  }]);
  return HeadlinesFeedsList;
}(CustomElement);
shared_api.elements.define('converse-headlines-feeds-list', HeadlinesFeedsList);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/headlines-view/styles/headlines.scss
var styles_headlines = __webpack_require__(9703);
;// CONCATENATED MODULE: ./src/plugins/headlines-view/styles/headlines.scss

      
      
      
      
      
      
      
      
      

var headlines_options = {};

headlines_options.styleTagTransform = (styleTagTransform_default());
headlines_options.setAttributes = (setAttributesWithoutAttributes_default());

      headlines_options.insert = insertBySelector_default().bind(null, "head");
    
headlines_options.domAPI = (styleDomAPI_default());
headlines_options.insertStyleElement = (insertStyleElement_default());

var headlines_update = injectStylesIntoStyleTag_default()(styles_headlines/* default */.Z, headlines_options);




       /* harmony default export */ const headlines_view_styles_headlines = (styles_headlines/* default */.Z && styles_headlines/* default */.Z.locals ? styles_headlines/* default */.Z.locals : undefined);

// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/headlines-view/styles/headlines-head.scss
var headlines_head = __webpack_require__(4058);
;// CONCATENATED MODULE: ./src/plugins/headlines-view/styles/headlines-head.scss

      
      
      
      
      
      
      
      
      

var headlines_head_options = {};

headlines_head_options.styleTagTransform = (styleTagTransform_default());
headlines_head_options.setAttributes = (setAttributesWithoutAttributes_default());

      headlines_head_options.insert = insertBySelector_default().bind(null, "head");
    
headlines_head_options.domAPI = (styleDomAPI_default());
headlines_head_options.insertStyleElement = (insertStyleElement_default());

var headlines_head_update = injectStylesIntoStyleTag_default()(headlines_head/* default */.Z, headlines_head_options);




       /* harmony default export */ const styles_headlines_head = (headlines_head/* default */.Z && headlines_head/* default */.Z.locals ? headlines_head/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/headlines-view/index.js
/**
 * @module converse-headlines-view
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






public_converse.plugins.add('converse-headlines-view', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded by the bundler
   */
  dependencies: ['converse-headlines', 'converse-chatview'],
  initialize: function initialize() {
    shared_converse.HeadlinesFeedsList = HeadlinesFeedsList;

    // Deprecated
    shared_converse.HeadlinesPanel = HeadlinesFeedsList;
  }
});
;// CONCATENATED MODULE: ./src/plugins/mam-views/templates/placeholder.js
var placeholder_templateObject;
function placeholder_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const placeholder = (function (el) {
  return el.model.get('fetching') ? spinner({
    'classes': 'hor_centered'
  }) : (0,external_lit_html_namespaceObject.html)(placeholder_templateObject || (placeholder_templateObject = placeholder_taggedTemplateLiteral(["<a @click=\"", "\" title=\"", "\">\n            <div class=\"message mam-placeholder\"></div>\n        </a>"])), function (ev) {
    return el.fetchMissingMessages(ev);
  }, __('Click to load missing messages'));
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/mam-views/styles/placeholder.scss
var styles_placeholder = __webpack_require__(9484);
;// CONCATENATED MODULE: ./src/plugins/mam-views/styles/placeholder.scss

      
      
      
      
      
      
      
      
      

var placeholder_options = {};

placeholder_options.styleTagTransform = (styleTagTransform_default());
placeholder_options.setAttributes = (setAttributesWithoutAttributes_default());

      placeholder_options.insert = insertBySelector_default().bind(null, "head");
    
placeholder_options.domAPI = (styleDomAPI_default());
placeholder_options.insertStyleElement = (insertStyleElement_default());

var placeholder_update = injectStylesIntoStyleTag_default()(styles_placeholder/* default */.Z, placeholder_options);




       /* harmony default export */ const mam_views_styles_placeholder = (styles_placeholder/* default */.Z && styles_placeholder/* default */.Z.locals ? styles_placeholder/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/mam-views/placeholder.js
function mam_views_placeholder_typeof(obj) {
  "@babel/helpers - typeof";

  return mam_views_placeholder_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;
  }, mam_views_placeholder_typeof(obj);
}
function placeholder_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  placeholder_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" == mam_views_placeholder_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 placeholder_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 placeholder_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        placeholder_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        placeholder_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function mam_views_placeholder_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function mam_views_placeholder_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, mam_views_placeholder_toPropertyKey(descriptor.key), descriptor);
  }
}
function mam_views_placeholder_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) mam_views_placeholder_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) mam_views_placeholder_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function mam_views_placeholder_toPropertyKey(arg) {
  var key = mam_views_placeholder_toPrimitive(arg, "string");
  return mam_views_placeholder_typeof(key) === "symbol" ? key : String(key);
}
function mam_views_placeholder_toPrimitive(input, hint) {
  if (mam_views_placeholder_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (mam_views_placeholder_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function mam_views_placeholder_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) mam_views_placeholder_setPrototypeOf(subClass, superClass);
}
function mam_views_placeholder_setPrototypeOf(o, p) {
  mam_views_placeholder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return mam_views_placeholder_setPrototypeOf(o, p);
}
function mam_views_placeholder_createSuper(Derived) {
  var hasNativeReflectConstruct = mam_views_placeholder_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = mam_views_placeholder_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = mam_views_placeholder_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return mam_views_placeholder_possibleConstructorReturn(this, result);
  };
}
function mam_views_placeholder_possibleConstructorReturn(self, call) {
  if (call && (mam_views_placeholder_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 mam_views_placeholder_assertThisInitialized(self);
}
function mam_views_placeholder_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function mam_views_placeholder_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 mam_views_placeholder_getPrototypeOf(o) {
  mam_views_placeholder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return mam_views_placeholder_getPrototypeOf(o);
}





var Placeholder = /*#__PURE__*/function (_CustomElement) {
  mam_views_placeholder_inherits(Placeholder, _CustomElement);
  var _super = mam_views_placeholder_createSuper(Placeholder);
  function Placeholder() {
    mam_views_placeholder_classCallCheck(this, Placeholder);
    return _super.apply(this, arguments);
  }
  mam_views_placeholder_createClass(Placeholder, [{
    key: "render",
    value: function render() {
      return placeholder(this);
    }
  }, {
    key: "fetchMissingMessages",
    value: function () {
      var _fetchMissingMessages = placeholder_asyncToGenerator( /*#__PURE__*/placeholder_regeneratorRuntime().mark(function _callee(ev) {
        var _ev$preventDefault;
        var options;
        return placeholder_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
              this.model.set('fetching', true);
              options = {
                'before': this.model.get('before'),
                'start': this.model.get('start')
              };
              _context.next = 5;
              return fetchArchivedMessages(this.model.collection.chatbox, options);
            case 5:
              this.model.destroy();
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function fetchMissingMessages(_x) {
        return _fetchMissingMessages.apply(this, arguments);
      }
      return fetchMissingMessages;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        'model': {
          type: Object
        }
      };
    }
  }]);
  return Placeholder;
}(CustomElement);
shared_api.elements.define('converse-mam-placeholder', Placeholder);
;// CONCATENATED MODULE: ./src/plugins/mam-views/utils.js
function mam_views_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return mam_views_utils_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;
  }, mam_views_utils_typeof(obj);
}
var mam_views_utils_templateObject;
function mam_views_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  mam_views_utils_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" == mam_views_utils_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 mam_views_utils_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 mam_views_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        mam_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        mam_views_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function mam_views_utils_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





function getPlaceholderTemplate(message, tpl) {
  if (message instanceof MAMPlaceholderMessage) {
    return (0,external_lit_html_namespaceObject.html)(mam_views_utils_templateObject || (mam_views_utils_templateObject = mam_views_utils_taggedTemplateLiteral(["<converse-mam-placeholder .model=", "></converse-mam-placeholder>"])), message);
  } else {
    return tpl;
  }
}
function fetchMessagesOnScrollUp(_x) {
  return _fetchMessagesOnScrollUp.apply(this, arguments);
}
function _fetchMessagesOnScrollUp() {
  _fetchMessagesOnScrollUp = mam_views_utils_asyncToGenerator( /*#__PURE__*/mam_views_utils_regeneratorRuntime().mark(function _callee(view) {
    var is_groupchat, oldest_message, by_jid, stanza_id;
    return mam_views_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!view.model.ui.get('chat-content-spinner-top')) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return");
        case 2:
          if (!view.model.messages.length) {
            _context.next = 26;
            break;
          }
          is_groupchat = view.model.get('type') === shared_converse.CHATROOMS_TYPE;
          oldest_message = view.model.getOldestMessage();
          if (!oldest_message) {
            _context.next = 26;
            break;
          }
          by_jid = is_groupchat ? view.model.get('jid') : shared_converse.bare_jid;
          stanza_id = oldest_message && oldest_message.get("stanza_id ".concat(by_jid));
          view.model.ui.set('chat-content-spinner-top', true);
          _context.prev = 9;
          if (!stanza_id) {
            _context.next = 15;
            break;
          }
          _context.next = 13;
          return fetchArchivedMessages(view.model, {
            'before': stanza_id
          });
        case 13:
          _context.next = 17;
          break;
        case 15:
          _context.next = 17;
          return fetchArchivedMessages(view.model, {
            'end': oldest_message.get('time')
          });
        case 17:
          _context.next = 24;
          break;
        case 19:
          _context.prev = 19;
          _context.t0 = _context["catch"](9);
          log.error(_context.t0);
          view.model.ui.set('chat-content-spinner-top', false);
          return _context.abrupt("return");
        case 24:
          if (shared_api.settings.get('allow_url_history_change')) {
            shared_converse.router.history.navigate("#".concat(oldest_message.get('msgid')));
          }
          setTimeout(function () {
            return view.model.ui.set('chat-content-spinner-top', false);
          }, 250);
        case 26:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[9, 19]]);
  }));
  return _fetchMessagesOnScrollUp.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/plugins/mam-views/index.js
/**
 * @description UI code XEP-0313 Message Archive Management
 * @copyright 2021, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



public_converse.plugins.add('converse-mam-views', {
  dependencies: ['converse-mam', 'converse-chatview', 'converse-muc-views'],
  initialize: function initialize() {
    shared_api.listen.on('chatBoxScrolledUp', fetchMessagesOnScrollUp);
    shared_api.listen.on('getMessageTemplate', getPlaceholderTemplate);
  }
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/affiliation-form.js
var affiliation_form_templateObject, affiliation_form_templateObject2, affiliation_form_templateObject3;
function affiliation_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const affiliation_form = (function (el) {
  var i18n_change_affiliation = __('Change affiliation');
  var i18n_new_affiliation = __('New affiliation');
  var i18n_reason = __('Reason');
  var occupant = el.muc.getOwnOccupant();
  var assignable_affiliations = getAssignableAffiliations(occupant);
  return (0,external_lit_namespaceObject.html)(affiliation_form_templateObject || (affiliation_form_templateObject = affiliation_form_taggedTemplateLiteral(["\n        <form class=\"affiliation-form\" @submit=", ">\n            ", "\n            <div class=\"form-group\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <label><strong>", ":</strong></label>\n                        <select class=\"custom-select select-affiliation\" name=\"affiliation\">\n                            ", "\n                        </select>\n                    </div>\n                    <div class=\"col\">\n                        <label><strong>", ":</strong></label>\n                        <input class=\"form-control\" type=\"text\" name=\"reason\"/>\n                    </div>\n                </div>\n            </div>\n            <div class=\"form-group\">\n                <div class=\"col\">\n                    <input type=\"submit\" class=\"btn btn-primary\" name=\"change\" value=\"", "\"/>\n                </div>\n            </div>\n        </form>\n    "])), function (ev) {
    return el.assignAffiliation(ev);
  }, el.alert_message ? (0,external_lit_namespaceObject.html)(affiliation_form_templateObject2 || (affiliation_form_templateObject2 = affiliation_form_taggedTemplateLiteral(["<div class=\"alert alert-", "\" role=\"alert\">", "</div>"])), el.alert_type, el.alert_message) : '', i18n_new_affiliation, assignable_affiliations.map(function (aff) {
    return (0,external_lit_namespaceObject.html)(affiliation_form_templateObject3 || (affiliation_form_templateObject3 = affiliation_form_taggedTemplateLiteral(["<option value=\"", "\" ?selected=", ">", "</option>"])), aff, aff === el.affiliation, aff);
  }), i18n_reason, i18n_change_affiliation);
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/affiliation-form.js
function affiliation_form_typeof(obj) {
  "@babel/helpers - typeof";

  return affiliation_form_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;
  }, affiliation_form_typeof(obj);
}
function affiliation_form_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  affiliation_form_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" == affiliation_form_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 affiliation_form_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 affiliation_form_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        affiliation_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        affiliation_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function affiliation_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function affiliation_form_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, affiliation_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function affiliation_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) affiliation_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) affiliation_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function affiliation_form_toPropertyKey(arg) {
  var key = affiliation_form_toPrimitive(arg, "string");
  return affiliation_form_typeof(key) === "symbol" ? key : String(key);
}
function affiliation_form_toPrimitive(input, hint) {
  if (affiliation_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (affiliation_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function affiliation_form_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) affiliation_form_setPrototypeOf(subClass, superClass);
}
function affiliation_form_setPrototypeOf(o, p) {
  affiliation_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return affiliation_form_setPrototypeOf(o, p);
}
function affiliation_form_createSuper(Derived) {
  var hasNativeReflectConstruct = affiliation_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = affiliation_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = affiliation_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return affiliation_form_possibleConstructorReturn(this, result);
  };
}
function affiliation_form_possibleConstructorReturn(self, call) {
  if (call && (affiliation_form_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 affiliation_form_assertThisInitialized(self);
}
function affiliation_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function affiliation_form_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 affiliation_form_getPrototypeOf(o) {
  affiliation_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return affiliation_form_getPrototypeOf(o);
}






var affiliation_form_converse$env = public_converse.env,
  affiliation_form_Strophe = affiliation_form_converse$env.Strophe,
  affiliation_form_sizzle = affiliation_form_converse$env.sizzle;
var AffiliationForm = /*#__PURE__*/function (_CustomElement) {
  affiliation_form_inherits(AffiliationForm, _CustomElement);
  var _super = affiliation_form_createSuper(AffiliationForm);
  function AffiliationForm() {
    affiliation_form_classCallCheck(this, AffiliationForm);
    return _super.apply(this, arguments);
  }
  affiliation_form_createClass(AffiliationForm, [{
    key: "render",
    value: function render() {
      return affiliation_form(this);
    }
  }, {
    key: "alert",
    value: function alert(message, type) {
      this.alert_message = message;
      this.alert_type = type;
    }
  }, {
    key: "assignAffiliation",
    value: function () {
      var _assignAffiliation = affiliation_form_asyncToGenerator( /*#__PURE__*/affiliation_form_regeneratorRuntime().mark(function _callee(ev) {
        var data, affiliation, attrs, muc_jid, event;
        return affiliation_form_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev.stopPropagation();
              ev.preventDefault();
              this.alert(); // clear alert messages
              data = new FormData(ev.target);
              affiliation = data.get('affiliation');
              attrs = {
                jid: this.jid,
                reason: data.get('reason')
              };
              muc_jid = this.muc.get('jid');
              _context.prev = 7;
              _context.next = 10;
              return setAffiliation(affiliation, muc_jid, [attrs]);
            case 10:
              _context.next = 17;
              break;
            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](7);
              if (_context.t0 === null) {
                this.alert(__('Timeout error while trying to set the affiliation'), 'danger');
              } else if (affiliation_form_sizzle("not-allowed[xmlns=\"".concat(affiliation_form_Strophe.NS.STANZAS, "\"]"), _context.t0).length) {
                this.alert(__("Sorry, you're not allowed to make that change"), 'danger');
              } else {
                this.alert(__('Sorry, something went wrong while trying to set the affiliation'), 'danger');
              }
              log.error(_context.t0);
              return _context.abrupt("return");
            case 17:
              _context.next = 19;
              return this.muc.occupants.fetchMembers();
            case 19:
              /**
               * @event affiliationChanged
               * @example
               *  const el = document.querySelector('converse-muc-affiliation-form');
               *  el.addEventListener('affiliationChanged', () => { ... });
               */
              event = new CustomEvent('affiliationChanged', {
                bubbles: true
              });
              this.dispatchEvent(event);
            case 21:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[7, 12]]);
      }));
      function assignAffiliation(_x) {
        return _assignAffiliation.apply(this, arguments);
      }
      return assignAffiliation;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        muc: {
          type: Object
        },
        jid: {
          type: String
        },
        affiliation: {
          type: String
        },
        alert_message: {
          type: String,
          attribute: false
        },
        alert_type: {
          type: String,
          attribute: false
        }
      };
    }
  }]);
  return AffiliationForm;
}(CustomElement);
shared_api.elements.define('converse-muc-affiliation-form', AffiliationForm);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/role-form.js
var role_form_templateObject, role_form_templateObject2;
function role_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const role_form = (function (el) {
  var i18n_change_role = __('Change role');
  var i18n_new_role = __('New Role');
  var i18n_reason = __('Reason');
  var occupant = el.muc.getOwnOccupant();
  var assignable_roles = getAssignableRoles(occupant);
  return (0,external_lit_namespaceObject.html)(role_form_templateObject || (role_form_templateObject = role_form_taggedTemplateLiteral(["\n        <form class=\"role-form\" @submit=", ">\n            <div class=\"form-group\">\n                <input type=\"hidden\" name=\"jid\" value=\"", "\"/>\n                <input type=\"hidden\" name=\"nick\" value=\"", "\"/>\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <label><strong>", ":</strong></label>\n                        <select class=\"custom-select select-role\" name=\"role\">\n                        ", "\n                        </select>\n                    </div>\n                    <div class=\"col\">\n                        <label><strong>", ":</strong></label>\n                        <input class=\"form-control\" type=\"text\" name=\"reason\"/>\n                    </div>\n                </div>\n            </div>\n            <div class=\"form-group\">\n                <div class=\"col\">\n                    <input type=\"submit\" class=\"btn btn-primary\" value=\"", "\"/>\n                </div>\n            </div>\n        </form>\n    "])), el.assignRole, el.jid, el.nick, i18n_new_role, assignable_roles.map(function (role) {
    return (0,external_lit_namespaceObject.html)(role_form_templateObject2 || (role_form_templateObject2 = role_form_taggedTemplateLiteral(["<option value=\"", "\" ?selected=", ">", "</option>"])), role, role === el.role, role);
  }), i18n_reason, i18n_change_role);
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/role-form.js
function role_form_typeof(obj) {
  "@babel/helpers - typeof";

  return role_form_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;
  }, role_form_typeof(obj);
}
function role_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function role_form_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, role_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function role_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) role_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) role_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function role_form_toPropertyKey(arg) {
  var key = role_form_toPrimitive(arg, "string");
  return role_form_typeof(key) === "symbol" ? key : String(key);
}
function role_form_toPrimitive(input, hint) {
  if (role_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (role_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function role_form_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) role_form_setPrototypeOf(subClass, superClass);
}
function role_form_setPrototypeOf(o, p) {
  role_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return role_form_setPrototypeOf(o, p);
}
function role_form_createSuper(Derived) {
  var hasNativeReflectConstruct = role_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = role_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = role_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return role_form_possibleConstructorReturn(this, result);
  };
}
function role_form_possibleConstructorReturn(self, call) {
  if (call && (role_form_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 role_form_assertThisInitialized(self);
}
function role_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function role_form_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 role_form_getPrototypeOf(o) {
  role_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return role_form_getPrototypeOf(o);
}






var role_form_converse$env = public_converse.env,
  role_form_Strophe = role_form_converse$env.Strophe,
  role_form_sizzle = role_form_converse$env.sizzle;
var RoleForm = /*#__PURE__*/function (_CustomElement) {
  role_form_inherits(RoleForm, _CustomElement);
  var _super = role_form_createSuper(RoleForm);
  function RoleForm() {
    role_form_classCallCheck(this, RoleForm);
    return _super.apply(this, arguments);
  }
  role_form_createClass(RoleForm, [{
    key: "render",
    value: function render() {
      return role_form(this);
    }
  }, {
    key: "alert",
    value: function alert(message, type) {
      this.alert_message = message;
      this.alert_type = type;
    }
  }, {
    key: "assignRole",
    value: function assignRole(ev) {
      var _this = this;
      ev.stopPropagation();
      ev.preventDefault();
      this.alert(); // clear alert

      var data = new FormData(ev.target);
      var occupant = this.muc.getOccupant(data.get('jid') || data.get('nick'));
      var role = data.get('role');
      var reason = data.get('reason');
      this.muc.setRole(occupant, role, reason, function () {
        /**
         * @event roleChanged
         * @example
         *  const el = document.querySelector('converse-muc-role-form');
         *  el.addEventListener('roleChanged', () => { ... });
         */
        var event = new CustomEvent('roleChanged', {
          bubbles: true
        });
        _this.dispatchEvent(event);
      }, function (e) {
        if (role_form_sizzle("not-allowed[xmlns=\"".concat(role_form_Strophe.NS.STANZAS, "\"]"), e).length) {
          _this.alert(__("You're not allowed to make that change"), 'danger');
        } else {
          _this.alert(__('Sorry, something went wrong while trying to set the role'), 'danger');
          if (isErrorObject(e)) log.error(e);
        }
      });
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        muc: {
          type: Object
        },
        jid: {
          type: String
        },
        role: {
          type: String
        },
        alert_message: {
          type: String,
          attribute: false
        },
        alert_type: {
          type: String,
          attribute: false
        }
      };
    }
  }]);
  return RoleForm;
}(CustomElement);
shared_api.elements.define('converse-muc-role-form', RoleForm);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/message-form.js
var templates_message_form_templateObject;
function templates_message_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const templates_message_form = (function (o) {
  var label_message = o.composing_spoiler ? __('Hidden message') : __('Message');
  var label_spoiler_hint = __('Optional hint');
  var show_send_button = shared_api.settings.get('show_send_button');
  return (0,external_lit_namespaceObject.html)(templates_message_form_templateObject || (templates_message_form_templateObject = templates_message_form_taggedTemplateLiteral(["\n        <form class=\"setNicknameButtonForm hidden\">\n            <input type=\"submit\" class=\"btn btn-primary\" name=\"join\" value=\"Join\"/>\n        </form>\n        <form class=\"sendXMPPMessage\">\n            <input type=\"text\" placeholder=\"", "\" value=\"", "\" class=\"", " spoiler-hint\"/>\n            <div class=\"suggestion-box\">\n                <ul class=\"suggestion-box__results suggestion-box__results--above\" hidden=\"\"></ul>\n                <textarea\n                    autofocus\n                    type=\"text\"\n                    @drop=", "\n                    @input=", "\n                    @keydown=", "\n                    @keyup=", "\n                    @paste=", "\n                    @change=", "\n                    class=\"chat-textarea suggestion-box__input\n                        ", "\n                        ", "\"\n                    placeholder=\"", "\">", "</textarea>\n                <span class=\"suggestion-box__additions visually-hidden\" role=\"status\" aria-live=\"assertive\" aria-relevant=\"additions\"></span>\n            </div>\n        </form>"])), label_spoiler_hint || '', o.hint_value || '', o.composing_spoiler ? '' : 'hidden', o.onDrop, resetElementHeight, o.onKeyDown, o.onKeyUp, o.onPaste, o.onChange, show_send_button ? 'chat-textarea-send-button' : '', o.composing_spoiler ? 'spoiler' : '', label_message, o.message_value || '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/message-form.js
function muc_views_message_form_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_message_form_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;
  }, muc_views_message_form_typeof(obj);
}
function muc_views_message_form_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_message_form_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" == muc_views_message_form_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 muc_views_message_form_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 muc_views_message_form_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_message_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_message_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function muc_views_message_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_views_message_form_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, muc_views_message_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_views_message_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_views_message_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_views_message_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_views_message_form_toPropertyKey(arg) {
  var key = muc_views_message_form_toPrimitive(arg, "string");
  return muc_views_message_form_typeof(key) === "symbol" ? key : String(key);
}
function muc_views_message_form_toPrimitive(input, hint) {
  if (muc_views_message_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_views_message_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_views_message_form_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    muc_views_message_form_get = Reflect.get.bind();
  } else {
    muc_views_message_form_get = function _get(target, property, receiver) {
      var base = muc_views_message_form_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return muc_views_message_form_get.apply(this, arguments);
}
function muc_views_message_form_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = muc_views_message_form_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function muc_views_message_form_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) muc_views_message_form_setPrototypeOf(subClass, superClass);
}
function muc_views_message_form_setPrototypeOf(o, p) {
  muc_views_message_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_views_message_form_setPrototypeOf(o, p);
}
function muc_views_message_form_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_views_message_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_views_message_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_views_message_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_views_message_form_possibleConstructorReturn(this, result);
  };
}
function muc_views_message_form_possibleConstructorReturn(self, call) {
  if (call && (muc_views_message_form_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 muc_views_message_form_assertThisInitialized(self);
}
function muc_views_message_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_views_message_form_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 muc_views_message_form_getPrototypeOf(o) {
  muc_views_message_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_views_message_form_getPrototypeOf(o);
}




var MUCMessageForm = /*#__PURE__*/function (_MessageForm) {
  muc_views_message_form_inherits(MUCMessageForm, _MessageForm);
  var _super = muc_views_message_form_createSuper(MUCMessageForm);
  function MUCMessageForm() {
    muc_views_message_form_classCallCheck(this, MUCMessageForm);
    return _super.apply(this, arguments);
  }
  muc_views_message_form_createClass(MUCMessageForm, [{
    key: "connectedCallback",
    value: function () {
      var _connectedCallback = muc_views_message_form_asyncToGenerator( /*#__PURE__*/muc_views_message_form_regeneratorRuntime().mark(function _callee() {
        return muc_views_message_form_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              muc_views_message_form_get(muc_views_message_form_getPrototypeOf(MUCMessageForm.prototype), "connectedCallback", this).call(this);
              _context.next = 3;
              return this.model.initialized;
            case 3:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function connectedCallback() {
        return _connectedCallback.apply(this, arguments);
      }
      return connectedCallback;
    }()
  }, {
    key: "toHTML",
    value: function toHTML() {
      var _this$querySelector,
        _this$querySelector2,
        _this = this;
      return templates_message_form(Object.assign(this.model.toJSON(), {
        'hint_value': (_this$querySelector = this.querySelector('.spoiler-hint')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.value,
        'message_value': (_this$querySelector2 = this.querySelector('.chat-textarea')) === null || _this$querySelector2 === void 0 ? void 0 : _this$querySelector2.value,
        'onChange': function onChange(ev) {
          return _this.model.set({
            'draft': ev.target.value
          });
        },
        'onDrop': function onDrop(ev) {
          return _this.onDrop(ev);
        },
        'onKeyDown': function onKeyDown(ev) {
          return _this.onKeyDown(ev);
        },
        'onKeyUp': function onKeyUp(ev) {
          return _this.onKeyUp(ev);
        },
        'onPaste': function onPaste(ev) {
          return _this.onPaste(ev);
        },
        'scrolled': this.model.ui.get('scrolled'),
        'viewUnreadMessages': function viewUnreadMessages(ev) {
          return _this.viewUnreadMessages(ev);
        }
      }));
    }
  }, {
    key: "afterRender",
    value: function afterRender() {
      var entered = this.model.session.get('connection_status') === public_converse.ROOMSTATUS.ENTERED;
      var can_edit = entered && !(this.model.features.get('moderated') && this.model.getOwnRole() === 'visitor');
      if (entered && can_edit) {
        this.initMentionAutoComplete();
      }
    }
  }, {
    key: "initMentionAutoComplete",
    value: function initMentionAutoComplete() {
      var _this2 = this;
      this.mention_auto_complete = new shared_converse.AutoComplete(this, {
        'auto_first': true,
        'auto_evaluate': false,
        'min_chars': shared_api.settings.get('muc_mention_autocomplete_min_chars'),
        'match_current_word': true,
        'list': function list() {
          return _this2.getAutoCompleteList();
        },
        'filter': shared_api.settings.get('muc_mention_autocomplete_filter') == 'contains' ? shared_converse.FILTER_CONTAINS : shared_converse.FILTER_STARTSWITH,
        'ac_triggers': ['Tab', '@'],
        'include_triggers': [],
        'item': getAutoCompleteListItem
      });
      this.mention_auto_complete.on('suggestion-box-selectcomplete', function () {
        return _this2.auto_completing = false;
      });
    }
  }, {
    key: "getAutoCompleteList",
    value: function getAutoCompleteList() {
      return this.model.getAllKnownNicknames().map(function (nick) {
        return {
          'label': nick,
          'value': "@".concat(nick)
        };
      });
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(ev) {
      if (this.mention_auto_complete.onKeyDown(ev)) {
        return;
      }
      muc_views_message_form_get(muc_views_message_form_getPrototypeOf(MUCMessageForm.prototype), "onKeyDown", this).call(this, ev);
    }
  }, {
    key: "onKeyUp",
    value: function onKeyUp(ev) {
      this.mention_auto_complete.evaluate(ev);
      muc_views_message_form_get(muc_views_message_form_getPrototypeOf(MUCMessageForm.prototype), "onKeyUp", this).call(this, ev);
    }
  }]);
  return MUCMessageForm;
}(MessageForm);

shared_api.elements.define('converse-muc-message-form', MUCMessageForm);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-nickname-form.js
var muc_nickname_form_templateObject;
function muc_nickname_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const muc_nickname_form = (function (el) {
  var _el$model, _el$model2, _el$model3;
  var i18n_nickname = __('Nickname');
  var i18n_join = (_el$model = el.model) !== null && _el$model !== void 0 && _el$model.isEntered() ? __('Change nickname') : __('Enter groupchat');
  var i18n_heading = shared_api.settings.get('muc_show_logs_before_join') ? __('Choose a nickname to enter') : __('Please choose your nickname');
  var validation_message = (_el$model2 = el.model) === null || _el$model2 === void 0 ? void 0 : _el$model2.get('nickname_validation_message');
  return (0,external_lit_namespaceObject.html)(muc_nickname_form_templateObject || (muc_nickname_form_templateObject = muc_nickname_form_taggedTemplateLiteral(["\n        <div class=\"chatroom-form-container muc-nickname-form\">\n                <form class=\"converse-form chatroom-form converse-centered-form\"\n                        @submit=", ">\n                <fieldset class=\"form-group\">\n                    <label>", "</label>\n                    <p class=\"validation-message\">", "</p>\n                    <input type=\"text\"\n                        required=\"required\"\n                        name=\"nick\"\n                        value=\"", "\"\n                        class=\"form-control ", "\"\n                        placeholder=\"", "\"/>\n                </fieldset>\n                <fieldset class=\"form-group\">\n                    <input type=\"submit\"\n                        class=\"btn btn-primary\"\n                        name=\"join\"\n                        value=\"", "\"/>\n                </fieldset>\n            </form>\n        </div>"])), function (ev) {
    return el.submitNickname(ev);
  }, i18n_heading, validation_message, ((_el$model3 = el.model) === null || _el$model3 === void 0 ? void 0 : _el$model3.get('nick')) || '', validation_message ? 'error' : '', i18n_nickname, i18n_join);
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/nickname-form.scss
var nickname_form = __webpack_require__(3449);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/nickname-form.scss

      
      
      
      
      
      
      
      
      

var nickname_form_options = {};

nickname_form_options.styleTagTransform = (styleTagTransform_default());
nickname_form_options.setAttributes = (setAttributesWithoutAttributes_default());

      nickname_form_options.insert = insertBySelector_default().bind(null, "head");
    
nickname_form_options.domAPI = (styleDomAPI_default());
nickname_form_options.insertStyleElement = (insertStyleElement_default());

var nickname_form_update = injectStylesIntoStyleTag_default()(nickname_form/* default */.Z, nickname_form_options);




       /* harmony default export */ const styles_nickname_form = (nickname_form/* default */.Z && nickname_form/* default */.Z.locals ? nickname_form/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/nickname-form.js
function nickname_form_typeof(obj) {
  "@babel/helpers - typeof";

  return nickname_form_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;
  }, nickname_form_typeof(obj);
}
function nickname_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function nickname_form_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, nickname_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function nickname_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) nickname_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) nickname_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function nickname_form_toPropertyKey(arg) {
  var key = nickname_form_toPrimitive(arg, "string");
  return nickname_form_typeof(key) === "symbol" ? key : String(key);
}
function nickname_form_toPrimitive(input, hint) {
  if (nickname_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (nickname_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function nickname_form_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    nickname_form_get = Reflect.get.bind();
  } else {
    nickname_form_get = function _get(target, property, receiver) {
      var base = nickname_form_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return nickname_form_get.apply(this, arguments);
}
function nickname_form_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = nickname_form_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function nickname_form_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) nickname_form_setPrototypeOf(subClass, superClass);
}
function nickname_form_setPrototypeOf(o, p) {
  nickname_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return nickname_form_setPrototypeOf(o, p);
}
function nickname_form_createSuper(Derived) {
  var hasNativeReflectConstruct = nickname_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = nickname_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = nickname_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return nickname_form_possibleConstructorReturn(this, result);
  };
}
function nickname_form_possibleConstructorReturn(self, call) {
  if (call && (nickname_form_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 nickname_form_assertThisInitialized(self);
}
function nickname_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function nickname_form_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 nickname_form_getPrototypeOf(o) {
  nickname_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return nickname_form_getPrototypeOf(o);
}




var MUCNicknameForm = /*#__PURE__*/function (_CustomElement) {
  nickname_form_inherits(MUCNicknameForm, _CustomElement);
  var _super = nickname_form_createSuper(MUCNicknameForm);
  function MUCNicknameForm() {
    nickname_form_classCallCheck(this, MUCNicknameForm);
    return _super.apply(this, arguments);
  }
  nickname_form_createClass(MUCNicknameForm, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      nickname_form_get(nickname_form_getPrototypeOf(MUCNicknameForm.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
    }
  }, {
    key: "render",
    value: function render() {
      return muc_nickname_form(this);
    }
  }, {
    key: "submitNickname",
    value: function submitNickname(ev) {
      ev.preventDefault();
      var nick = ev.target.nick.value.trim();
      if (!nick) {
        return;
      }
      if (this.model.isEntered()) {
        this.model.setNickname(nick);
        this.closeModal();
      } else {
        this.model.join(nick);
      }
    }
  }, {
    key: "closeModal",
    value: function closeModal() {
      var evt = document.createEvent('Event');
      evt.initEvent('hide.bs.modal', true, true);
      this.dispatchEvent(evt);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCNicknameForm;
}(CustomElement);
shared_api.elements.define('converse-muc-nickname-form', MUCNicknameForm);
/* harmony default export */ const muc_views_nickname_form = ((/* unused pure expression or super */ null && (MUCNicknameForm)));
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-bottom-panel.js
var muc_bottom_panel_templateObject, muc_bottom_panel_templateObject2, muc_bottom_panel_templateObject3, muc_bottom_panel_templateObject4, muc_bottom_panel_templateObject5, muc_bottom_panel_templateObject6, muc_bottom_panel_templateObject7;
function muc_bottom_panel_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}






var tplCanEdit = function tplCanEdit(o) {
  var unread_msgs = __('You have unread messages');
  var message_limit = shared_api.settings.get('message_limit');
  var show_call_button = shared_api.settings.get('visible_toolbar_buttons').call;
  var show_emoji_button = shared_api.settings.get('visible_toolbar_buttons').emoji;
  var show_send_button = shared_api.settings.get('show_send_button');
  var show_spoiler_button = shared_api.settings.get('visible_toolbar_buttons').spoiler;
  var show_toolbar = shared_api.settings.get('show_toolbar');
  return (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject || (muc_bottom_panel_templateObject = muc_bottom_panel_taggedTemplateLiteral(["\n        ", "\n        ", "\n        <converse-muc-message-form jid=", "></converse-muc-message-form>"])), o.model.ui.get('scrolled') && o.model.get('num_unread') ? (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject2 || (muc_bottom_panel_templateObject2 = muc_bottom_panel_taggedTemplateLiteral(["<div class=\"new-msgs-indicator\" @click=", ">\u25BC ", " \u25BC</div>"])), function (ev) {
    return o.viewUnreadMessages(ev);
  }, unread_msgs) : '', show_toolbar ? (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject3 || (muc_bottom_panel_templateObject3 = muc_bottom_panel_taggedTemplateLiteral(["\n            <converse-chat-toolbar\n                class=\"chat-toolbar no-text-select\"\n                .model=", "\n                ?hidden_occupants=\"", "\"\n                ?is_groupchat=\"", "\"\n                ?show_call_button=\"", "\"\n                ?show_emoji_button=\"", "\"\n                ?show_send_button=\"", "\"\n                ?show_spoiler_button=\"", "\"\n                ?show_toolbar=\"", "\"\n                message_limit=\"", "\"></converse-chat-toolbar>"])), o.model, o.model.get('hidden_occupants'), o.is_groupchat, show_call_button, show_emoji_button, show_send_button, show_spoiler_button, show_toolbar, message_limit) : '', o.model.get('jid'));
};
/* harmony default export */ const muc_bottom_panel = (function (o) {
  var unread_msgs = __('You have unread messages');
  var conn_status = o.model.session.get('connection_status');
  var i18n_not_allowed = __("You're not allowed to send messages in this room");
  if (conn_status === public_converse.ROOMSTATUS.ENTERED) {
    return (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject4 || (muc_bottom_panel_templateObject4 = muc_bottom_panel_taggedTemplateLiteral(["\n            ", "\n            ", ""])), o.model.ui.get('scrolled') && o.model.get('num_unread_general') ? (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject5 || (muc_bottom_panel_templateObject5 = muc_bottom_panel_taggedTemplateLiteral(["<div class=\"new-msgs-indicator\" @click=", ">\u25BC ", " \u25BC</div>"])), function (ev) {
      return o.viewUnreadMessages(ev);
    }, unread_msgs) : '', o.can_edit ? tplCanEdit(o) : (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject6 || (muc_bottom_panel_templateObject6 = muc_bottom_panel_taggedTemplateLiteral(["<span class=\"muc-bottom-panel muc-bottom-panel--muted\">", "</span>"])), i18n_not_allowed));
  } else if (conn_status == public_converse.ROOMSTATUS.NICKNAME_REQUIRED) {
    if (shared_api.settings.get('muc_show_logs_before_join')) {
      return (0,external_lit_namespaceObject.html)(muc_bottom_panel_templateObject7 || (muc_bottom_panel_templateObject7 = muc_bottom_panel_taggedTemplateLiteral(["<span class=\"muc-bottom-panel muc-bottom-panel--nickname\">\n                <converse-muc-nickname-form jid=\"", "\"></converse-muc-nickname-form>\n            </span>"])), o.model.get('jid'));
    }
  } else {
    return '';
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/muc-bottom-panel.scss
var styles_muc_bottom_panel = __webpack_require__(9224);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/muc-bottom-panel.scss

      
      
      
      
      
      
      
      
      

var muc_bottom_panel_options = {};

muc_bottom_panel_options.styleTagTransform = (styleTagTransform_default());
muc_bottom_panel_options.setAttributes = (setAttributesWithoutAttributes_default());

      muc_bottom_panel_options.insert = insertBySelector_default().bind(null, "head");
    
muc_bottom_panel_options.domAPI = (styleDomAPI_default());
muc_bottom_panel_options.insertStyleElement = (insertStyleElement_default());

var muc_bottom_panel_update = injectStylesIntoStyleTag_default()(styles_muc_bottom_panel/* default */.Z, muc_bottom_panel_options);




       /* harmony default export */ const muc_views_styles_muc_bottom_panel = (styles_muc_bottom_panel/* default */.Z && styles_muc_bottom_panel/* default */.Z.locals ? styles_muc_bottom_panel/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/bottom-panel.js
function muc_views_bottom_panel_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_bottom_panel_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;
  }, muc_views_bottom_panel_typeof(obj);
}
function muc_views_bottom_panel_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_bottom_panel_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" == muc_views_bottom_panel_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 muc_views_bottom_panel_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 muc_views_bottom_panel_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_bottom_panel_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_bottom_panel_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function muc_views_bottom_panel_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_views_bottom_panel_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, muc_views_bottom_panel_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_views_bottom_panel_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_views_bottom_panel_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_views_bottom_panel_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_views_bottom_panel_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    muc_views_bottom_panel_get = Reflect.get.bind();
  } else {
    muc_views_bottom_panel_get = function _get(target, property, receiver) {
      var base = muc_views_bottom_panel_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return muc_views_bottom_panel_get.apply(this, arguments);
}
function muc_views_bottom_panel_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = muc_views_bottom_panel_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function muc_views_bottom_panel_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) muc_views_bottom_panel_setPrototypeOf(subClass, superClass);
}
function muc_views_bottom_panel_setPrototypeOf(o, p) {
  muc_views_bottom_panel_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_views_bottom_panel_setPrototypeOf(o, p);
}
function muc_views_bottom_panel_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_views_bottom_panel_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_views_bottom_panel_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_views_bottom_panel_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_views_bottom_panel_possibleConstructorReturn(this, result);
  };
}
function muc_views_bottom_panel_possibleConstructorReturn(self, call) {
  if (call && (muc_views_bottom_panel_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 muc_views_bottom_panel_assertThisInitialized(self);
}
function muc_views_bottom_panel_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_views_bottom_panel_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 muc_views_bottom_panel_getPrototypeOf(o) {
  muc_views_bottom_panel_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_views_bottom_panel_getPrototypeOf(o);
}
function muc_views_bottom_panel_defineProperty(obj, key, value) {
  key = muc_views_bottom_panel_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 muc_views_bottom_panel_toPropertyKey(arg) {
  var key = muc_views_bottom_panel_toPrimitive(arg, "string");
  return muc_views_bottom_panel_typeof(key) === "symbol" ? key : String(key);
}
function muc_views_bottom_panel_toPrimitive(input, hint) {
  if (muc_views_bottom_panel_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_views_bottom_panel_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}






var MUCBottomPanel = /*#__PURE__*/function (_BottomPanel) {
  muc_views_bottom_panel_inherits(MUCBottomPanel, _BottomPanel);
  var _super = muc_views_bottom_panel_createSuper(MUCBottomPanel);
  function MUCBottomPanel() {
    var _this;
    muc_views_bottom_panel_classCallCheck(this, MUCBottomPanel);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    muc_views_bottom_panel_defineProperty(muc_views_bottom_panel_assertThisInitialized(_this), "events", {
      'click .hide-occupants': 'hideOccupants',
      'click .send-button': 'sendButtonClicked'
    });
    return _this;
  }
  muc_views_bottom_panel_createClass(MUCBottomPanel, [{
    key: "initialize",
    value: function () {
      var _initialize = muc_views_bottom_panel_asyncToGenerator( /*#__PURE__*/muc_views_bottom_panel_regeneratorRuntime().mark(function _callee() {
        return muc_views_bottom_panel_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return muc_views_bottom_panel_get(muc_views_bottom_panel_getPrototypeOf(MUCBottomPanel.prototype), "initialize", this).call(this);
            case 2:
              this.listenTo(this.model, 'change:hidden_occupants', this.debouncedRender);
              this.listenTo(this.model, 'change:num_unread_general', this.debouncedRender);
              this.listenTo(this.model.features, 'change:moderated', this.debouncedRender);
              this.listenTo(this.model.occupants, 'add', this.renderIfOwnOccupant);
              this.listenTo(this.model.occupants, 'change:role', this.renderIfOwnOccupant);
              this.listenTo(this.model.session, 'change:connection_status', this.debouncedRender);
            case 8:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var entered = this.model.session.get('connection_status') === public_converse.ROOMSTATUS.ENTERED;
      var can_edit = entered && !(this.model.features.get('moderated') && this.model.getOwnRole() === 'visitor');
      (0,external_lit_namespaceObject.render)(muc_bottom_panel({
        can_edit: can_edit,
        entered: entered,
        'model': this.model,
        'is_groupchat': true,
        'viewUnreadMessages': function viewUnreadMessages(ev) {
          return _this2.viewUnreadMessages(ev);
        }
      }), this);
    }
  }, {
    key: "renderIfOwnOccupant",
    value: function renderIfOwnOccupant(o) {
      o.get('jid') === shared_converse.bare_jid && this.debouncedRender();
    }
  }, {
    key: "sendButtonClicked",
    value: function sendButtonClicked(ev) {
      var _this$querySelector;
      (_this$querySelector = this.querySelector('converse-muc-message-form')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.onFormSubmitted(ev);
    }
  }, {
    key: "hideOccupants",
    value: function hideOccupants(ev) {
      var _ev$preventDefault, _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      this.model.save({
        'hidden_occupants': true
      });
    }
  }]);
  return MUCBottomPanel;
}(ChatBottomPanel);

shared_api.elements.define('converse-muc-bottom-panel', MUCBottomPanel);
;// CONCATENATED MODULE: ./src/plugins/muc-views/constants.js
var PRETTY_CHAT_STATUS = {
  'offline': 'Offline',
  'unavailable': 'Unavailable',
  'xa': 'Extended Away',
  'away': 'Away',
  'dnd': 'Do not disturb',
  'chat': 'Chattty',
  'online': 'Online'
};
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/occupant.js
var templates_occupant_templateObject, templates_occupant_templateObject2, templates_occupant_templateObject3, occupant_templateObject4, occupant_templateObject5, occupant_templateObject6;
function templates_occupant_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var i18n_occupant_hint = function i18n_occupant_hint(o) {
  return __('Click to mention %1$s in your message.', o.get('nick'));
};
var occupant_title = function occupant_title(o) {
  var role = o.get('role');
  var hint_occupant = i18n_occupant_hint(o);
  var i18n_moderator_hint = __('This user is a moderator.');
  var i18n_participant_hint = __('This user can send messages in this groupchat.');
  var i18n_visitor_hint = __('This user can NOT send messages in this groupchat.');
  var spaced_jid = o.get('jid') ? "".concat(o.get('jid'), " ") : '';
  if (role === "moderator") {
    return "".concat(spaced_jid).concat(i18n_moderator_hint, " ").concat(hint_occupant);
  } else if (role === "participant") {
    return "".concat(spaced_jid).concat(i18n_participant_hint, " ").concat(hint_occupant);
  } else if (role === "visitor") {
    return "".concat(spaced_jid).concat(i18n_visitor_hint, " ").concat(hint_occupant);
  } else if (!["visitor", "participant", "moderator"].includes(role)) {
    return "".concat(spaced_jid).concat(hint_occupant);
  }
};
/* harmony default export */ const muc_views_templates_occupant = (function (o, chat) {
  var _o$vcard, _o$vcard2;
  var affiliation = o.get('affiliation');
  var hint_show = PRETTY_CHAT_STATUS[o.get('show')];
  var i18n_admin = __('Admin');
  var i18n_member = __('Member');
  var i18n_moderator = __('Moderator');
  var i18n_owner = __('Owner');
  var i18n_visitor = __('Visitor');
  var role = o.get('role');
  var show = o.get('show');
  var classes, color;
  if (show === 'online') {
    classes = 'fa fa-circle';
    color = 'chat-status-online';
  } else if (show === 'dnd') {
    classes = 'fa fa-minus-circle';
    color = 'chat-status-busy';
  } else if (show === 'away') {
    classes = 'fa fa-circle';
    color = 'chat-status-away';
  } else {
    classes = 'fa fa-circle';
    color = 'subdued-color';
  }
  return (0,external_lit_namespaceObject.html)(templates_occupant_templateObject || (templates_occupant_templateObject = templates_occupant_taggedTemplateLiteral(["\n        <li class=\"occupant\" id=\"", "\" title=\"", "\">\n            <div class=\"row no-gutters\">\n                <div class=\"col-auto\">\n                    <a class=\"show-msg-author-modal\" @click=", ">\n                        <converse-avatar\n                            class=\"avatar chat-msg__avatar\"\n                            .data=", "\n                            nonce=", "\n                            height=\"30\" width=\"30\"></converse-avatar>\n                        <converse-icon\n                           title=\"", "\"\n                           color=\"var(--", ")\"\n                           style=\"margin-top: -0.1em\"\n                           size=\"0.82em\"\n                           class=\"", " chat-status chat-status--avatar\"></converse-icon>\n                    </a>\n                </div>\n                <div class=\"col occupant-nick-badge\">\n                    <span class=\"occupant-nick\" @click=", ">", "</span>\n                    <span class=\"occupant-badges\">\n                        ", "\n                        ", "\n                        ", "\n                        ", "\n                        ", "\n                    </span>\n                </div>\n            </div>\n        </li>\n    "])), o.id, occupant_title(o), function (ev) {
    return showOccupantModal(ev, o);
  }, (_o$vcard = o.vcard) === null || _o$vcard === void 0 ? void 0 : _o$vcard.attributes, (_o$vcard2 = o.vcard) === null || _o$vcard2 === void 0 ? void 0 : _o$vcard2.get('vcard_updated'), hint_show, color, classes, chat.onOccupantClicked, o.getDisplayName(), affiliation === "owner" ? (0,external_lit_namespaceObject.html)(templates_occupant_templateObject2 || (templates_occupant_templateObject2 = templates_occupant_taggedTemplateLiteral(["<span class=\"badge badge-groupchat\">", "</span>"])), i18n_owner) : '', affiliation === "admin" ? (0,external_lit_namespaceObject.html)(templates_occupant_templateObject3 || (templates_occupant_templateObject3 = templates_occupant_taggedTemplateLiteral(["<span class=\"badge badge-info\">", "</span>"])), i18n_admin) : '', affiliation === "member" ? (0,external_lit_namespaceObject.html)(occupant_templateObject4 || (occupant_templateObject4 = templates_occupant_taggedTemplateLiteral(["<span class=\"badge badge-info\">", "</span>"])), i18n_member) : '', role === "moderator" ? (0,external_lit_namespaceObject.html)(occupant_templateObject5 || (occupant_templateObject5 = templates_occupant_taggedTemplateLiteral(["<span class=\"badge badge-info\">", "</span>"])), i18n_moderator) : '', role === "visitor" ? (0,external_lit_namespaceObject.html)(occupant_templateObject6 || (occupant_templateObject6 = templates_occupant_taggedTemplateLiteral(["<span class=\"badge badge-secondary\">", "</span>"])), i18n_visitor) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-sidebar.js
var muc_sidebar_templateObject;
function muc_sidebar_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const muc_sidebar = (function (o) {
  var i18n_participants = o.occupants.length === 1 ? __('Participant') : __('Participants');
  return (0,external_lit_namespaceObject.html)(muc_sidebar_templateObject || (muc_sidebar_templateObject = muc_sidebar_taggedTemplateLiteral(["\n        <div class=\"occupants-header\">\n            <div class=\"occupants-header--title\">\n                <span class=\"occupants-heading\">", " ", "</span>\n                <i class=\"hide-occupants\" @click=", ">\n                    <converse-icon class=\"fa fa-times\" size=\"1em\"></converse-icon>\n                </i>\n            </div>\n        </div>\n        <div class=\"dragresize dragresize-occupants-left\"></div>\n        <ul class=\"occupant-list\">", "</ul>\n    "])), o.occupants.length, i18n_participants, o.closeSidebar, repeat_c(o.occupants, function (occ) {
    return occ.get('jid');
  }, function (occ) {
    return muc_views_templates_occupant(occ, o);
  }));
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/styles/status.scss
var styles_status = __webpack_require__(8258);
;// CONCATENATED MODULE: ./src/shared/styles/status.scss

      
      
      
      
      
      
      
      
      

var status_options = {};

status_options.styleTagTransform = (styleTagTransform_default());
status_options.setAttributes = (setAttributesWithoutAttributes_default());

      status_options.insert = insertBySelector_default().bind(null, "head");
    
status_options.domAPI = (styleDomAPI_default());
status_options.insertStyleElement = (insertStyleElement_default());

var status_update = injectStylesIntoStyleTag_default()(styles_status/* default */.Z, status_options);




       /* harmony default export */ const shared_styles_status = (styles_status/* default */.Z && styles_status/* default */.Z.locals ? styles_status/* default */.Z.locals : undefined);

// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/muc-occupants.scss
var muc_occupants = __webpack_require__(4669);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/muc-occupants.scss

      
      
      
      
      
      
      
      
      

var muc_occupants_options = {};

muc_occupants_options.styleTagTransform = (styleTagTransform_default());
muc_occupants_options.setAttributes = (setAttributesWithoutAttributes_default());

      muc_occupants_options.insert = insertBySelector_default().bind(null, "head");
    
muc_occupants_options.domAPI = (styleDomAPI_default());
muc_occupants_options.insertStyleElement = (insertStyleElement_default());

var muc_occupants_update = injectStylesIntoStyleTag_default()(muc_occupants/* default */.Z, muc_occupants_options);




       /* harmony default export */ const styles_muc_occupants = (muc_occupants/* default */.Z && muc_occupants/* default */.Z.locals ? muc_occupants/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/sidebar.js
function sidebar_typeof(obj) {
  "@babel/helpers - typeof";

  return sidebar_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;
  }, sidebar_typeof(obj);
}
function sidebar_toConsumableArray(arr) {
  return sidebar_arrayWithoutHoles(arr) || sidebar_iterableToArray(arr) || sidebar_unsupportedIterableToArray(arr) || sidebar_nonIterableSpread();
}
function sidebar_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function sidebar_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return sidebar_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 sidebar_arrayLikeToArray(o, minLen);
}
function sidebar_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function sidebar_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return sidebar_arrayLikeToArray(arr);
}
function sidebar_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 sidebar_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function sidebar_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, sidebar_toPropertyKey(descriptor.key), descriptor);
  }
}
function sidebar_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) sidebar_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) sidebar_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function sidebar_toPropertyKey(arg) {
  var key = sidebar_toPrimitive(arg, "string");
  return sidebar_typeof(key) === "symbol" ? key : String(key);
}
function sidebar_toPrimitive(input, hint) {
  if (sidebar_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (sidebar_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function sidebar_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    sidebar_get = Reflect.get.bind();
  } else {
    sidebar_get = function _get(target, property, receiver) {
      var base = sidebar_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return sidebar_get.apply(this, arguments);
}
function sidebar_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = sidebar_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function sidebar_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) sidebar_setPrototypeOf(subClass, superClass);
}
function sidebar_setPrototypeOf(o, p) {
  sidebar_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return sidebar_setPrototypeOf(o, p);
}
function sidebar_createSuper(Derived) {
  var hasNativeReflectConstruct = sidebar_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = sidebar_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = sidebar_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return sidebar_possibleConstructorReturn(this, result);
  };
}
function sidebar_possibleConstructorReturn(self, call) {
  if (call && (sidebar_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 sidebar_assertThisInitialized(self);
}
function sidebar_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function sidebar_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 sidebar_getPrototypeOf(o) {
  sidebar_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return sidebar_getPrototypeOf(o);
}






var sidebar_u = public_converse.env.u;
var MUCSidebar = /*#__PURE__*/function (_CustomElement) {
  sidebar_inherits(MUCSidebar, _CustomElement);
  var _super = sidebar_createSuper(MUCSidebar);
  function MUCSidebar() {
    sidebar_classCallCheck(this, MUCSidebar);
    return _super.apply(this, arguments);
  }
  sidebar_createClass(MUCSidebar, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this = this;
      sidebar_get(sidebar_getPrototypeOf(MUCSidebar.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
      this.listenTo(this.model.occupants, 'add', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model.occupants, 'remove', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model.occupants, 'change', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model.occupants, 'vcard:change', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model.occupants, 'vcard:add', function () {
        return _this.requestUpdate();
      });
      this.model.initialized.then(function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var tpl = muc_sidebar(Object.assign(this.model.toJSON(), {
        'occupants': sidebar_toConsumableArray(this.model.occupants.models),
        'closeSidebar': function closeSidebar(ev) {
          return _this2.closeSidebar(ev);
        },
        'onOccupantClicked': function onOccupantClicked(ev) {
          return _this2.onOccupantClicked(ev);
        }
      }));
      return tpl;
    }
  }, {
    key: "closeSidebar",
    value: function closeSidebar(ev) {
      var _ev$preventDefault, _ev$stopPropagation;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
      sidebar_u.safeSave(this.model, {
        'hidden_occupants': true
      });
    }
  }, {
    key: "onOccupantClicked",
    value: function onOccupantClicked(ev) {
      var _ev$preventDefault2;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      var view = shared_converse.chatboxviews.get(this.getAttribute('jid'));
      view === null || view === void 0 ? void 0 : view.getMessageForm().insertIntoTextArea("@".concat(ev.target.textContent));
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        jid: {
          type: String
        }
      };
    }
  }]);
  return MUCSidebar;
}(CustomElement);

shared_api.elements.define('converse-muc-sidebar', MUCSidebar);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-chatarea.js
var muc_chatarea_templateObject, muc_chatarea_templateObject2, muc_chatarea_templateObject3;
function muc_chatarea_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}






/* harmony default export */ const muc_chatarea = (function (o) {
  var _o$model;
  return (0,external_lit_namespaceObject.html)(muc_chatarea_templateObject || (muc_chatarea_templateObject = muc_chatarea_taggedTemplateLiteral(["\n    <div class=\"chat-area\">\n        <div class=\"chat-content ", "\" aria-live=\"polite\">\n            <converse-chat-content\n                class=\"chat-content__messages\"\n                jid=\"", "\"></converse-chat-content>\n\n            ", "\n        </div>\n        <converse-muc-bottom-panel jid=\"", "\" class=\"bottom-panel\"></converse-muc-bottom-panel>\n    </div>\n    <div class=\"disconnect-container hidden\"></div>\n    ", "\n"])), o.show_send_button ? 'chat-content-sendbutton' : '', o.jid, (_o$model = o.model) !== null && _o$model !== void 0 && _o$model.get('show_help_messages') ? (0,external_lit_namespaceObject.html)(muc_chatarea_templateObject2 || (muc_chatarea_templateObject2 = muc_chatarea_taggedTemplateLiteral(["<div class=\"chat-content__help\">\n                    <converse-chat-help\n                        .model=", "\n                        .messages=", "\n                        type=\"info\"\n                        chat_type=\"", "\"\n                    ></converse-chat-help></div>"])), o.model, o.getHelpMessages(), shared_converse.CHATROOMS_TYPE) : '', o.jid, o.model ? (0,external_lit_namespaceObject.html)(muc_chatarea_templateObject3 || (muc_chatarea_templateObject3 = muc_chatarea_taggedTemplateLiteral(["\n        <converse-muc-sidebar\n            class=\"occupants col-md-3 col-4 ", "\"\n            style=\"flex: 0 0 ", "px\"\n            jid=", "\n            @mousedown=", "></converse-muc-sidebar>"])), o.shouldShowSidebar() ? '' : 'hidden', o.model.get('occupants_width'), o.jid, o.onMousedown) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/chatarea.js
function chatarea_typeof(obj) {
  "@babel/helpers - typeof";

  return chatarea_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;
  }, chatarea_typeof(obj);
}
function chatarea_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  chatarea_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" == chatarea_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 chatarea_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 chatarea_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        chatarea_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        chatarea_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function chatarea_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function chatarea_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, chatarea_toPropertyKey(descriptor.key), descriptor);
  }
}
function chatarea_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) chatarea_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) chatarea_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function chatarea_toPropertyKey(arg) {
  var key = chatarea_toPrimitive(arg, "string");
  return chatarea_typeof(key) === "symbol" ? key : String(key);
}
function chatarea_toPrimitive(input, hint) {
  if (chatarea_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chatarea_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function chatarea_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) chatarea_setPrototypeOf(subClass, superClass);
}
function chatarea_setPrototypeOf(o, p) {
  chatarea_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return chatarea_setPrototypeOf(o, p);
}
function chatarea_createSuper(Derived) {
  var hasNativeReflectConstruct = chatarea_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = chatarea_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = chatarea_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return chatarea_possibleConstructorReturn(this, result);
  };
}
function chatarea_possibleConstructorReturn(self, call) {
  if (call && (chatarea_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 chatarea_assertThisInitialized(self);
}
function chatarea_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function chatarea_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 chatarea_getPrototypeOf(o) {
  chatarea_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return chatarea_getPrototypeOf(o);
}




var chatarea_u = public_converse.env.u;
var MUCChatArea = /*#__PURE__*/function (_CustomElement) {
  chatarea_inherits(MUCChatArea, _CustomElement);
  var _super = chatarea_createSuper(MUCChatArea);
  function MUCChatArea() {
    chatarea_classCallCheck(this, MUCChatArea);
    return _super.apply(this, arguments);
  }
  chatarea_createClass(MUCChatArea, [{
    key: "initialize",
    value: function () {
      var _initialize = chatarea_asyncToGenerator( /*#__PURE__*/chatarea_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return chatarea_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.rooms.get(this.jid);
            case 2:
              this.model = _context.sent;
              this.listenTo(this.model, 'change:show_help_messages', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:hidden_occupants', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model.session, 'change:connection_status', function () {
                return _this.requestUpdate();
              });

              // Bind so that we can pass it to addEventListener and removeEventListener
              this.onMouseMove = this._onMouseMove.bind(this);
              this.onMouseUp = this._onMouseUp.bind(this);
              this.requestUpdate();
            // Make sure we render again after the model has been attached
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      return muc_chatarea({
        'getHelpMessages': function getHelpMessages() {
          return _this2.getHelpMessages();
        },
        'jid': this.jid,
        'model': this.model,
        'onMousedown': function onMousedown(ev) {
          return _this2.onMousedown(ev);
        },
        'show_send_button': shared_api.settings.get('show_send_button'),
        'shouldShowSidebar': function shouldShowSidebar() {
          return _this2.shouldShowSidebar();
        },
        'type': this.type
      });
    }
  }, {
    key: "shouldShowSidebar",
    value: function shouldShowSidebar() {
      return !this.model.get('hidden_occupants') && this.model.session.get('connection_status') === public_converse.ROOMSTATUS.ENTERED;
    }
  }, {
    key: "getHelpMessages",
    value: function getHelpMessages() {
      var _this3 = this;
      var setting = shared_api.settings.get('muc_disable_slash_commands');
      var disabled_commands = Array.isArray(setting) ? setting : [];
      return ["<strong>/admin</strong>: ".concat(__("Change user's affiliation to admin")), "<strong>/ban</strong>: ".concat(__('Ban user by changing their affiliation to outcast')), "<strong>/clear</strong>: ".concat(__('Clear the chat area')), "<strong>/close</strong>: ".concat(__('Close this groupchat')), "<strong>/deop</strong>: ".concat(__('Change user role to participant')), "<strong>/destroy</strong>: ".concat(__('Remove this groupchat')), "<strong>/help</strong>: ".concat(__('Show this menu')), "<strong>/kick</strong>: ".concat(__('Kick user from groupchat')), "<strong>/me</strong>: ".concat(__('Write in 3rd person')), "<strong>/member</strong>: ".concat(__('Grant membership to a user')), "<strong>/modtools</strong>: ".concat(__('Opens up the moderator tools GUI')), "<strong>/mute</strong>: ".concat(__("Remove user's ability to post messages")), "<strong>/nick</strong>: ".concat(__('Change your nickname')), "<strong>/op</strong>: ".concat(__('Grant moderator role to user')), "<strong>/owner</strong>: ".concat(__('Grant ownership of this groupchat')), "<strong>/register</strong>: ".concat(__('Register your nickname')), "<strong>/revoke</strong>: ".concat(__("Revoke the user's current affiliation")), "<strong>/subject</strong>: ".concat(__('Set groupchat subject')), "<strong>/topic</strong>: ".concat(__('Set groupchat subject (alias for /subject)')), "<strong>/voice</strong>: ".concat(__('Allow muted user to post messages'))].filter(function (line) {
        return disabled_commands.every(function (c) {
          return !line.startsWith(c + '<', 9);
        });
      }).filter(function (line) {
        return _this3.model.getAllowedCommands().some(function (c) {
          return line.startsWith(c + '<', 9);
        });
      });
    }
  }, {
    key: "onMousedown",
    value: function onMousedown(ev) {
      if (chatarea_u.hasClass('dragresize-occupants-left', ev.target)) {
        this.onStartResizeOccupants(ev);
      }
    }
  }, {
    key: "onStartResizeOccupants",
    value: function onStartResizeOccupants(ev) {
      this.resizing = true;
      this.addEventListener('mousemove', this.onMouseMove);
      this.addEventListener('mouseup', this.onMouseUp);
      var sidebar_el = this.querySelector('converse-muc-sidebar');
      var style = window.getComputedStyle(sidebar_el);
      this.width = parseInt(style.width.replace(/px$/, ''), 10);
      this.prev_pageX = ev.pageX;
    }
  }, {
    key: "_onMouseMove",
    value: function _onMouseMove(ev) {
      if (this.resizing) {
        ev.preventDefault();
        var delta = this.prev_pageX - ev.pageX;
        this.resizeSidebarView(delta, ev.pageX);
        this.prev_pageX = ev.pageX;
      }
    }
  }, {
    key: "_onMouseUp",
    value: function _onMouseUp(ev) {
      if (this.resizing) {
        ev.preventDefault();
        this.resizing = false;
        this.removeEventListener('mousemove', this.onMouseMove);
        this.removeEventListener('mouseup', this.onMouseUp);
        var sidebar_el = this.querySelector('converse-muc-sidebar');
        var element_position = sidebar_el.getBoundingClientRect();
        var occupants_width = this.calculateSidebarWidth(element_position, 0);
        chatarea_u.safeSave(this.model, {
          occupants_width: occupants_width
        });
      }
    }
  }, {
    key: "calculateSidebarWidth",
    value: function calculateSidebarWidth(element_position, delta) {
      var occupants_width = element_position.width + delta;
      var room_width = this.clientWidth;
      // keeping display in boundaries
      if (occupants_width < room_width * 0.2) {
        // set pixel to 20% width
        occupants_width = room_width * 0.2;
        this.is_minimum = true;
      } else if (occupants_width > room_width * 0.75) {
        // set pixel to 75% width
        occupants_width = room_width * 0.75;
        this.is_maximum = true;
      } else if (room_width - occupants_width < 250) {
        // resize occupants if chat-area becomes smaller than 250px (min-width property set in css)
        occupants_width = room_width - 250;
        this.is_maximum = true;
      } else {
        this.is_maximum = false;
        this.is_minimum = false;
      }
      return occupants_width;
    }
  }, {
    key: "resizeSidebarView",
    value: function resizeSidebarView(delta, current_mouse_position) {
      var sidebar_el = this.querySelector('converse-muc-sidebar');
      var element_position = sidebar_el.getBoundingClientRect();
      if (this.is_minimum) {
        this.is_minimum = element_position.left < current_mouse_position;
      } else if (this.is_maximum) {
        this.is_maximum = element_position.left > current_mouse_position;
      } else {
        var occupants_width = this.calculateSidebarWidth(element_position, delta);
        sidebar_el.style.flex = '0 0 ' + occupants_width + 'px';
      }
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        jid: {
          type: String
        },
        show_help_messages: {
          type: Boolean
        },
        type: {
          type: String
        }
      };
    }
  }]);
  return MUCChatArea;
}(CustomElement);

shared_api.elements.define('converse-muc-chatarea', MUCChatArea);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-config-form.js
var muc_config_form_templateObject, muc_config_form_templateObject2, muc_config_form_templateObject3;
function muc_config_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var muc_config_form_sizzle = public_converse.env.sizzle;
var muc_config_form_u = public_converse.env.utils;
/* harmony default export */ const muc_config_form = (function (o) {
  var whitelist = shared_api.settings.get('roomconfig_whitelist');
  var config_stanza = o.model.session.get('config_stanza');
  var fields = [];
  var instructions = '';
  var title;
  if (config_stanza) {
    var _stanza$querySelector, _stanza$querySelector2;
    var stanza = muc_config_form_u.toStanza(config_stanza);
    fields = muc_config_form_sizzle('field', stanza);
    if (whitelist.length) {
      fields = fields.filter(function (f) {
        return whitelist.includes(f.getAttribute('var'));
      });
    }
    var password_protected = o.model.features.get('passwordprotected');
    var options = {
      'new_password': !password_protected,
      'fixed_username': o.model.get('jid')
    };
    fields = fields.map(function (f) {
      return muc_config_form_u.xForm2TemplateResult(f, stanza, options);
    });
    instructions = (_stanza$querySelector = stanza.querySelector('instructions')) === null || _stanza$querySelector === void 0 ? void 0 : _stanza$querySelector.textContent;
    title = (_stanza$querySelector2 = stanza.querySelector('title')) === null || _stanza$querySelector2 === void 0 ? void 0 : _stanza$querySelector2.textContent;
  } else {
    title = __('Loading configuration form');
  }
  var i18n_save = __('Save');
  var i18n_cancel = __('Cancel');
  return (0,external_lit_namespaceObject.html)(muc_config_form_templateObject || (muc_config_form_templateObject = muc_config_form_taggedTemplateLiteral(["\n        <form class=\"converse-form chatroom-form ", "\"\n                autocomplete=\"off\"\n                @submit=", ">\n\n            <fieldset class=\"form-group\">\n                <legend class=\"centered\">", "</legend>\n                ", "\n                ", "\n            </fieldset>\n            ", "\n        </form>\n    "])), fields.length ? '' : 'converse-form--spinner', o.submitConfigForm, title, title !== instructions ? (0,external_lit_namespaceObject.html)(muc_config_form_templateObject2 || (muc_config_form_templateObject2 = muc_config_form_taggedTemplateLiteral(["<p class=\"form-help\">", "</p>"])), instructions) : '', fields.length ? fields : spinner({
    'classes': 'hor_centered'
  }), fields.length ? (0,external_lit_namespaceObject.html)(muc_config_form_templateObject3 || (muc_config_form_templateObject3 = muc_config_form_taggedTemplateLiteral(["\n                <fieldset>\n                    <input type=\"submit\" class=\"btn btn-primary\" value=\"", "\">\n                    <input type=\"button\" class=\"btn btn-secondary button-cancel\" value=\"", "\" @click=", ">\n                </fieldset>"])), i18n_save, i18n_cancel, o.closeConfigForm) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/config-form.js
function config_form_typeof(obj) {
  "@babel/helpers - typeof";

  return config_form_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;
  }, config_form_typeof(obj);
}
function config_form_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  config_form_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" == config_form_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 config_form_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 config_form_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        config_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        config_form_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function config_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function config_form_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, config_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function config_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) config_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) config_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function config_form_toPropertyKey(arg) {
  var key = config_form_toPrimitive(arg, "string");
  return config_form_typeof(key) === "symbol" ? key : String(key);
}
function config_form_toPrimitive(input, hint) {
  if (config_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (config_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function config_form_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    config_form_get = Reflect.get.bind();
  } else {
    config_form_get = function _get(target, property, receiver) {
      var base = config_form_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return config_form_get.apply(this, arguments);
}
function config_form_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = config_form_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function config_form_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) config_form_setPrototypeOf(subClass, superClass);
}
function config_form_setPrototypeOf(o, p) {
  config_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return config_form_setPrototypeOf(o, p);
}
function config_form_createSuper(Derived) {
  var hasNativeReflectConstruct = config_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = config_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = config_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return config_form_possibleConstructorReturn(this, result);
  };
}
function config_form_possibleConstructorReturn(self, call) {
  if (call && (config_form_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 config_form_assertThisInitialized(self);
}
function config_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function config_form_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 config_form_getPrototypeOf(o) {
  config_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return config_form_getPrototypeOf(o);
}





var config_form_sizzle = public_converse.env.sizzle;
var config_form_u = public_converse.env.utils;
var MUCConfigForm = /*#__PURE__*/function (_CustomElement) {
  config_form_inherits(MUCConfigForm, _CustomElement);
  var _super = config_form_createSuper(MUCConfigForm);
  function MUCConfigForm() {
    config_form_classCallCheck(this, MUCConfigForm);
    return _super.apply(this, arguments);
  }
  config_form_createClass(MUCConfigForm, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      var _this = this;
      config_form_get(config_form_getPrototypeOf(MUCConfigForm.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
      this.listenTo(this.model.features, 'change:passwordprotected', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model.session, 'change:config_stanza', function () {
        return _this.requestUpdate();
      });
      this.getConfig();
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      return muc_config_form({
        'model': this.model,
        'closeConfigForm': function closeConfigForm(ev) {
          return _this2.closeForm(ev);
        },
        'submitConfigForm': function submitConfigForm(ev) {
          return _this2.submitConfigForm(ev);
        }
      });
    }
  }, {
    key: "getConfig",
    value: function () {
      var _getConfig = config_form_asyncToGenerator( /*#__PURE__*/config_form_regeneratorRuntime().mark(function _callee() {
        var iq;
        return config_form_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return this.model.fetchRoomConfiguration();
            case 2:
              iq = _context.sent;
              this.model.session.set('config_stanza', iq.outerHTML);
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function getConfig() {
        return _getConfig.apply(this, arguments);
      }
      return getConfig;
    }()
  }, {
    key: "submitConfigForm",
    value: function () {
      var _submitConfigForm = config_form_asyncToGenerator( /*#__PURE__*/config_form_regeneratorRuntime().mark(function _callee2(ev) {
        var inputs, config_array, message;
        return config_form_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev.preventDefault();
              inputs = config_form_sizzle(':input:not([type=button]):not([type=submit])', ev.target);
              config_array = inputs.map(config_form_u.webForm2xForm).filter(function (f) {
                return f;
              });
              _context2.prev = 3;
              _context2.next = 6;
              return this.model.sendConfiguration(config_array);
            case 6:
              _context2.next = 13;
              break;
            case 8:
              _context2.prev = 8;
              _context2.t0 = _context2["catch"](3);
              log.error(_context2.t0);
              message = __("Sorry, an error occurred while trying to submit the config form.") + " " + __("Check your browser's developer console for details.");
              shared_api.alert('error', __('Error'), message);
            case 13:
              _context2.next = 15;
              return this.model.refreshDiscoInfo();
            case 15:
              this.closeForm();
            case 16:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this, [[3, 8]]);
      }));
      function submitConfigForm(_x) {
        return _submitConfigForm.apply(this, arguments);
      }
      return submitConfigForm;
    }()
  }, {
    key: "closeForm",
    value: function closeForm(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      this.model.session.set('view', null);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCConfigForm;
}(CustomElement);
shared_api.elements.define('converse-muc-config-form', MUCConfigForm);
/* harmony default export */ const config_form = ((/* unused pure expression or super */ null && (MUCConfigForm)));
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-destroyed.js
var muc_destroyed_templateObject, muc_destroyed_templateObject2, muc_destroyed_templateObject3;
function muc_destroyed_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var tplMoved = function tplMoved(o) {
  var i18n_moved = __('The conversation has moved to a new address. Click the link below to enter.');
  return (0,external_lit_namespaceObject.html)(muc_destroyed_templateObject || (muc_destroyed_templateObject = muc_destroyed_taggedTemplateLiteral(["\n        <p class=\"moved-label\">", "</p>\n        <p class=\"moved-link\">\n            <a class=\"switch-chat\" @click=", ">", "</a>\n        </p>"])), i18n_moved, function (ev) {
    return o.onSwitch(ev);
  }, o.moved_jid);
};
/* harmony default export */ const muc_destroyed = (function (o) {
  var i18n_non_existent = __('This groupchat no longer exists');
  var i18n_reason = __('The following reason was given: "%1$s"', o.reason || '');
  return (0,external_lit_namespaceObject.html)(muc_destroyed_templateObject2 || (muc_destroyed_templateObject2 = muc_destroyed_taggedTemplateLiteral(["\n        <div class=\"alert alert-danger\">\n            <h3 class=\"alert-heading disconnect-msg\">", "</h3>\n        </div>\n        ", "\n        ", "\n    "])), i18n_non_existent, o.reason ? (0,external_lit_namespaceObject.html)(muc_destroyed_templateObject3 || (muc_destroyed_templateObject3 = muc_destroyed_taggedTemplateLiteral(["<p class=\"destroyed-reason\">", "</p>"])), i18n_reason) : '', o.moved_jid ? tplMoved(o) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/destroyed.js
function destroyed_typeof(obj) {
  "@babel/helpers - typeof";

  return destroyed_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;
  }, destroyed_typeof(obj);
}
function destroyed_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  destroyed_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" == destroyed_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 destroyed_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 destroyed_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        destroyed_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        destroyed_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function destroyed_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function destroyed_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, destroyed_toPropertyKey(descriptor.key), descriptor);
  }
}
function destroyed_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) destroyed_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) destroyed_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function destroyed_toPropertyKey(arg) {
  var key = destroyed_toPrimitive(arg, "string");
  return destroyed_typeof(key) === "symbol" ? key : String(key);
}
function destroyed_toPrimitive(input, hint) {
  if (destroyed_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (destroyed_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function destroyed_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    destroyed_get = Reflect.get.bind();
  } else {
    destroyed_get = function _get(target, property, receiver) {
      var base = destroyed_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return destroyed_get.apply(this, arguments);
}
function destroyed_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = destroyed_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function destroyed_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) destroyed_setPrototypeOf(subClass, superClass);
}
function destroyed_setPrototypeOf(o, p) {
  destroyed_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return destroyed_setPrototypeOf(o, p);
}
function destroyed_createSuper(Derived) {
  var hasNativeReflectConstruct = destroyed_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = destroyed_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = destroyed_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return destroyed_possibleConstructorReturn(this, result);
  };
}
function destroyed_possibleConstructorReturn(self, call) {
  if (call && (destroyed_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 destroyed_assertThisInitialized(self);
}
function destroyed_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function destroyed_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 destroyed_getPrototypeOf(o) {
  destroyed_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return destroyed_getPrototypeOf(o);
}



var MUCDestroyed = /*#__PURE__*/function (_CustomElement) {
  destroyed_inherits(MUCDestroyed, _CustomElement);
  var _super = destroyed_createSuper(MUCDestroyed);
  function MUCDestroyed() {
    destroyed_classCallCheck(this, MUCDestroyed);
    return _super.apply(this, arguments);
  }
  destroyed_createClass(MUCDestroyed, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      destroyed_get(destroyed_getPrototypeOf(MUCDestroyed.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
    }
  }, {
    key: "render",
    value: function render() {
      var _this = this;
      var reason = this.model.get('destroyed_reason');
      var moved_jid = this.model.get('moved_jid');
      return muc_destroyed({
        moved_jid: moved_jid,
        reason: reason,
        'onSwitch': function onSwitch(ev) {
          return _this.onSwitch(ev);
        }
      });
    }
  }, {
    key: "onSwitch",
    value: function () {
      var _onSwitch = destroyed_asyncToGenerator( /*#__PURE__*/destroyed_regeneratorRuntime().mark(function _callee(ev) {
        var moved_jid, room;
        return destroyed_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev.preventDefault();
              moved_jid = this.model.get('moved_jid');
              _context.next = 4;
              return shared_api.rooms.get(moved_jid, {}, true);
            case 4:
              room = _context.sent;
              room.maybeShow(true);
              this.model.destroy();
            case 7:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function onSwitch(_x) {
        return _onSwitch.apply(this, arguments);
      }
      return onSwitch;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCDestroyed;
}(CustomElement);
shared_api.elements.define('converse-muc-destroyed', MUCDestroyed);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-disconnect.js
var muc_disconnect_templateObject, muc_disconnect_templateObject2;
function muc_disconnect_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const muc_disconnect = (function (messages) {
  return (0,external_lit_namespaceObject.html)(muc_disconnect_templateObject || (muc_disconnect_templateObject = muc_disconnect_taggedTemplateLiteral(["\n        <div class=\"alert alert-danger\">\n            <h3 class=\"alert-heading disconnect-msg\">", "</h3>\n            ", "\n        </div>"])), messages[0], messages.slice(1).map(function (m) {
    return (0,external_lit_namespaceObject.html)(muc_disconnect_templateObject2 || (muc_disconnect_templateObject2 = muc_disconnect_taggedTemplateLiteral(["<p class=\"disconnect-msg\">", "</p>"])), m);
  }));
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/disconnected.js
function disconnected_typeof(obj) {
  "@babel/helpers - typeof";

  return disconnected_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;
  }, disconnected_typeof(obj);
}
function disconnected_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function disconnected_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, disconnected_toPropertyKey(descriptor.key), descriptor);
  }
}
function disconnected_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) disconnected_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) disconnected_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function disconnected_toPropertyKey(arg) {
  var key = disconnected_toPrimitive(arg, "string");
  return disconnected_typeof(key) === "symbol" ? key : String(key);
}
function disconnected_toPrimitive(input, hint) {
  if (disconnected_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (disconnected_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function disconnected_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    disconnected_get = Reflect.get.bind();
  } else {
    disconnected_get = function _get(target, property, receiver) {
      var base = disconnected_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return disconnected_get.apply(this, arguments);
}
function disconnected_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = disconnected_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function disconnected_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) disconnected_setPrototypeOf(subClass, superClass);
}
function disconnected_setPrototypeOf(o, p) {
  disconnected_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return disconnected_setPrototypeOf(o, p);
}
function disconnected_createSuper(Derived) {
  var hasNativeReflectConstruct = disconnected_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = disconnected_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = disconnected_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return disconnected_possibleConstructorReturn(this, result);
  };
}
function disconnected_possibleConstructorReturn(self, call) {
  if (call && (disconnected_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 disconnected_assertThisInitialized(self);
}
function disconnected_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function disconnected_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 disconnected_getPrototypeOf(o) {
  disconnected_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return disconnected_getPrototypeOf(o);
}




var MUCDisconnected = /*#__PURE__*/function (_CustomElement) {
  disconnected_inherits(MUCDisconnected, _CustomElement);
  var _super = disconnected_createSuper(MUCDisconnected);
  function MUCDisconnected() {
    disconnected_classCallCheck(this, MUCDisconnected);
    return _super.apply(this, arguments);
  }
  disconnected_createClass(MUCDisconnected, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      disconnected_get(disconnected_getPrototypeOf(MUCDisconnected.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
    }
  }, {
    key: "render",
    value: function render() {
      var message = this.model.session.get('disconnection_message');
      if (!message) {
        return;
      }
      var messages = [message];
      var actor = this.model.session.get('disconnection_actor');
      if (actor) {
        messages.push(__('This action was done by %1$s.', actor));
      }
      var reason = this.model.session.get('disconnection_reason');
      if (reason) {
        messages.push(__('The reason given is: "%1$s".', reason));
      }
      return muc_disconnect(messages);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCDisconnected;
}(CustomElement);
shared_api.elements.define('converse-muc-disconnected', MUCDisconnected);
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/templates/muc-details.js
var muc_details_templateObject, muc_details_templateObject2, muc_details_templateObject3, muc_details_templateObject4, muc_details_templateObject5, muc_details_templateObject6, muc_details_templateObject7, muc_details_templateObject8, muc_details_templateObject9, muc_details_templateObject10, muc_details_templateObject11, muc_details_templateObject12, muc_details_templateObject13, muc_details_templateObject14, muc_details_templateObject15;
function muc_details_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


var subject = function subject(o) {
  var i18n_topic = __('Topic');
  var i18n_topic_author = __('Topic author');
  return (0,external_lit_namespaceObject.html)(muc_details_templateObject || (muc_details_templateObject = muc_details_taggedTemplateLiteral(["\n        <p class=\"room-info\"><strong>", "</strong>: <converse-rich-text text=", " render_styling></converse-rich-text></p>\n        <p class=\"room-info\"><strong>", "</strong>: ", "</p>\n    "])), i18n_topic, o.subject.text, i18n_topic_author, o.subject && o.subject.author);
};
/* harmony default export */ const muc_details = (function (model) {
  var o = model.toJSON();
  var config = model.config.toJSON();
  var features = model.features.toJSON();
  var num_occupants = model.occupants.filter(function (o) {
    return o.get('show') !== 'offline';
  }).length;
  var i18n_address = __('XMPP address');
  var i18n_archiving = __('Message archiving');
  var i18n_archiving_help = __('Messages are archived on the server');
  var i18n_desc = __('Description');
  var i18n_features = __('Features');
  var i18n_hidden = __('Hidden');
  var i18n_hidden_help = __('This groupchat is not publicly searchable');
  var i18n_members_help = __('This groupchat is restricted to members only');
  var i18n_members_only = __('Members only');
  var i18n_moderated = __('Moderated');
  var i18n_moderated_help = __('Participants entering this groupchat need to request permission to write');
  var i18n_name = __('Name');
  var i18n_no_pass_help = __('This groupchat does not require a password upon entry');
  var i18n_no_password_required = __('No password required');
  var i18n_not_anonymous = __('Not anonymous');
  var i18n_not_anonymous_help = __('All other groupchat participants can see your XMPP address');
  var i18n_not_moderated = __('Not moderated');
  var i18n_not_moderated_help = __('Participants entering this groupchat can write right away');
  var i18n_online_users = __('Online users');
  var i18n_open = __('Open');
  var i18n_open_help = __('Anyone can join this groupchat');
  var i18n_password_help = __('This groupchat requires a password before entry');
  var i18n_password_protected = __('Password protected');
  var i18n_persistent = __('Persistent');
  var i18n_persistent_help = __('This groupchat persists even if it\'s unoccupied');
  var i18n_public = __('Public');
  var i18n_semi_anon = __('Semi-anonymous');
  var i18n_semi_anon_help = __('Only moderators can see your XMPP address');
  var i18n_temporary = __('Temporary');
  var i18n_temporary_help = __('This groupchat will disappear once the last person leaves');
  return (0,external_lit_namespaceObject.html)(muc_details_templateObject2 || (muc_details_templateObject2 = muc_details_taggedTemplateLiteral(["\n        <div class=\"room-info\">\n            <p class=\"room-info\"><strong>", "</strong>: ", "</p>\n            <p class=\"room-info\"><strong>", "</strong>: <converse-rich-text text=\"xmpp:", "?join\"></converse-rich-text></p>\n            <p class=\"room-info\"><strong>", "</strong>: <converse-rich-text text=\"", "\" render_styling></converse-rich-text></p>\n            ", "\n            <p class=\"room-info\"><strong>", "</strong>: ", "</p>\n            <p class=\"room-info\"><strong>", "</strong>:\n                <div class=\"chatroom-features\">\n                <ul class=\"features-list\">\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                    ", "\n                </ul>\n                </div>\n            </p>\n    "])), i18n_name, o.name, i18n_address, o.jid, i18n_desc, config.description, o.subject ? subject(o) : '', i18n_online_users, num_occupants, i18n_features, features.passwordprotected ? (0,external_lit_namespaceObject.html)(muc_details_templateObject3 || (muc_details_templateObject3 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-lock\"></converse-icon>", " - <em>", "</em></li>"])), i18n_password_protected, i18n_password_help) : '', features.unsecured ? (0,external_lit_namespaceObject.html)(muc_details_templateObject4 || (muc_details_templateObject4 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-unlock\"></converse-icon>", " - <em>", "</em></li>"])), i18n_no_password_required, i18n_no_pass_help) : '', features.hidden ? (0,external_lit_namespaceObject.html)(muc_details_templateObject5 || (muc_details_templateObject5 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-eye-slash\"></converse-icon>", " - <em>", "</em></li>"])), i18n_hidden, i18n_hidden_help) : '', features.public_room ? (0,external_lit_namespaceObject.html)(muc_details_templateObject6 || (muc_details_templateObject6 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-eye\"></converse-icon>", " - <em>", "</em></li>"])), i18n_public, o.__('This groupchat is publicly searchable')) : '', features.membersonly ? (0,external_lit_namespaceObject.html)(muc_details_templateObject7 || (muc_details_templateObject7 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-address-book\"></converse-icon>", " - <em>", "</em></li>"])), i18n_members_only, i18n_members_help) : '', features.open ? (0,external_lit_namespaceObject.html)(muc_details_templateObject8 || (muc_details_templateObject8 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-globe\"></converse-icon>", " - <em>", "</em></li>"])), i18n_open, i18n_open_help) : '', features.persistent ? (0,external_lit_namespaceObject.html)(muc_details_templateObject9 || (muc_details_templateObject9 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-save\"></converse-icon>", " - <em>", "</em></li>"])), i18n_persistent, i18n_persistent_help) : '', features.temporary ? (0,external_lit_namespaceObject.html)(muc_details_templateObject10 || (muc_details_templateObject10 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-snowflake\"></converse-icon>", " - <em>", "</em></li>"])), i18n_temporary, i18n_temporary_help) : '', features.nonanonymous ? (0,external_lit_namespaceObject.html)(muc_details_templateObject11 || (muc_details_templateObject11 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-id-card\"></converse-icon>", " - <em>", "</em></li>"])), i18n_not_anonymous, i18n_not_anonymous_help) : '', features.semianonymous ? (0,external_lit_namespaceObject.html)(muc_details_templateObject12 || (muc_details_templateObject12 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-user-secret\"></converse-icon>", " - <em>", "</em></li>"])), i18n_semi_anon, i18n_semi_anon_help) : '', features.moderated ? (0,external_lit_namespaceObject.html)(muc_details_templateObject13 || (muc_details_templateObject13 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-gavel\"></converse-icon>", " - <em>", "</em></li>"])), i18n_moderated, i18n_moderated_help) : '', features.unmoderated ? (0,external_lit_namespaceObject.html)(muc_details_templateObject14 || (muc_details_templateObject14 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-info-circle\"></converse-icon>", " - <em>", "</em></li>"])), i18n_not_moderated, i18n_not_moderated_help) : '', features.mam_enabled ? (0,external_lit_namespaceObject.html)(muc_details_templateObject15 || (muc_details_templateObject15 = muc_details_taggedTemplateLiteral(["<li class=\"feature\" ><converse-icon size=\"1em\" class=\"fa fa-database\"></converse-icon>", " - <em>", "</em></li>"])), i18n_archiving, i18n_archiving_help) : '');
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/muc-details-modal.scss
var muc_details_modal = __webpack_require__(9866);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/muc-details-modal.scss

      
      
      
      
      
      
      
      
      

var muc_details_modal_options = {};

muc_details_modal_options.styleTagTransform = (styleTagTransform_default());
muc_details_modal_options.setAttributes = (setAttributesWithoutAttributes_default());

      muc_details_modal_options.insert = insertBySelector_default().bind(null, "head");
    
muc_details_modal_options.domAPI = (styleDomAPI_default());
muc_details_modal_options.insertStyleElement = (insertStyleElement_default());

var muc_details_modal_update = injectStylesIntoStyleTag_default()(muc_details_modal/* default */.Z, muc_details_modal_options);




       /* harmony default export */ const styles_muc_details_modal = (muc_details_modal/* default */.Z && muc_details_modal/* default */.Z.locals ? muc_details_modal/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/muc-details.js
function muc_details_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_details_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;
  }, muc_details_typeof(obj);
}
function muc_details_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_details_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, muc_details_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_details_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_details_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_details_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_details_toPropertyKey(arg) {
  var key = muc_details_toPrimitive(arg, "string");
  return muc_details_typeof(key) === "symbol" ? key : String(key);
}
function muc_details_toPrimitive(input, hint) {
  if (muc_details_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_details_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_details_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    muc_details_get = Reflect.get.bind();
  } else {
    muc_details_get = function _get(target, property, receiver) {
      var base = muc_details_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return muc_details_get.apply(this, arguments);
}
function muc_details_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = muc_details_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function muc_details_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) muc_details_setPrototypeOf(subClass, superClass);
}
function muc_details_setPrototypeOf(o, p) {
  muc_details_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_details_setPrototypeOf(o, p);
}
function muc_details_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_details_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_details_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_details_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_details_possibleConstructorReturn(this, result);
  };
}
function muc_details_possibleConstructorReturn(self, call) {
  if (call && (muc_details_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 muc_details_assertThisInitialized(self);
}
function muc_details_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_details_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 muc_details_getPrototypeOf(o) {
  muc_details_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_details_getPrototypeOf(o);
}





var MUCDetailsModal = /*#__PURE__*/function (_BaseModal) {
  muc_details_inherits(MUCDetailsModal, _BaseModal);
  var _super = muc_details_createSuper(MUCDetailsModal);
  function MUCDetailsModal() {
    muc_details_classCallCheck(this, MUCDetailsModal);
    return _super.apply(this, arguments);
  }
  muc_details_createClass(MUCDetailsModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      muc_details_get(muc_details_getPrototypeOf(MUCDetailsModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', function () {
        return _this.render();
      });
      this.listenTo(this.model.features, 'change', function () {
        return _this.render();
      });
      this.listenTo(this.model.occupants, 'add', function () {
        return _this.render();
      });
      this.listenTo(this.model.occupants, 'change', function () {
        return _this.render();
      });
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return muc_details(this.model);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Groupchat info for %1$s', this.model.getDisplayName());
    }
  }]);
  return MUCDetailsModal;
}(modal_modal);

shared_api.elements.define('converse-muc-details-modal', MUCDetailsModal);
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/templates/muc-invite.js
var muc_invite_templateObject, muc_invite_templateObject2;
function muc_invite_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const muc_invite = (function (el) {
  var i18n_invite = __('Invite');
  var i18n_jid_placeholder = __('user@example.org');
  var i18n_error_message = __('Please enter a valid XMPP address');
  var i18n_invite_label = __('XMPP Address');
  var i18n_reason = __('Optional reason for the invitation');
  return (0,external_lit_namespaceObject.html)(muc_invite_templateObject || (muc_invite_templateObject = muc_invite_taggedTemplateLiteral(["\n        <form class=\"converse-form\" @submit=", ">\n            <div class=\"form-group\">\n                <label class=\"clearfix\" for=\"invitee_jids\">", ":</label>\n                ", "\n                <converse-autocomplete\n                    .getAutoCompleteList=", "\n                    ?autofocus=", "\n                    min_chars=\"1\"\n                    position=\"below\"\n                    required=\"required\"\n                    name=\"invitee_jids\"\n                    id=\"invitee_jids\"\n                    placeholder=\"", "\">\n                </converse-autocomplete>\n            </div>\n            <div class=\"form-group\">\n                <label>", ":</label>\n                <textarea class=\"form-control\" name=\"reason\"></textarea>\n            </div>\n            <div class=\"form-group\">\n                <input type=\"submit\" class=\"btn btn-primary\" value=\"", "\"/>\n            </div>\n        </form>\n    "])), function (ev) {
    return el.submitInviteForm(ev);
  }, i18n_invite_label, el.model.get('invalid_invite_jid') ? (0,external_lit_namespaceObject.html)(muc_invite_templateObject2 || (muc_invite_templateObject2 = muc_invite_taggedTemplateLiteral(["<div class=\"error error-feedback\">", "</div>"])), i18n_error_message) : '', function () {
    return el.getAutoCompleteList();
  }, true, i18n_jid_placeholder, i18n_reason, i18n_invite);
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/muc-invite.js
function muc_invite_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_invite_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;
  }, muc_invite_typeof(obj);
}
function muc_invite_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_invite_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, muc_invite_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_invite_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_invite_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_invite_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_invite_toPropertyKey(arg) {
  var key = muc_invite_toPrimitive(arg, "string");
  return muc_invite_typeof(key) === "symbol" ? key : String(key);
}
function muc_invite_toPrimitive(input, hint) {
  if (muc_invite_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_invite_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_invite_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    muc_invite_get = Reflect.get.bind();
  } else {
    muc_invite_get = function _get(target, property, receiver) {
      var base = muc_invite_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return muc_invite_get.apply(this, arguments);
}
function muc_invite_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = muc_invite_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function muc_invite_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) muc_invite_setPrototypeOf(subClass, superClass);
}
function muc_invite_setPrototypeOf(o, p) {
  muc_invite_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_invite_setPrototypeOf(o, p);
}
function muc_invite_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_invite_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_invite_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_invite_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_invite_possibleConstructorReturn(this, result);
  };
}
function muc_invite_possibleConstructorReturn(self, call) {
  if (call && (muc_invite_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 muc_invite_assertThisInitialized(self);
}
function muc_invite_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_invite_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 muc_invite_getPrototypeOf(o) {
  muc_invite_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_invite_getPrototypeOf(o);
}





var muc_invite_u = public_converse.env.utils;
var MUCInviteModal = /*#__PURE__*/function (_BaseModal) {
  muc_invite_inherits(MUCInviteModal, _BaseModal);
  var _super = muc_invite_createSuper(MUCInviteModal);
  function MUCInviteModal() {
    muc_invite_classCallCheck(this, MUCInviteModal);
    return _super.apply(this, arguments);
  }
  muc_invite_createClass(MUCInviteModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      muc_invite_get(muc_invite_getPrototypeOf(MUCInviteModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', function () {
        return _this.render();
      });
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return muc_invite(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Invite someone to this groupchat');
    }
  }, {
    key: "getAutoCompleteList",
    value: function getAutoCompleteList() {
      // eslint-disable-line class-methods-use-this
      return shared_converse.roster.map(function (i) {
        return {
          'label': i.getDisplayName(),
          'value': i.get('jid')
        };
      });
    }
  }, {
    key: "submitInviteForm",
    value: function submitInviteForm(ev) {
      var _data$get;
      ev.preventDefault();
      // TODO: Add support for sending an invite to multiple JIDs
      var data = new FormData(ev.target);
      var jid = (_data$get = data.get('invitee_jids')) === null || _data$get === void 0 ? void 0 : _data$get.trim();
      var reason = data.get('reason');
      if (muc_invite_u.isValidJID(jid)) {
        // TODO: Create and use API here
        this.chatroomview.model.directInvite(jid, reason);
        this.modal.hide();
      } else {
        this.model.set({
          'invalid_invite_jid': true
        });
      }
    }
  }]);
  return MUCInviteModal;
}(modal_modal);

shared_api.elements.define('converse-muc-invite-modal', MUCInviteModal);
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/nickname.js
function nickname_typeof(obj) {
  "@babel/helpers - typeof";

  return nickname_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;
  }, nickname_typeof(obj);
}
var nickname_templateObject;
function nickname_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function nickname_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function nickname_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, nickname_toPropertyKey(descriptor.key), descriptor);
  }
}
function nickname_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) nickname_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) nickname_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function nickname_toPropertyKey(arg) {
  var key = nickname_toPrimitive(arg, "string");
  return nickname_typeof(key) === "symbol" ? key : String(key);
}
function nickname_toPrimitive(input, hint) {
  if (nickname_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (nickname_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function nickname_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) nickname_setPrototypeOf(subClass, superClass);
}
function nickname_setPrototypeOf(o, p) {
  nickname_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return nickname_setPrototypeOf(o, p);
}
function nickname_createSuper(Derived) {
  var hasNativeReflectConstruct = nickname_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = nickname_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = nickname_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return nickname_possibleConstructorReturn(this, result);
  };
}
function nickname_possibleConstructorReturn(self, call) {
  if (call && (nickname_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 nickname_assertThisInitialized(self);
}
function nickname_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function nickname_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 nickname_getPrototypeOf(o) {
  nickname_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return nickname_getPrototypeOf(o);
}




var MUCNicknameModal = /*#__PURE__*/function (_BaseModal) {
  nickname_inherits(MUCNicknameModal, _BaseModal);
  var _super = nickname_createSuper(MUCNicknameModal);
  function MUCNicknameModal() {
    nickname_classCallCheck(this, MUCNicknameModal);
    return _super.apply(this, arguments);
  }
  nickname_createClass(MUCNicknameModal, [{
    key: "renderModal",
    value: function renderModal() {
      return (0,external_lit_namespaceObject.html)(nickname_templateObject || (nickname_templateObject = nickname_taggedTemplateLiteral(["<converse-muc-nickname-form jid=\"", "\"></converse-muc-nickname-form>"])), this.model.get('jid'));
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Change your nickname');
    }
  }]);
  return MUCNicknameModal;
}(modal_modal);

shared_api.elements.define('converse-muc-nickname-modal', MUCNicknameModal);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/shared/components/styles/rich-text.scss
var styles_rich_text = __webpack_require__(9320);
;// CONCATENATED MODULE: ./src/shared/components/styles/rich-text.scss

      
      
      
      
      
      
      
      
      

var rich_text_options = {};

rich_text_options.styleTagTransform = (styleTagTransform_default());
rich_text_options.setAttributes = (setAttributesWithoutAttributes_default());

      rich_text_options.insert = insertBySelector_default().bind(null, "head");
    
rich_text_options.domAPI = (styleDomAPI_default());
rich_text_options.insertStyleElement = (insertStyleElement_default());

var rich_text_update = injectStylesIntoStyleTag_default()(styles_rich_text/* default */.Z, rich_text_options);




       /* harmony default export */ const components_styles_rich_text = (styles_rich_text/* default */.Z && styles_rich_text/* default */.Z.locals ? styles_rich_text/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/shared/components/rich-text.js
function components_rich_text_typeof(obj) {
  "@babel/helpers - typeof";

  return components_rich_text_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;
  }, components_rich_text_typeof(obj);
}
function components_rich_text_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function components_rich_text_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, components_rich_text_toPropertyKey(descriptor.key), descriptor);
  }
}
function components_rich_text_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) components_rich_text_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) components_rich_text_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function components_rich_text_toPropertyKey(arg) {
  var key = components_rich_text_toPrimitive(arg, "string");
  return components_rich_text_typeof(key) === "symbol" ? key : String(key);
}
function components_rich_text_toPrimitive(input, hint) {
  if (components_rich_text_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (components_rich_text_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function components_rich_text_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) components_rich_text_setPrototypeOf(subClass, superClass);
}
function components_rich_text_setPrototypeOf(o, p) {
  components_rich_text_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return components_rich_text_setPrototypeOf(o, p);
}
function components_rich_text_createSuper(Derived) {
  var hasNativeReflectConstruct = components_rich_text_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = components_rich_text_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = components_rich_text_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return components_rich_text_possibleConstructorReturn(this, result);
  };
}
function components_rich_text_possibleConstructorReturn(self, call) {
  if (call && (components_rich_text_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 components_rich_text_assertThisInitialized(self);
}
function components_rich_text_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function components_rich_text_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 components_rich_text_getPrototypeOf(o) {
  components_rich_text_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return components_rich_text_getPrototypeOf(o);
}





/**
 * The RichText custom element allows you to parse transform text into rich DOM elements.
 * @example <converse-rich-text text="*_hello_ world!*"></converse-rich-text>
 */
var rich_text_RichText = /*#__PURE__*/function (_CustomElement) {
  components_rich_text_inherits(RichText, _CustomElement);
  var _super = components_rich_text_createSuper(RichText);
  function RichText() {
    var _this;
    components_rich_text_classCallCheck(this, RichText);
    _this = _super.call(this);
    _this.embed_audio = false;
    _this.embed_videos = false;
    _this.hide_media_urls = false;
    _this.mentions = [];
    _this.offset = 0;
    _this.render_styling = false;
    _this.show_image_urls = true;
    _this.show_images = false;
    _this.show_me_message = false;
    return _this;
  }
  components_rich_text_createClass(RichText, [{
    key: "render",
    value: function render() {
      var options = {
        embed_audio: this.embed_audio,
        embed_videos: this.embed_videos,
        hide_media_urls: this.hide_media_urls,
        mentions: this.mentions,
        nick: this.nick,
        onImgClick: this.onImgClick,
        onImgLoad: this.onImgLoad,
        render_styling: this.render_styling,
        show_images: this.show_images,
        show_me_message: this.show_me_message
      };
      return rich_text(this.text, this.offset, options);
    }
  }], [{
    key: "properties",
    get: function get() {
      /**
       * @typedef { Object } RichTextComponentProperties
       * @property { Boolean } embed_audio
       *  Whether URLs that point to audio files should render as audio players.
       * @property { Boolean } embed_videos
       *  Whether URLs that point to video files should render as video players.
       * @property { Array } mentions - An array of objects representing chat mentions
       * @property { String } nick - The current user's nickname, relevant for mentions
       * @property { Number } offset - The text offset, in case this is a nested RichText element.
       * @property { Function } onImgClick
       * @property { Function } onImgLoad
       * @property { Boolean } render_styling
       *  Whether XEP-0393 message styling hints should be rendered
       * @property { Boolean } show_images
       *  Whether URLs that point to image files should render as images
       * @property { Boolean } hide_media_urls
       *  If media URLs are rendered as media, then this option determines
       *  whether the original URL is also still shown or not.
       *  Only relevant in conjunction with `show_images`, `embed_audio` and `embed_videos`.
       * @property { Boolean } show_me_message
       *  Whether text that starts with /me should be rendered in the 3rd person.
       * @property { String } text - The text that will get transformed.
       */
      return {
        embed_audio: {
          type: Boolean
        },
        embed_videos: {
          type: Boolean
        },
        mentions: {
          type: Array
        },
        nick: {
          type: String
        },
        offset: {
          type: Number
        },
        onImgClick: {
          type: Function
        },
        onImgLoad: {
          type: Function
        },
        render_styling: {
          type: Boolean
        },
        show_images: {
          type: Boolean
        },
        hide_media_urls: {
          type: Boolean
        },
        show_me_message: {
          type: Boolean
        },
        text: {
          type: String
        }
      };
    }
  }]);
  return RichText;
}(CustomElement);

shared_api.elements.define('converse-rich-text', rich_text_RichText);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-head.js
var muc_head_templateObject, muc_head_templateObject2, muc_head_templateObject3, muc_head_templateObject4, muc_head_templateObject5;
function muc_head_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}







/* harmony default export */ const muc_head = (function (el) {
  var _el$user_settings, _el$user_settings$get, _el$model$vcard, _el$model$vcard2, _el$model$vcard3;
  var o = el.model.toJSON();
  var subject_hidden = (_el$user_settings = el.user_settings) === null || _el$user_settings === void 0 ? void 0 : (_el$user_settings$get = _el$user_settings.get('mucs_with_hidden_subject', [])) === null || _el$user_settings$get === void 0 ? void 0 : _el$user_settings$get.includes(el.model.get('jid'));
  var heading_buttons_promise = el.getHeadingButtons(subject_hidden);
  var i18n_hide_topic = __('Hide the groupchat topic');
  var i18n_bookmarked = __('This groupchat is bookmarked');
  var subject = o.subject ? o.subject.text : '';
  var show_subject = subject && !subject_hidden;
  var muc_vcard = (_el$model$vcard = el.model.vcard) === null || _el$model$vcard === void 0 ? void 0 : _el$model$vcard.get('image');
  return (0,external_lit_namespaceObject.html)(muc_head_templateObject || (muc_head_templateObject = muc_head_taggedTemplateLiteral(["\n        <div class=\"chatbox-title ", "\">\n\n            ", "\n\n            <div class=\"chatbox-title--row\">\n                ", "\n                <div class=\"chatbox-title__text\" title=\"", "\">", "\n                ", "\n                </div>\n            </div>\n            <div class=\"chatbox-title__buttons row no-gutters\">\n                ", "\n                ", "\n            </div>\n        </div>\n        ", "\n    "])), show_subject ? '' : "chatbox-title--no-desc", muc_vcard && muc_vcard !== shared_converse.DEFAULT_IMAGE ? (0,external_lit_namespaceObject.html)(muc_head_templateObject2 || (muc_head_templateObject2 = muc_head_taggedTemplateLiteral(["\n                <converse-avatar class=\"avatar align-self-center\"\n                    .data=", "\n                    nonce=", "\n                    height=\"40\" width=\"40\"></converse-avatar>"])), (_el$model$vcard2 = el.model.vcard) === null || _el$model$vcard2 === void 0 ? void 0 : _el$model$vcard2.attributes, (_el$model$vcard3 = el.model.vcard) === null || _el$model$vcard3 === void 0 ? void 0 : _el$model$vcard3.get('vcard_updated')) : '', !shared_converse.api.settings.get("singleton") ? (0,external_lit_namespaceObject.html)(muc_head_templateObject3 || (muc_head_templateObject3 = muc_head_taggedTemplateLiteral(["<converse-controlbox-navback jid=\"", "\"></converse-controlbox-navback>"])), o.jid) : '', shared_api.settings.get('locked_muc_domain') !== 'hidden' ? o.jid : '', el.model.getDisplayName(), o.bookmarked ? (0,external_lit_namespaceObject.html)(muc_head_templateObject4 || (muc_head_templateObject4 = muc_head_taggedTemplateLiteral(["<converse-icon\n                            class=\"fa fa-bookmark chatbox-title__text--bookmarked\"\n                            size=\"1em\"\n                            color=\"var(--chatroom-head-color)\"\n                            title=\"", "\">\n                        </converse-icon>"])), i18n_bookmarked) : '', until_m(getStandaloneButtons(heading_buttons_promise), ''), until_m(getDropdownButtons(heading_buttons_promise), ''), show_subject ? (0,external_lit_namespaceObject.html)(muc_head_templateObject5 || (muc_head_templateObject5 = muc_head_taggedTemplateLiteral(["<p class=\"chat-head__desc\" title=\"", "\">\n            <converse-rich-text text=", " render_styling></converse-rich-text>\n          </p>"])), i18n_hide_topic, subject) : '');
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/muc-head.scss
var styles_muc_head = __webpack_require__(4186);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/muc-head.scss

      
      
      
      
      
      
      
      
      

var muc_head_options = {};

muc_head_options.styleTagTransform = (styleTagTransform_default());
muc_head_options.setAttributes = (setAttributesWithoutAttributes_default());

      muc_head_options.insert = insertBySelector_default().bind(null, "head");
    
muc_head_options.domAPI = (styleDomAPI_default());
muc_head_options.insertStyleElement = (insertStyleElement_default());

var muc_head_update = injectStylesIntoStyleTag_default()(styles_muc_head/* default */.Z, muc_head_options);




       /* harmony default export */ const muc_views_styles_muc_head = (styles_muc_head/* default */.Z && styles_muc_head/* default */.Z.locals ? styles_muc_head/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/heading.js
function muc_views_heading_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_heading_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;
  }, muc_views_heading_typeof(obj);
}
function muc_views_heading_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_heading_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" == muc_views_heading_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 muc_views_heading_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 muc_views_heading_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_heading_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_heading_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function muc_views_heading_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_views_heading_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, muc_views_heading_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_views_heading_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_views_heading_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_views_heading_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_views_heading_toPropertyKey(arg) {
  var key = muc_views_heading_toPrimitive(arg, "string");
  return muc_views_heading_typeof(key) === "symbol" ? key : String(key);
}
function muc_views_heading_toPrimitive(input, hint) {
  if (muc_views_heading_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_views_heading_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_views_heading_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) muc_views_heading_setPrototypeOf(subClass, superClass);
}
function muc_views_heading_setPrototypeOf(o, p) {
  muc_views_heading_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_views_heading_setPrototypeOf(o, p);
}
function muc_views_heading_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_views_heading_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_views_heading_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_views_heading_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_views_heading_possibleConstructorReturn(this, result);
  };
}
function muc_views_heading_possibleConstructorReturn(self, call) {
  if (call && (muc_views_heading_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 muc_views_heading_assertThisInitialized(self);
}
function muc_views_heading_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_views_heading_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 muc_views_heading_getPrototypeOf(o) {
  muc_views_heading_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_views_heading_getPrototypeOf(o);
}










var MUCHeading = /*#__PURE__*/function (_CustomElement) {
  muc_views_heading_inherits(MUCHeading, _CustomElement);
  var _super = muc_views_heading_createSuper(MUCHeading);
  function MUCHeading() {
    muc_views_heading_classCallCheck(this, MUCHeading);
    return _super.apply(this, arguments);
  }
  muc_views_heading_createClass(MUCHeading, [{
    key: "initialize",
    value: function () {
      var _initialize = muc_views_heading_asyncToGenerator( /*#__PURE__*/muc_views_heading_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return muc_views_heading_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.model = shared_converse.chatboxes.get(this.getAttribute('jid'));
              this.listenTo(this.model, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'vcard:add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'vcard:change', function () {
                return _this.requestUpdate();
              });
              _context.next = 6;
              return shared_converse.api.user.settings.getModel();
            case 6:
              this.user_settings = _context.sent;
              this.listenTo(this.user_settings, 'change:mucs_with_hidden_subject', function () {
                return _this.requestUpdate();
              });
              _context.next = 10;
              return this.model.initialized;
            case 10:
              this.listenTo(this.model.features, 'change:open', function () {
                return _this.requestUpdate();
              });
              this.model.occupants.forEach(function (o) {
                return _this.onOccupantAdded(o);
              });
              this.listenTo(this.model.occupants, 'add', this.onOccupantAdded);
              this.listenTo(this.model.occupants, 'change:affiliation', this.onOccupantAffiliationChanged);
              this.requestUpdate();
            case 15:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return this.model && this.user_settings ? muc_head(this) : '';
    }
  }, {
    key: "onOccupantAdded",
    value: function onOccupantAdded(occupant) {
      if (occupant.get('jid') === shared_converse.bare_jid) {
        this.requestUpdate();
      }
    }
  }, {
    key: "onOccupantAffiliationChanged",
    value: function onOccupantAffiliationChanged(occupant) {
      if (occupant.get('jid') === shared_converse.bare_jid) {
        this.requestUpdate();
      }
    }
  }, {
    key: "showRoomDetailsModal",
    value: function showRoomDetailsModal(ev) {
      ev.preventDefault();
      shared_api.modal.show('converse-muc-details-modal', {
        'model': this.model
      }, ev);
    }
  }, {
    key: "showInviteModal",
    value: function showInviteModal(ev) {
      ev.preventDefault();
      shared_api.modal.show('converse-muc-invite-modal', {
        'model': new Model(),
        'chatroomview': this
      }, ev);
    }
  }, {
    key: "toggleTopic",
    value: function toggleTopic(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      this.model.toggleSubjectHiddenState();
    }
  }, {
    key: "getAndRenderConfigurationForm",
    value: function getAndRenderConfigurationForm() {
      this.model.session.set('view', public_converse.MUC.VIEWS.CONFIG);
    }
  }, {
    key: "close",
    value: function close(ev) {
      ev.preventDefault();
      this.model.close();
    }
  }, {
    key: "destroy",
    value: function destroy(ev) {
      ev.preventDefault();
      destroyMUC(this.model);
    }

    /**
     * Returns a list of objects which represent buttons for the groupchat header.
     * @emits _converse#getHeadingButtons
     */
  }, {
    key: "getHeadingButtons",
    value: function getHeadingButtons(subject_hidden) {
      var _this2 = this;
      var buttons = [];
      buttons.push({
        'i18n_text': __('Details'),
        'i18n_title': __('Show more information about this groupchat'),
        'handler': function handler(ev) {
          return _this2.showRoomDetailsModal(ev);
        },
        'a_class': 'show-muc-details-modal',
        'icon_class': 'fa-info-circle',
        'name': 'details'
      });
      if (this.model.getOwnAffiliation() === 'owner') {
        buttons.push({
          'i18n_text': __('Configure'),
          'i18n_title': __('Configure this groupchat'),
          'handler': function handler() {
            return _this2.getAndRenderConfigurationForm();
          },
          'a_class': 'configure-chatroom-button',
          'icon_class': 'fa-wrench',
          'name': 'configure'
        });
      }
      buttons.push({
        'i18n_text': __('Nickname'),
        'i18n_title': __("Change the nickname you're using in this groupchat"),
        'handler': function handler(ev) {
          return shared_api.modal.show('converse-muc-nickname-modal', {
            'model': _this2.model
          }, ev);
        },
        'a_class': 'open-nickname-modal',
        'icon_class': 'fa-smile',
        'name': 'nickname'
      });
      if (this.model.invitesAllowed()) {
        buttons.push({
          'i18n_text': __('Invite'),
          'i18n_title': __('Invite someone to join this groupchat'),
          'handler': function handler(ev) {
            return _this2.showInviteModal(ev);
          },
          'a_class': 'open-invite-modal',
          'icon_class': 'fa-user-plus',
          'name': 'invite'
        });
      }
      var subject = this.model.get('subject');
      if (subject && subject.text) {
        buttons.push({
          'i18n_text': subject_hidden ? __('Show topic') : __('Hide topic'),
          'i18n_title': subject_hidden ? __('Show the topic message in the heading') : __('Hide the topic in the heading'),
          'handler': function handler(ev) {
            return _this2.toggleTopic(ev);
          },
          'a_class': 'hide-topic',
          'icon_class': 'fa-minus-square',
          'name': 'toggle-topic'
        });
      }
      var conn_status = this.model.session.get('connection_status');
      if (conn_status === public_converse.ROOMSTATUS.ENTERED) {
        var allowed_commands = this.model.getAllowedCommands();
        if (allowed_commands.includes('modtools')) {
          buttons.push({
            'i18n_text': __('Moderate'),
            'i18n_title': __('Moderate this groupchat'),
            'handler': function handler() {
              return showModeratorToolsModal(_this2.model);
            },
            'a_class': 'moderate-chatroom-button',
            'icon_class': 'fa-user-cog',
            'name': 'moderate'
          });
        }
        if (allowed_commands.includes('destroy')) {
          buttons.push({
            'i18n_text': __('Destroy'),
            'i18n_title': __('Remove this groupchat'),
            'handler': function handler(ev) {
              return _this2.destroy(ev);
            },
            'a_class': 'destroy-chatroom-button',
            'icon_class': 'fa-trash',
            'name': 'destroy'
          });
        }
      }
      if (!shared_api.settings.get('singleton')) {
        buttons.push({
          'i18n_text': __('Leave'),
          'i18n_title': __('Leave and close this groupchat'),
          'handler': function () {
            var _handler = muc_views_heading_asyncToGenerator( /*#__PURE__*/muc_views_heading_regeneratorRuntime().mark(function _callee2(ev) {
              var messages, result;
              return muc_views_heading_regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) switch (_context2.prev = _context2.next) {
                  case 0:
                    ev.stopPropagation();
                    messages = [__('Are you sure you want to leave this groupchat?')];
                    _context2.next = 4;
                    return shared_api.confirm(__('Confirm'), messages);
                  case 4:
                    result = _context2.sent;
                    result && _this2.close(ev);
                  case 6:
                  case "end":
                    return _context2.stop();
                }
              }, _callee2);
            }));
            function handler(_x) {
              return _handler.apply(this, arguments);
            }
            return handler;
          }(),
          'a_class': 'close-chatbox-button',
          'standalone': shared_api.settings.get('view_mode') === 'overlayed',
          'icon_class': 'fa-sign-out-alt',
          'name': 'signout'
        });
      }
      var el = shared_converse.chatboxviews.get(this.getAttribute('jid'));
      if (el) {
        // This hook is described in src/plugins/chatview/heading.js
        return shared_converse.api.hook('getHeadingButtons', el, buttons);
      } else {
        return Promise.resolve(buttons); // Happens during tests
      }
    }
  }]);

  return MUCHeading;
}(CustomElement);

shared_api.elements.define('converse-muc-heading', MUCHeading);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-password-form.js
var muc_password_form_templateObject;
function muc_password_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const muc_password_form = (function (o) {
  var i18n_heading = __('This groupchat requires a password');
  var i18n_password = __('Password: ');
  var i18n_submit = __('Submit');
  return (0,external_lit_namespaceObject.html)(muc_password_form_templateObject || (muc_password_form_templateObject = muc_password_form_taggedTemplateLiteral(["\n        <form class=\"converse-form chatroom-form converse-centered-form\" @submit=", ">\n            <fieldset class=\"form-group\">\n                <label>", "</label>\n                <p class=\"validation-message\">", "</p>\n                <input class=\"hidden-username\" type=\"text\" autocomplete=\"username\" value=\"", "\"></input>\n                <input type=\"password\"\n                    name=\"password\"\n                    required=\"required\"\n                    class=\"form-control ", "\"\n                    placeholder=\"", "\"/>\n            </fieldset>\n            <fieldset class=\"form-group\">\n                <input class=\"btn btn-primary\" type=\"submit\" value=\"", "\"/>\n            </fieldset>\n        </form>\n    "])), o.submitPassword, i18n_heading, o.validation_message, o.jid, o.validation_message ? 'error' : '', i18n_password, i18n_submit);
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/password-form.js
function password_form_typeof(obj) {
  "@babel/helpers - typeof";

  return password_form_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;
  }, password_form_typeof(obj);
}
function password_form_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function password_form_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, password_form_toPropertyKey(descriptor.key), descriptor);
  }
}
function password_form_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) password_form_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) password_form_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function password_form_toPropertyKey(arg) {
  var key = password_form_toPrimitive(arg, "string");
  return password_form_typeof(key) === "symbol" ? key : String(key);
}
function password_form_toPrimitive(input, hint) {
  if (password_form_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (password_form_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function password_form_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    password_form_get = Reflect.get.bind();
  } else {
    password_form_get = function _get(target, property, receiver) {
      var base = password_form_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return password_form_get.apply(this, arguments);
}
function password_form_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = password_form_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function password_form_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) password_form_setPrototypeOf(subClass, superClass);
}
function password_form_setPrototypeOf(o, p) {
  password_form_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return password_form_setPrototypeOf(o, p);
}
function password_form_createSuper(Derived) {
  var hasNativeReflectConstruct = password_form_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = password_form_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = password_form_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return password_form_possibleConstructorReturn(this, result);
  };
}
function password_form_possibleConstructorReturn(self, call) {
  if (call && (password_form_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 password_form_assertThisInitialized(self);
}
function password_form_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function password_form_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 password_form_getPrototypeOf(o) {
  password_form_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return password_form_getPrototypeOf(o);
}



var MUCPasswordForm = /*#__PURE__*/function (_CustomElement) {
  password_form_inherits(MUCPasswordForm, _CustomElement);
  var _super = password_form_createSuper(MUCPasswordForm);
  function MUCPasswordForm() {
    password_form_classCallCheck(this, MUCPasswordForm);
    return _super.apply(this, arguments);
  }
  password_form_createClass(MUCPasswordForm, [{
    key: "connectedCallback",
    value: function connectedCallback() {
      password_form_get(password_form_getPrototypeOf(MUCPasswordForm.prototype), "connectedCallback", this).call(this);
      this.model = shared_converse.chatboxes.get(this.jid);
      this.listenTo(this.model, 'change:password_validation_message', this.render);
      this.render();
    }
  }, {
    key: "render",
    value: function render() {
      var _this = this;
      return muc_password_form({
        'jid': this.model.get('jid'),
        'submitPassword': function submitPassword(ev) {
          return _this.submitPassword(ev);
        },
        'validation_message': this.model.get('password_validation_message')
      });
    }
  }, {
    key: "submitPassword",
    value: function submitPassword(ev) {
      ev.preventDefault();
      var password = this.querySelector('input[type=password]').value;
      this.model.join(this.model.get('nick'), password);
      this.model.set('password_validation_message', null);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return MUCPasswordForm;
}(CustomElement);
shared_api.elements.define('converse-muc-password-form', MUCPasswordForm);
/* harmony default export */ const password_form = ((/* unused pure expression or super */ null && (MUCPasswordForm)));
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc.js
var muc_templateObject, muc_templateObject2;
function muc_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}









/* harmony default export */ const templates_muc = (function (o) {
  return (0,external_lit_namespaceObject.html)(muc_templateObject || (muc_templateObject = muc_taggedTemplateLiteral(["\n        <div class=\"flyout box-flyout\">\n            <converse-dragresize></converse-dragresize>\n            ", "\n        </div>"])), o.model ? (0,external_lit_namespaceObject.html)(muc_templateObject2 || (muc_templateObject2 = muc_taggedTemplateLiteral(["\n                <converse-muc-heading jid=\"", "\" class=\"chat-head chat-head-chatroom row no-gutters\">\n                </converse-muc-heading>\n                <div class=\"chat-body chatroom-body row no-gutters\">", "</div>\n            "])), o.model.get('jid'), getChatRoomBodyTemplate(o)) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/muc.js
function muc_views_muc_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_muc_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;
  }, muc_views_muc_typeof(obj);
}
function muc_views_muc_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_muc_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" == muc_views_muc_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 muc_views_muc_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 muc_views_muc_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_muc_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_muc_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function muc_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_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, muc_views_muc_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_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) muc_setPrototypeOf(subClass, superClass);
}
function muc_setPrototypeOf(o, p) {
  muc_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_setPrototypeOf(o, p);
}
function muc_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_possibleConstructorReturn(this, result);
  };
}
function muc_possibleConstructorReturn(self, call) {
  if (call && (muc_views_muc_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 muc_assertThisInitialized(self);
}
function muc_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_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 muc_getPrototypeOf(o) {
  muc_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_getPrototypeOf(o);
}
function muc_views_muc_defineProperty(obj, key, value) {
  key = muc_views_muc_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 muc_views_muc_toPropertyKey(arg) {
  var key = muc_views_muc_toPrimitive(arg, "string");
  return muc_views_muc_typeof(key) === "symbol" ? key : String(key);
}
function muc_views_muc_toPrimitive(input, hint) {
  if (muc_views_muc_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_views_muc_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}



var MUCView = /*#__PURE__*/function (_BaseChatView) {
  muc_inherits(MUCView, _BaseChatView);
  var _super = muc_createSuper(MUCView);
  function MUCView() {
    var _this;
    muc_classCallCheck(this, MUCView);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    muc_views_muc_defineProperty(muc_assertThisInitialized(_this), "length", 300);
    muc_views_muc_defineProperty(muc_assertThisInitialized(_this), "is_chatroom", true);
    return _this;
  }
  muc_createClass(MUCView, [{
    key: "initialize",
    value: function () {
      var _initialize = muc_views_muc_asyncToGenerator( /*#__PURE__*/muc_views_muc_regeneratorRuntime().mark(function _callee() {
        var _this2 = this;
        return muc_views_muc_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.rooms.get(this.jid);
            case 2:
              this.model = _context.sent;
              shared_converse.chatboxviews.add(this.jid, this);
              this.setAttribute('id', this.model.get('box_id'));
              this.listenTo(shared_converse, 'windowStateChanged', this.onWindowStateChanged);
              this.listenTo(this.model, 'change:composing_spoiler', this.requestUpdateMessageForm);
              this.listenTo(this.model.session, 'change:connection_status', this.onConnectionStatusChanged);
              this.listenTo(this.model.session, 'change:view', function () {
                return _this2.requestUpdate();
              });
              this.onConnectionStatusChanged();
              this.model.maybeShow();
              /**
               * Triggered once a {@link _converse.ChatRoomView} has been opened
               * @event _converse#chatRoomViewInitialized
               * @type { _converse.ChatRoomView }
               * @example _converse.api.listen.on('chatRoomViewInitialized', view => { ... });
               */
              shared_api.trigger('chatRoomViewInitialized', this);
            case 12:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return templates_muc({
        'model': this.model
      });
    }
  }, {
    key: "onConnectionStatusChanged",
    value: function onConnectionStatusChanged() {
      var conn_status = this.model.session.get('connection_status');
      if (conn_status === public_converse.ROOMSTATUS.CONNECTING) {
        this.model.session.save({
          'disconnection_actor': undefined,
          'disconnection_message': undefined,
          'disconnection_reason': undefined
        });
        this.model.save({
          'moved_jid': undefined,
          'password_validation_message': undefined,
          'reason': undefined
        });
      }
      this.requestUpdate();
    }
  }]);
  return MUCView;
}(BaseChatView);

shared_api.elements.define('converse-muc', MUCView);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/index.scss
var muc_views_styles = __webpack_require__(9761);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/index.scss

      
      
      
      
      
      
      
      
      

var muc_views_styles_options = {};

muc_views_styles_options.styleTagTransform = (styleTagTransform_default());
muc_views_styles_options.setAttributes = (setAttributesWithoutAttributes_default());

      muc_views_styles_options.insert = insertBySelector_default().bind(null, "head");
    
muc_views_styles_options.domAPI = (styleDomAPI_default());
muc_views_styles_options.insertStyleElement = (insertStyleElement_default());

var muc_views_styles_update = injectStylesIntoStyleTag_default()(muc_views_styles/* default */.Z, muc_views_styles_options);




       /* harmony default export */ const plugins_muc_views_styles = (muc_views_styles/* default */.Z && muc_views_styles/* default */.Z.locals ? muc_views_styles/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/index.js
function muc_views_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_views_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;
  }, muc_views_typeof(obj);
}
function muc_views_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  muc_views_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" == muc_views_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 muc_views_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 muc_views_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        muc_views_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        muc_views_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js developers
 * @description XEP-0045 Multi-User Chat Views
 * @license Mozilla Public License (MPLv2)
 */






var muc_views_Strophe = public_converse.env.Strophe;

public_converse.MUC.VIEWS = {
  CONFIG: 'config-form'
};
public_converse.plugins.add('converse-muc-views', {
  /* Dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * NB: These plugins need to have already been loaded via require.js.
   *
   * It's possible to make these dependencies "non-optional".
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   */
  dependencies: ['converse-modal', 'converse-controlbox', 'converse-chatview'],
  initialize: function initialize() {
    var _converse = this._converse;

    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'auto_list_rooms': false,
      'cache_muc_messages': true,
      'locked_muc_nickname': false,
      'modtools_disable_query': [],
      'muc_disable_slash_commands': false,
      'muc_mention_autocomplete_filter': 'contains',
      'muc_mention_autocomplete_min_chars': 0,
      'muc_mention_autocomplete_show_avatar': true,
      'muc_roomid_policy': null,
      'muc_roomid_policy_hint': null,
      'roomconfig_whitelist': [],
      'show_retraction_warning': true,
      'visible_toolbar_buttons': {
        'toggle_occupants': true
      }
    });
    _converse.ChatRoomView = MUCView;
    if (!shared_api.settings.get('muc_domain')) {
      // Use service discovery to get the default MUC domain
      shared_api.listen.on('serviceDiscovered', /*#__PURE__*/function () {
        var _ref = muc_views_asyncToGenerator( /*#__PURE__*/muc_views_regeneratorRuntime().mark(function _callee(feature) {
          var identity;
          return muc_views_regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                if (!((feature === null || feature === void 0 ? void 0 : feature.get('var')) === muc_views_Strophe.NS.MUC)) {
                  _context.next = 7;
                  break;
                }
                if (!feature.entity.get('jid').includes('@')) {
                  _context.next = 3;
                  break;
                }
                return _context.abrupt("return");
              case 3:
                _context.next = 5;
                return feature.entity.getIdentity('conference', 'text');
              case 5:
                identity = _context.sent;
                if (identity) {
                  shared_api.settings.set('muc_domain', muc_views_Strophe.getDomainFromJid(feature.get('from')));
                }
              case 7:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
    }
    shared_api.listen.on('clearsession', function () {
      var view = _converse.chatboxviews.get('controlbox');
      if (view && view.roomspanel) {
        view.roomspanel.model.destroy();
        view.roomspanel.remove();
        delete view.roomspanel;
      }
    });
    shared_api.listen.on('chatBoxClosed', function (model) {
      if (model.get('type') === _converse.CHATROOMS_TYPE) {
        clearHistory(model.get('jid'));
      }
    });
    shared_api.listen.on('parseMessageForCommands', parseMessageForMUCCommands);
    shared_api.listen.on('confirmDirectMUCInvitation', confirmDirectMUCInvitation);
  }
});
;// CONCATENATED MODULE: ./src/plugins/minimize/toggle.js

var MinimizedChatsToggle = Model.extend({
  defaults: {
    'collapsed': false
  }
});
/* harmony default export */ const minimize_toggle = (MinimizedChatsToggle);
;// CONCATENATED MODULE: ./src/plugins/minimize/templates/chats-panel.js
var chats_panel_templateObject, chats_panel_templateObject2;
function chats_panel_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const chats_panel = (function (o) {
  return (0,external_lit_namespaceObject.html)(chats_panel_templateObject || (chats_panel_templateObject = chats_panel_taggedTemplateLiteral(["<div id=\"minimized-chats\" class=\"", "\">\n        <a id=\"toggle-minimized-chats\" class=\"row no-gutters\" @click=", ">\n            ", " ", "\n            <span class=\"unread-message-count ", "\" href=\"#\">", "</span>\n        </a>\n        <div class=\"flyout minimized-chats-flyout row no-gutters ", "\">\n            ", "\n        </div>\n    </div>"])), o.chats.length ? '' : 'hidden', o.toggle, o.num_minimized, __('Minimized'), !o.num_unread ? 'unread-message-count-hidden' : '', o.num_unread, o.collapsed ? 'hidden' : '', o.chats.map(function (chat) {
    return (0,external_lit_namespaceObject.html)(chats_panel_templateObject2 || (chats_panel_templateObject2 = chats_panel_taggedTemplateLiteral(["<converse-minimized-chat\n                        .model=", "\n                        title=", "\n                        type=", "\n                        num_unread=", "></converse-minimized-chat>"])), chat, chat.getDisplayName(), chat.get('type'), chat.get('num_unread'));
  }));
});
;// CONCATENATED MODULE: ./src/plugins/minimize/view.js
function minimize_view_typeof(obj) {
  "@babel/helpers - typeof";

  return minimize_view_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;
  }, minimize_view_typeof(obj);
}
function minimize_view_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  minimize_view_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" == minimize_view_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 minimize_view_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 minimize_view_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        minimize_view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        minimize_view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function minimize_view_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function minimize_view_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, minimize_view_toPropertyKey(descriptor.key), descriptor);
  }
}
function minimize_view_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) minimize_view_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) minimize_view_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function minimize_view_toPropertyKey(arg) {
  var key = minimize_view_toPrimitive(arg, "string");
  return minimize_view_typeof(key) === "symbol" ? key : String(key);
}
function minimize_view_toPrimitive(input, hint) {
  if (minimize_view_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (minimize_view_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function minimize_view_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) minimize_view_setPrototypeOf(subClass, superClass);
}
function minimize_view_setPrototypeOf(o, p) {
  minimize_view_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return minimize_view_setPrototypeOf(o, p);
}
function minimize_view_createSuper(Derived) {
  var hasNativeReflectConstruct = minimize_view_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = minimize_view_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = minimize_view_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return minimize_view_possibleConstructorReturn(this, result);
  };
}
function minimize_view_possibleConstructorReturn(self, call) {
  if (call && (minimize_view_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 minimize_view_assertThisInitialized(self);
}
function minimize_view_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function minimize_view_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 minimize_view_getPrototypeOf(o) {
  minimize_view_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return minimize_view_getPrototypeOf(o);
}





var MinimizedChats = /*#__PURE__*/function (_CustomElement) {
  minimize_view_inherits(MinimizedChats, _CustomElement);
  var _super = minimize_view_createSuper(MinimizedChats);
  function MinimizedChats() {
    minimize_view_classCallCheck(this, MinimizedChats);
    return _super.apply(this, arguments);
  }
  minimize_view_createClass(MinimizedChats, [{
    key: "initialize",
    value: function () {
      var _initialize = minimize_view_asyncToGenerator( /*#__PURE__*/minimize_view_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return minimize_view_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.model = shared_converse.chatboxes;
              _context.next = 3;
              return this.initToggle();
            case 3:
              this.listenTo(this.minchats, 'change:collapsed', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:fullname', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:jid', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:minimized', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:name', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change:num_unread', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse, 'connected', function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse, 'reconnected', function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse, 'disconnected', function () {
                return _this.requestUpdate();
              });
            case 14:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var chats = this.model.where({
        'minimized': true
      });
      var num_unread = chats.reduce(function (acc, chat) {
        return acc + chat.get('num_unread');
      }, 0);
      var num_minimized = chats.reduce(function (acc, chat) {
        return acc + (chat.get('minimized') ? 1 : 0);
      }, 0);
      var collapsed = this.minchats.get('collapsed');
      var data = {
        chats: chats,
        num_unread: num_unread,
        num_minimized: num_minimized,
        collapsed: collapsed
      };
      data.toggle = function (ev) {
        return _this2.toggle(ev);
      };
      return chats_panel(data);
    }
  }, {
    key: "initToggle",
    value: function () {
      var _initToggle = minimize_view_asyncToGenerator( /*#__PURE__*/minimize_view_regeneratorRuntime().mark(function _callee2() {
        var _this3 = this;
        var id;
        return minimize_view_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              id = "converse.minchatstoggle-".concat(shared_converse.bare_jid);
              this.minchats = new minimize_toggle({
                id: id
              });
              initStorage(this.minchats, id, 'session');
              _context2.next = 5;
              return new Promise(function (resolve) {
                return _this3.minchats.fetch({
                  'success': resolve,
                  'error': resolve
                });
              });
            case 5:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function initToggle() {
        return _initToggle.apply(this, arguments);
      }
      return initToggle;
    }()
  }, {
    key: "toggle",
    value: function toggle(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      this.minchats.save({
        'collapsed': !this.minchats.get('collapsed')
      });
    }
  }]);
  return MinimizedChats;
}(CustomElement);

shared_api.elements.define('converse-minimized-chats', MinimizedChats);
;// CONCATENATED MODULE: ./src/plugins/minimize/templates/trimmed_chat.js
var trimmed_chat_templateObject, trimmed_chat_templateObject2;
function trimmed_chat_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const trimmed_chat = (function (o) {
  var i18n_tooltip = __('Click to restore this chat');
  var close_color;
  if (o.type === 'chatroom') {
    close_color = "var(--chatroom-head-color)";
  } else if (o.type === 'headline') {
    close_color = "var(--headlines-head-text-color)";
  } else {
    close_color = "var(--chat-head-text-color)";
  }
  return (0,external_lit_namespaceObject.html)(trimmed_chat_templateObject || (trimmed_chat_templateObject = trimmed_chat_taggedTemplateLiteral(["\n    <div class=\"chat-head-", " chat-head row no-gutters\">\n        <a class=\"restore-chat w-100 align-self-center\" title=\"", "\" @click=", ">\n            ", "\n            ", "\n        </a>\n        <a class=\"chatbox-btn close-chatbox-button\" @click=", ">\n            <converse-icon color=", " class=\"fas fa-times\" @click=", " size=\"1em\"></converse-icon>\n        </a>\n    </div>"])), o.type, i18n_tooltip, o.restore, o.num_unread ? (0,external_lit_namespaceObject.html)(trimmed_chat_templateObject2 || (trimmed_chat_templateObject2 = trimmed_chat_taggedTemplateLiteral(["<span class=\"message-count badge badge-light\">", "</span>"])), o.num_unread) : '', o.title, o.close, close_color, o.close);
});
;// CONCATENATED MODULE: ./src/plugins/minimize/utils.js
function minimize_utils_toConsumableArray(arr) {
  return minimize_utils_arrayWithoutHoles(arr) || minimize_utils_iterableToArray(arr) || minimize_utils_unsupportedIterableToArray(arr) || minimize_utils_nonIterableSpread();
}
function minimize_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function minimize_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return minimize_utils_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 minimize_utils_arrayLikeToArray(o, minLen);
}
function minimize_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function minimize_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return minimize_utils_arrayLikeToArray(arr);
}
function minimize_utils_arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}


var minimize_utils_converse$env = public_converse.env,
  minimize_utils_dayjs = minimize_utils_converse$env.dayjs,
  minimize_utils_u = minimize_utils_converse$env.u;
function initializeChat(chat) {
  chat.on('change:hidden', function (m) {
    return !m.get('hidden') && maximize(chat);
  }, chat);
  if (chat.get('id') === 'controlbox') {
    return;
  }
  chat.save({
    'minimized': chat.get('minimized') || false,
    'time_minimized': chat.get('time_minimized') || minimize_utils_dayjs()
  });
}
function getChatBoxWidth(view) {
  if (view.model.get('id') === 'controlbox') {
    // We return the width of the controlbox or its toggle,
    // depending on which is visible.
    if (minimize_utils_u.isVisible(view)) {
      return minimize_utils_u.getOuterWidth(view, true);
    } else {
      var toggle = document.querySelector('converse-controlbox-toggle');
      return toggle ? minimize_utils_u.getOuterWidth(toggle, true) : 0;
    }
  } else if (!view.model.get('minimized') && minimize_utils_u.isVisible(view)) {
    return minimize_utils_u.getOuterWidth(view, true);
  }
  return 0;
}
function getShownChats() {
  return shared_converse.chatboxviews.filter(function (el) {
    return (
      // The controlbox can take a while to close,
      // so we need to check its state. That's why we checked the 'closed' state.
      !el.model.get('minimized') && !el.model.get('closed') && minimize_utils_u.isVisible(el)
    );
  });
}
function getMinimizedWidth() {
  var minimized_el = document.querySelector('converse-minimized-chats');
  return shared_converse.chatboxes.pluck('minimized').includes(true) ? minimize_utils_u.getOuterWidth(minimized_el, true) : 0;
}
function getBoxesWidth(newchat) {
  var new_id = newchat ? newchat.model.get('id') : null;
  var newchat_width = newchat ? minimize_utils_u.getOuterWidth(newchat, true) : 0;
  return Object.values(shared_converse.chatboxviews.xget(new_id)).reduce(function (memo, view) {
    return memo + getChatBoxWidth(view);
  }, newchat_width);
}

/**
 * This method is called when a newly created chat box will be shown.
 * It checks whether there is enough space on the page to show
 * another chat box. Otherwise it minimizes the oldest chat box
 * to create space.
 * @private
 * @method _converse.ChatBoxViews#trimChats
 * @param { _converse.ChatBoxView|_converse.ChatRoomView|_converse.ControlBoxView|_converse.HeadlinesFeedView } [newchat]
 */
function trimChats(newchat) {
  if (shared_converse.isTestEnv() || shared_api.settings.get('no_trimming') || shared_api.settings.get("view_mode") !== 'overlayed') {
    return;
  }
  var shown_chats = getShownChats();
  if (shown_chats.length <= 1) {
    return;
  }
  var body_width = minimize_utils_u.getOuterWidth(document.querySelector('body'), true);
  if (getChatBoxWidth(shown_chats[0]) === body_width) {
    // If the chats shown are the same width as the body,
    // then we're in responsive mode and the chats are
    // fullscreen. In this case we don't trim.
    return;
  }
  var minimized_el = document.querySelector('converse-minimized-chats');
  if (minimized_el) {
    while (getMinimizedWidth() + getBoxesWidth(newchat) > body_width) {
      var new_id = newchat ? newchat.model.get('id') : null;
      var oldest_chat = getOldestMaximizedChat([new_id]);
      if (oldest_chat) {
        var model = shared_converse.chatboxes.get(oldest_chat.get('id'));
        model === null || model === void 0 ? void 0 : model.save('hidden', true);
        minimize(oldest_chat);
      } else {
        break;
      }
    }
  }
}
function getOldestMaximizedChat(exclude_ids) {
  // Get oldest view (if its id is not excluded)
  exclude_ids.push('controlbox');
  var i = 0;
  var model = shared_converse.chatboxes.sort().at(i);
  while (exclude_ids.includes(model.get('id')) || model.get('minimized') === true) {
    i++;
    model = shared_converse.chatboxes.at(i);
    if (!model) {
      return null;
    }
  }
  return model;
}
function addMinimizeButtonToChat(view, buttons) {
  var data = {
    'a_class': 'toggle-chatbox-button',
    'handler': function handler(ev) {
      return minimize(ev, view.model);
    },
    'i18n_text': __('Minimize'),
    'i18n_title': __('Minimize this chat'),
    'icon_class': "fa-minus",
    'name': 'minimize',
    'standalone': shared_converse.api.settings.get("view_mode") === 'overlayed'
  };
  var names = buttons.map(function (t) {
    return t.name;
  });
  var idx = names.indexOf('close');
  return idx > -1 ? [].concat(minimize_utils_toConsumableArray(buttons.slice(0, idx)), [data], minimize_utils_toConsumableArray(buttons.slice(idx))) : [data].concat(minimize_utils_toConsumableArray(buttons));
}
function addMinimizeButtonToMUC(view, buttons) {
  var data = {
    'a_class': 'toggle-chatbox-button',
    'handler': function handler(ev) {
      return minimize(ev, view.model);
    },
    'i18n_text': __('Minimize'),
    'i18n_title': __('Minimize this groupchat'),
    'icon_class': "fa-minus",
    'name': 'minimize',
    'standalone': shared_converse.api.settings.get("view_mode") === 'overlayed'
  };
  var names = buttons.map(function (t) {
    return t.name;
  });
  var idx = names.indexOf('signout');
  return idx > -1 ? [].concat(minimize_utils_toConsumableArray(buttons.slice(0, idx)), [data], minimize_utils_toConsumableArray(buttons.slice(idx))) : [data].concat(minimize_utils_toConsumableArray(buttons));
}
function maximize(ev, chatbox) {
  if (ev !== null && ev !== void 0 && ev.preventDefault) {
    ev.preventDefault();
  } else {
    chatbox = ev;
  }
  minimize_utils_u.safeSave(chatbox, {
    'hidden': false,
    'minimized': false,
    'time_opened': new Date().getTime()
  });
}
function minimize(ev, model) {
  if (ev !== null && ev !== void 0 && ev.preventDefault) {
    ev.preventDefault();
  } else {
    model = ev;
  }
  model.setChatState(shared_converse.INACTIVE);
  minimize_utils_u.safeSave(model, {
    'hidden': true,
    'minimized': true,
    'time_minimized': new Date().toISOString()
  });
}

/**
 * Handler which gets called when a {@link _converse#ChatBox} has it's
 * `minimized` property set to false.
 *
 * Will trigger {@link _converse#chatBoxMaximized}
 * @returns {_converse.ChatBoxView|_converse.ChatRoomView}
 */
function onMaximized(model) {
  if (!model.isScrolledUp()) {
    model.clearUnreadMsgCounter();
  }
  model.setChatState(shared_converse.ACTIVE);
  /**
   * Triggered when a previously minimized chat gets maximized
   * @event _converse#chatBoxMaximized
   * @type { _converse.ChatBoxView }
   * @example _converse.api.listen.on('chatBoxMaximized', view => { ... });
   */
  shared_api.trigger('chatBoxMaximized', model);
}

/**
 * Handler which gets called when a {@link _converse#ChatBox} has it's
 * `minimized` property set to true.
 *
 * Will trigger {@link _converse#chatBoxMinimized}
 * @returns {_converse.ChatBoxView|_converse.ChatRoomView}
 */
function onMinimized(model) {
  /**
   * Triggered when a previously maximized chat gets Minimized
   * @event _converse#chatBoxMinimized
   * @type { _converse.ChatBoxView }
   * @example _converse.api.listen.on('chatBoxMinimized', view => { ... });
   */
  shared_api.trigger('chatBoxMinimized', model);
}
function onMinimizedChanged(model) {
  if (model.get('minimized')) {
    onMinimized(model);
  } else {
    onMaximized(model);
  }
}
;// CONCATENATED MODULE: ./src/plugins/minimize/components/minimized-chat.js
function minimized_chat_typeof(obj) {
  "@babel/helpers - typeof";

  return minimized_chat_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;
  }, minimized_chat_typeof(obj);
}
function minimized_chat_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function minimized_chat_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, minimized_chat_toPropertyKey(descriptor.key), descriptor);
  }
}
function minimized_chat_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) minimized_chat_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) minimized_chat_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function minimized_chat_toPropertyKey(arg) {
  var key = minimized_chat_toPrimitive(arg, "string");
  return minimized_chat_typeof(key) === "symbol" ? key : String(key);
}
function minimized_chat_toPrimitive(input, hint) {
  if (minimized_chat_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (minimized_chat_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function minimized_chat_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) minimized_chat_setPrototypeOf(subClass, superClass);
}
function minimized_chat_setPrototypeOf(o, p) {
  minimized_chat_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return minimized_chat_setPrototypeOf(o, p);
}
function minimized_chat_createSuper(Derived) {
  var hasNativeReflectConstruct = minimized_chat_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = minimized_chat_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = minimized_chat_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return minimized_chat_possibleConstructorReturn(this, result);
  };
}
function minimized_chat_possibleConstructorReturn(self, call) {
  if (call && (minimized_chat_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 minimized_chat_assertThisInitialized(self);
}
function minimized_chat_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function minimized_chat_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 minimized_chat_getPrototypeOf(o) {
  minimized_chat_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return minimized_chat_getPrototypeOf(o);
}




var MinimizedChat = /*#__PURE__*/function (_CustomElement) {
  minimized_chat_inherits(MinimizedChat, _CustomElement);
  var _super = minimized_chat_createSuper(MinimizedChat);
  function MinimizedChat() {
    minimized_chat_classCallCheck(this, MinimizedChat);
    return _super.apply(this, arguments);
  }
  minimized_chat_createClass(MinimizedChat, [{
    key: "render",
    value: function render() {
      var _this = this;
      var data = {
        'close': function close(ev) {
          return _this.close(ev);
        },
        'num_unread': this.num_unread,
        'restore': function restore(ev) {
          return _this.restore(ev);
        },
        'title': this.title,
        'type': this.type
      };
      return trimmed_chat(data);
    }
  }, {
    key: "close",
    value: function close(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      this.model.close();
    }
  }, {
    key: "restore",
    value: function restore(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      maximize(this.model);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        model: {
          type: Object
        },
        title: {
          type: String
        },
        type: {
          type: String
        },
        num_unread: {
          type: Number
        }
      };
    }
  }]);
  return MinimizedChat;
}(CustomElement);

shared_api.elements.define('converse-minimized-chat', MinimizedChat);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/minimize/styles/minimize.scss
var styles_minimize = __webpack_require__(6922);
;// CONCATENATED MODULE: ./src/plugins/minimize/styles/minimize.scss

      
      
      
      
      
      
      
      
      

var minimize_options = {};

minimize_options.styleTagTransform = (styleTagTransform_default());
minimize_options.setAttributes = (setAttributesWithoutAttributes_default());

      minimize_options.insert = insertBySelector_default().bind(null, "head");
    
minimize_options.domAPI = (styleDomAPI_default());
minimize_options.insertStyleElement = (insertStyleElement_default());

var minimize_update = injectStylesIntoStyleTag_default()(styles_minimize/* default */.Z, minimize_options);




       /* harmony default export */ const minimize_styles_minimize = (styles_minimize/* default */.Z && styles_minimize/* default */.Z.locals ? styles_minimize/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/minimize/index.js
/**
 * @module converse-minimize
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







public_converse.plugins.add('converse-minimize', {
  /* Optional dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are called "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * It's possible however to make optional dependencies non-optional.
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   */
  dependencies: ["converse-chatview", "converse-controlbox", "converse-muc-views", "converse-headlines-view", "converse-dragresize"],
  enabled: function enabled(_converse) {
    return _converse.api.settings.get("view_mode") === 'overlayed';
  },
  // Overrides mentioned here will be picked up by converse.js's
  // plugin architecture they will replace existing methods on the
  // relevant objects or classes.
  // New functions which don't exist yet can also be added.
  overrides: {
    ChatBox: {
      maybeShow: function maybeShow(force) {
        if (!force && this.get('minimized')) {
          // Must return the chatbox
          return this;
        }
        return this.__super__.maybeShow.apply(this, arguments);
      },
      isHidden: function isHidden() {
        return this.__super__.isHidden.call(this) || this.get('minimized');
      }
    },
    ChatBoxView: {
      isNewMessageHidden: function isNewMessageHidden() {
        return this.model.get('minimized') || this.__super__.isNewMessageHidden.apply(this, arguments);
      },
      setChatBoxHeight: function setChatBoxHeight(height) {
        if (!this.model.get('minimized')) {
          return this.__super__.setChatBoxHeight.call(this, height);
        }
      },
      setChatBoxWidth: function setChatBoxWidth(width) {
        if (!this.model.get('minimized')) {
          return this.__super__.setChatBoxWidth.call(this, width);
        }
      }
    }
  },
  initialize: function initialize() {
    shared_api.settings.extend({
      'no_trimming': false
    });
    shared_api.promises.add('minimizedChatsInitialized');
    shared_converse.MinimizedChatsToggle = minimize_toggle;
    shared_converse.minimize = {
      trimChats: trimChats,
      minimize: minimize,
      maximize: maximize
    };
    function onChatInitialized(model) {
      initializeChat(model);
      model.on('change:minimized', function () {
        return onMinimizedChanged(model);
      });
    }
    shared_api.listen.on('chatBoxViewInitialized', function (view) {
      return shared_converse.minimize.trimChats(view);
    });
    shared_api.listen.on('chatRoomViewInitialized', function (view) {
      return shared_converse.minimize.trimChats(view);
    });
    shared_api.listen.on('controlBoxOpened', function (view) {
      return shared_converse.minimize.trimChats(view);
    });
    shared_api.listen.on('chatBoxInitialized', onChatInitialized);
    shared_api.listen.on('chatRoomInitialized', onChatInitialized);
    shared_api.listen.on('getHeadingButtons', function (view, buttons) {
      if (view.model.get('type') === shared_converse.CHATROOMS_TYPE) {
        return addMinimizeButtonToMUC(view, buttons);
      } else {
        return addMinimizeButtonToChat(view, buttons);
      }
    });
    var debouncedTrimChats = lodash_es_debounce(function () {
      return shared_converse.minimize.trimChats();
    }, 250);
    shared_api.listen.on('registeredGlobalEventHandlers', function () {
      return window.addEventListener("resize", debouncedTrimChats);
    });
    shared_api.listen.on('unregisteredGlobalEventHandlers', function () {
      return window.removeEventListener("resize", debouncedTrimChats);
    });
  }
});
// EXTERNAL MODULE: ./node_modules/favico.js-slevomat/favico.js
var favico = __webpack_require__(3429);
var favico_default = /*#__PURE__*/__webpack_require__.n(favico);
;// CONCATENATED MODULE: ./src/plugins/notifications/utils.js
function notifications_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return notifications_utils_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;
  }, notifications_utils_typeof(obj);
}
function notifications_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  notifications_utils_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" == notifications_utils_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 notifications_utils_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 notifications_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        notifications_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        notifications_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}





var notifications_utils_Strophe = public_converse.env.Strophe;
var supports_html5_notification = ('Notification' in window);
public_converse.env.Favico = (favico_default());
var favicon;
function isMessageToHiddenChat(attrs) {
  var _converse$chatboxes$g, _converse$chatboxes$g2;
  return shared_converse.isTestEnv() || ((_converse$chatboxes$g = (_converse$chatboxes$g2 = shared_converse.chatboxes.get(attrs.from)) === null || _converse$chatboxes$g2 === void 0 ? void 0 : _converse$chatboxes$g2.isHidden()) !== null && _converse$chatboxes$g !== void 0 ? _converse$chatboxes$g : false);
}
function areDesktopNotificationsEnabled() {
  return shared_converse.isTestEnv() || supports_html5_notification && shared_api.settings.get('show_desktop_notifications') && Notification.permission === 'granted';
}
function clearFavicon() {
  var _navigator$clearAppBa, _navigator;
  favicon = null;
  (_navigator$clearAppBa = (_navigator = navigator).clearAppBadge) === null || _navigator$clearAppBa === void 0 ? void 0 : _navigator$clearAppBa.call(_navigator).catch(function (e) {
    return log.error("Could not clear unread count in app badge " + e);
  });
}
function updateUnreadFavicon() {
  if (shared_api.settings.get('show_tab_notifications')) {
    var _favicon, _navigator$setAppBadg, _navigator2;
    favicon = (_favicon = favicon) !== null && _favicon !== void 0 ? _favicon : new public_converse.env.Favico({
      type: 'circle',
      animation: 'pop'
    });
    var chats = shared_converse.chatboxes.models;
    var num_unread = chats.reduce(function (acc, chat) {
      return acc + (chat.get('num_unread') || 0);
    }, 0);
    favicon.badge(num_unread);
    (_navigator$setAppBadg = (_navigator2 = navigator).setAppBadge) === null || _navigator$setAppBadg === void 0 ? void 0 : _navigator$setAppBadg.call(_navigator2, num_unread).catch(function (e) {
      return log.error("Could set unread count in app badge - " + e);
    });
  }
}
function isReferenced(references, muc_jid, nick) {
  var check = function check(r) {
    return [shared_converse.bare_jid, "".concat(muc_jid, "/").concat(nick)].includes(r.uri.replace(/^xmpp:/, ''));
  };
  return references.reduce(function (acc, r) {
    return acc || check(r);
  }, false);
}

/**
 * Is this a group message for which we should notify the user?
 * @private
 * @param { MUCMessageAttributes } attrs
 */
function shouldNotifyOfGroupMessage(_x) {
  return _shouldNotifyOfGroupMessage.apply(this, arguments);
}
function _shouldNotifyOfGroupMessage() {
  _shouldNotifyOfGroupMessage = notifications_utils_asyncToGenerator( /*#__PURE__*/notifications_utils_regeneratorRuntime().mark(function _callee(attrs) {
    var jid, muc_jid, notify_all, room, resource, sender, is_mentioned, nick, is_not_mine, should_notify_user, should_notify;
    return notifications_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!(!(attrs !== null && attrs !== void 0 && attrs.body) && !(attrs !== null && attrs !== void 0 && attrs.message))) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return", false);
        case 2:
          jid = attrs.from;
          muc_jid = attrs.from_muc;
          notify_all = shared_api.settings.get('notify_all_room_messages');
          room = shared_converse.chatboxes.get(muc_jid);
          resource = notifications_utils_Strophe.getResourceFromJid(jid);
          sender = resource && notifications_utils_Strophe.unescapeNode(resource) || '';
          is_mentioned = false;
          nick = room.get('nick');
          if (shared_api.settings.get('notify_nicknames_without_references')) {
            is_mentioned = new RegExp("\\b".concat(nick, "\\b")).test(attrs.body);
          }
          is_not_mine = sender !== nick;
          should_notify_user = notify_all === true || Array.isArray(notify_all) && notify_all.includes(muc_jid) || isReferenced(attrs.references, muc_jid, nick) || is_mentioned;
          if (!(is_not_mine && !!should_notify_user)) {
            _context.next = 18;
            break;
          }
          _context.next = 16;
          return shared_api.hook('shouldNotifyOfGroupMessage', attrs, true);
        case 16:
          should_notify = _context.sent;
          return _context.abrupt("return", should_notify);
        case 18:
          return _context.abrupt("return", false);
        case 19:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _shouldNotifyOfGroupMessage.apply(this, arguments);
}
function shouldNotifyOfInfoMessage(_x2) {
  return _shouldNotifyOfInfoMessage.apply(this, arguments);
}
/**
 * @private
 * @async
 * @method shouldNotifyOfMessage
 * @param { MessageData|MUCMessageData } data
 */
function _shouldNotifyOfInfoMessage() {
  _shouldNotifyOfInfoMessage = notifications_utils_asyncToGenerator( /*#__PURE__*/notifications_utils_regeneratorRuntime().mark(function _callee2(attrs) {
    var room, nick, muc_jid, notify_all;
    return notifications_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (attrs.from_muc) {
            _context2.next = 2;
            break;
          }
          return _context2.abrupt("return", false);
        case 2:
          _context2.next = 4;
          return shared_api.rooms.get(attrs.from_muc);
        case 4:
          room = _context2.sent;
          if (room) {
            _context2.next = 7;
            break;
          }
          return _context2.abrupt("return", false);
        case 7:
          nick = room.get('nick');
          muc_jid = attrs.from_muc;
          notify_all = shared_api.settings.get('notify_all_room_messages');
          return _context2.abrupt("return", notify_all === true || Array.isArray(notify_all) && notify_all.includes(muc_jid) || isReferenced(attrs.references, muc_jid, nick));
        case 11:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _shouldNotifyOfInfoMessage.apply(this, arguments);
}
function shouldNotifyOfMessage(data) {
  var attrs = data.attrs;
  if (!attrs || attrs.is_forwarded) {
    return false;
  }
  if (attrs['type'] === 'groupchat') {
    return shouldNotifyOfGroupMessage(attrs);
  } else if (attrs['type'] === 'info') {
    return shouldNotifyOfInfoMessage(attrs);
  } else if (attrs.is_headline) {
    // We want to show notifications for headline messages.
    return isMessageToHiddenChat(attrs);
  }
  var is_me = notifications_utils_Strophe.getBareJidFromJid(attrs.from) === shared_converse.bare_jid;
  return !isEmptyMessage(attrs) && !is_me && (shared_api.settings.get('show_desktop_notifications') === 'all' || isMessageToHiddenChat(attrs));
}
function showFeedbackNotification(data) {
  if (data.klass === 'error' || data.klass === 'warn') {
    var n = new Notification(data.subject, {
      body: data.message,
      lang: shared_converse.locale,
      icon: shared_api.settings.get('notification_icon')
    });
    setTimeout(n.close.bind(n), 5000);
  }
}

/**
 * Creates an HTML5 Notification to inform of a change in a
 * contact's chat state.
 */
function showChatStateNotification(contact) {
  var _api$settings$get;
  if ((_api$settings$get = shared_api.settings.get('chatstate_notification_blacklist')) !== null && _api$settings$get !== void 0 && _api$settings$get.includes(contact.jid)) {
    // Don't notify if the user is being ignored.
    return;
  }
  var chat_state = contact.presence.get('show');
  var message = null;
  if (chat_state === 'offline') {
    message = __('has gone offline');
  } else if (chat_state === 'away') {
    message = __('has gone away');
  } else if (chat_state === 'dnd') {
    message = __('is busy');
  } else if (chat_state === 'online') {
    message = __('has come online');
  }
  if (message === null) {
    return;
  }
  var n = new Notification(contact.getDisplayName(), {
    body: message,
    lang: shared_converse.locale,
    icon: shared_api.settings.get('notification_icon')
  });
  setTimeout(function () {
    return n.close();
  }, 5000);
}

/**
 * Shows an HTML5 Notification with the passed in message
 * @private
 * @param { MessageData|MUCMessageData } data
 */
function showMessageNotification(data) {
  var attrs = data.attrs;
  if (attrs.is_error) {
    return;
  }
  if (!areDesktopNotificationsEnabled()) {
    return;
  }
  var title, roster_item;
  var full_from_jid = attrs.from;
  var from_jid = notifications_utils_Strophe.getBareJidFromJid(full_from_jid);
  if (attrs.type == 'info') {
    title = attrs.message;
  } else if (attrs.type === 'headline') {
    if (!from_jid.includes('@') || shared_api.settings.get('allow_non_roster_messaging')) {
      title = __('Notification from %1$s', from_jid);
    } else {
      return;
    }
  } else if (!from_jid.includes('@')) {
    // workaround for Prosody which doesn't give type "headline"
    title = __('Notification from %1$s', from_jid);
  } else if (attrs.type === 'groupchat') {
    title = __('%1$s says', notifications_utils_Strophe.getResourceFromJid(full_from_jid));
  } else {
    if (shared_converse.roster === undefined) {
      log.error('Could not send notification, because roster is undefined');
      return;
    }
    roster_item = shared_converse.roster.get(from_jid);
    if (roster_item !== undefined) {
      title = __('%1$s says', roster_item.getDisplayName());
    } else {
      if (shared_api.settings.get('allow_non_roster_messaging')) {
        title = __('%1$s says', from_jid);
      } else {
        return;
      }
    }
  }
  var body;
  if (attrs.type == 'info') {
    body = attrs.reason;
  } else {
    body = attrs.is_encrypted ? attrs.plaintext : attrs.body;
    if (!body) {
      return;
    }
  }
  var n = new Notification(title, {
    'body': body,
    'lang': shared_converse.locale,
    'icon': shared_api.settings.get('notification_icon'),
    'requireInteraction': !shared_api.settings.get('notification_delay')
  });
  if (shared_api.settings.get('notification_delay')) {
    setTimeout(function () {
      return n.close();
    }, shared_api.settings.get('notification_delay'));
  }
  n.onclick = function (event) {
    event.preventDefault();
    window.focus();
    var chat = shared_converse.chatboxes.get(from_jid);
    chat.maybeShow(true);
  };
}
function playSoundNotification() {
  if (shared_api.settings.get('play_sounds') && window.Audio !== undefined) {
    var audioOgg = new Audio(shared_api.settings.get('sounds_path') + 'msg_received.ogg');
    var canPlayOgg = audioOgg.canPlayType('audio/ogg');
    if (canPlayOgg === 'probably') {
      return audioOgg.play();
    }
    var audioMp3 = new Audio(shared_api.settings.get('sounds_path') + 'msg_received.mp3');
    var canPlayMp3 = audioMp3.canPlayType('audio/mp3');
    if (canPlayMp3 === 'probably') {
      audioMp3.play();
    } else if (canPlayOgg === 'maybe') {
      audioOgg.play();
    } else if (canPlayMp3 === 'maybe') {
      audioMp3.play();
    }
  }
}

/**
 * Event handler for the on('message') event. Will call methods
 * to play sounds and show HTML5 notifications.
 */
function handleMessageNotification(_x3) {
  return _handleMessageNotification.apply(this, arguments);
}
function _handleMessageNotification() {
  _handleMessageNotification = notifications_utils_asyncToGenerator( /*#__PURE__*/notifications_utils_regeneratorRuntime().mark(function _callee3(data) {
    return notifications_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return shouldNotifyOfMessage(data);
        case 2:
          if (_context3.sent) {
            _context3.next = 4;
            break;
          }
          return _context3.abrupt("return", false);
        case 4:
          /**
           * Triggered when a notification (sound or HTML5 notification) for a new
           * message has will be made.
           * @event _converse#messageNotification
           * @type { MessageData|MUCMessageData}
           * @example _converse.api.listen.on('messageNotification', data => { ... });
           */
          shared_api.trigger('messageNotification', data);
          playSoundNotification();
          showMessageNotification(data);
        case 7:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _handleMessageNotification.apply(this, arguments);
}
function handleFeedback(data) {
  if (areDesktopNotificationsEnabled(true)) {
    showFeedbackNotification(data);
  }
}

/**
 * Event handler for on('contactPresenceChanged').
 * Will show an HTML5 notification to indicate that the chat status has changed.
 */
function handleChatStateNotification(contact) {
  if (areDesktopNotificationsEnabled() && shared_api.settings.get('show_chat_state_notifications')) {
    showChatStateNotification(contact);
  }
}
function showContactRequestNotification(contact) {
  var n = new Notification(contact.getDisplayName(), {
    body: __('wants to be your contact'),
    lang: shared_converse.locale,
    icon: shared_api.settings.get('notification_icon')
  });
  setTimeout(function () {
    return n.close();
  }, 5000);
}
function handleContactRequestNotification(contact) {
  if (areDesktopNotificationsEnabled(true)) {
    showContactRequestNotification(contact);
  }
}
function requestPermission() {
  if (supports_html5_notification && !['denied', 'granted'].includes(Notification.permission)) {
    // Ask user to enable HTML5 notifications
    Notification.requestPermission();
  }
}
;// CONCATENATED MODULE: ./src/plugins/notifications/index.js
/**
 * @module converse-notification
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


public_converse.plugins.add('converse-notification', {
  dependencies: ['converse-chatboxes'],
  initialize: function initialize() {
    shared_api.settings.extend({
      // ^ a list of JIDs to ignore concerning chat state notifications
      chatstate_notification_blacklist: [],
      notification_delay: 5000,
      notification_icon: '/images/logo/conversejs-filled.svg',
      notify_all_room_messages: false,
      notify_nicknames_without_references: false,
      play_sounds: true,
      show_chat_state_notifications: false,
      show_desktop_notifications: true,
      show_tab_notifications: true,
      sounds_path: shared_api.settings.get('assets_path') + '/sounds/'
    });

    /************************ Event Handlers ************************/
    shared_api.listen.on('clearSession', clearFavicon); // Needed for tests

    shared_api.waitUntil('chatBoxesInitialized').then(function () {
      return shared_converse.chatboxes.on('change:num_unread', updateUnreadFavicon);
    });
    shared_api.listen.on('pluginsInitialized', function () {
      // We only register event handlers after all plugins are
      // registered, because other plugins might override some of our
      // handlers.
      shared_api.listen.on('contactRequest', handleContactRequestNotification);
      shared_api.listen.on('contactPresenceChanged', handleChatStateNotification);
      shared_api.listen.on('message', handleMessageNotification);
      shared_api.listen.on('feedback', handleFeedback);
      shared_api.listen.on('connected', requestPermission);
    });
  }
});
;// CONCATENATED MODULE: ./src/plugins/profile/templates/chat-status-modal.js
var chat_status_modal_templateObject;
function chat_status_modal_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const chat_status_modal = (function (el) {
  var label_away = __('Away');
  var label_busy = __('Busy');
  var label_online = __('Online');
  var label_save = __('Save');
  var label_xa = __('Away for long');
  var placeholder_status_message = __('Personal status message');
  var status = el.model.get('status');
  var status_message = el.model.get('status_message');
  return (0,external_lit_namespaceObject.html)(chat_status_modal_templateObject || (chat_status_modal_templateObject = chat_status_modal_taggedTemplateLiteral(["\n    <form class=\"converse-form set-xmpp-status\" id=\"set-xmpp-status\" @submit=", ">\n        <div class=\"form-group\">\n            <div class=\"custom-control custom-radio\">\n                <input ?checked=", "\n                    type=\"radio\" id=\"radio-online\" value=\"online\" name=\"chat_status\" class=\"custom-control-input\"/>\n                <label class=\"custom-control-label\" for=\"radio-online\">\n                    <converse-icon size=\"1em\" class=\"fa fa-circle chat-status chat-status--online\"></converse-icon>", "</label>\n            </div>\n            <div class=\"custom-control custom-radio\">\n                <input ?checked=", "\n                    type=\"radio\" id=\"radio-busy\" value=\"dnd\" name=\"chat_status\" class=\"custom-control-input\"/>\n                <label class=\"custom-control-label\" for=\"radio-busy\">\n                    <converse-icon size=\"1em\" class=\"fa fa-minus-circle  chat-status chat-status--busy\"></converse-icon>", "</label>\n            </div>\n            <div class=\"custom-control custom-radio\">\n                <input ?checked=", "\n                    type=\"radio\" id=\"radio-away\" value=\"away\" name=\"chat_status\" class=\"custom-control-input\"/>\n                <label class=\"custom-control-label\" for=\"radio-away\">\n                    <converse-icon size=\"1em\" class=\"fa fa-circle chat-status chat-status--away\"></converse-icon>", "</label>\n            </div>\n            <div class=\"custom-control custom-radio\">\n                <input ?checked=", "\n                    type=\"radio\" id=\"radio-xa\" value=\"xa\" name=\"chat_status\" class=\"custom-control-input\"/>\n                <label class=\"custom-control-label\" for=\"radio-xa\">\n                    <converse-icon size=\"1em\" class=\"far fa-circle chat-status chat-status--xa\"></converse-icon>", "</label>\n            </div>\n        </div>\n        <div class=\"form-group\">\n            <div class=\"btn-group w-100\">\n                <input name=\"status_message\" type=\"text\" class=\"form-control\" autofocus\n                    value=\"", "\" placeholder=\"", "\"/>\n                <converse-icon size=\"1em\" class=\"fa fa-times clear-input ", "\" @click=", "></converse-icon>\n            </div>\n        </div>\n        <button type=\"submit\" class=\"btn btn-primary\">", "</button>\n    </form>"])), function (ev) {
    return el.onFormSubmitted(ev);
  }, status === 'online', label_online, status === 'busy', label_busy, status === 'away', label_away, status === 'xa', label_xa, status_message || '', placeholder_status_message, status_message ? '' : 'hidden', function (ev) {
    return el.clearStatusMessage(ev);
  }, label_save);
});
;// CONCATENATED MODULE: ./src/plugins/profile/modals/chat-status.js
function chat_status_typeof(obj) {
  "@babel/helpers - typeof";

  return chat_status_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;
  }, chat_status_typeof(obj);
}
function chat_status_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function chat_status_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, chat_status_toPropertyKey(descriptor.key), descriptor);
  }
}
function chat_status_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) chat_status_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) chat_status_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function chat_status_toPropertyKey(arg) {
  var key = chat_status_toPrimitive(arg, "string");
  return chat_status_typeof(key) === "symbol" ? key : String(key);
}
function chat_status_toPrimitive(input, hint) {
  if (chat_status_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (chat_status_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function chat_status_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    chat_status_get = Reflect.get.bind();
  } else {
    chat_status_get = function _get(target, property, receiver) {
      var base = chat_status_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return chat_status_get.apply(this, arguments);
}
function chat_status_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = chat_status_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function chat_status_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) chat_status_setPrototypeOf(subClass, superClass);
}
function chat_status_setPrototypeOf(o, p) {
  chat_status_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return chat_status_setPrototypeOf(o, p);
}
function chat_status_createSuper(Derived) {
  var hasNativeReflectConstruct = chat_status_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = chat_status_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = chat_status_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return chat_status_possibleConstructorReturn(this, result);
  };
}
function chat_status_possibleConstructorReturn(self, call) {
  if (call && (chat_status_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 chat_status_assertThisInitialized(self);
}
function chat_status_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function chat_status_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 chat_status_getPrototypeOf(o) {
  chat_status_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return chat_status_getPrototypeOf(o);
}




var chat_status_u = public_converse.env.utils;
var ChatStatusModal = /*#__PURE__*/function (_BaseModal) {
  chat_status_inherits(ChatStatusModal, _BaseModal);
  var _super = chat_status_createSuper(ChatStatusModal);
  function ChatStatusModal() {
    chat_status_classCallCheck(this, ChatStatusModal);
    return _super.apply(this, arguments);
  }
  chat_status_createClass(ChatStatusModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      chat_status_get(chat_status_getPrototypeOf(ChatStatusModal.prototype), "initialize", this).call(this);
      this.render();
      this.addEventListener('shown.bs.modal', function () {
        _this.querySelector('input[name="status_message"]').focus();
      }, false);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return chat_status_modal(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Change chat status');
    }
  }, {
    key: "clearStatusMessage",
    value: function clearStatusMessage(ev) {
      if (ev && ev.preventDefault) {
        ev.preventDefault();
        chat_status_u.hideElement(this.querySelector('.clear-input'));
      }
      var roster_filter = this.querySelector('input[name="status_message"]');
      roster_filter.value = '';
    }
  }, {
    key: "onFormSubmitted",
    value: function onFormSubmitted(ev) {
      ev.preventDefault();
      var data = new FormData(ev.target);
      this.model.save({
        'status_message': data.get('status_message'),
        'status': data.get('chat_status')
      });
      this.modal.hide();
    }
  }]);
  return ChatStatusModal;
}(modal_modal);

shared_converse.ChatStatusModal = ChatStatusModal;
shared_api.elements.define('converse-chat-status-modal', ChatStatusModal);
;// CONCATENATED MODULE: ./src/shared/components/image-picker.js
function image_picker_typeof(obj) {
  "@babel/helpers - typeof";

  return image_picker_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;
  }, image_picker_typeof(obj);
}
var image_picker_templateObject;
function image_picker_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function image_picker_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function image_picker_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, image_picker_toPropertyKey(descriptor.key), descriptor);
  }
}
function image_picker_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) image_picker_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) image_picker_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function image_picker_toPropertyKey(arg) {
  var key = image_picker_toPrimitive(arg, "string");
  return image_picker_typeof(key) === "symbol" ? key : String(key);
}
function image_picker_toPrimitive(input, hint) {
  if (image_picker_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (image_picker_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function image_picker_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) image_picker_setPrototypeOf(subClass, superClass);
}
function image_picker_setPrototypeOf(o, p) {
  image_picker_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return image_picker_setPrototypeOf(o, p);
}
function image_picker_createSuper(Derived) {
  var hasNativeReflectConstruct = image_picker_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = image_picker_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = image_picker_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return image_picker_possibleConstructorReturn(this, result);
  };
}
function image_picker_possibleConstructorReturn(self, call) {
  if (call && (image_picker_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 image_picker_assertThisInitialized(self);
}
function image_picker_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function image_picker_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 image_picker_getPrototypeOf(o) {
  image_picker_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return image_picker_getPrototypeOf(o);
}




var i18n_profile_picture = __('Your profile picture');
var ImagePicker = /*#__PURE__*/function (_CustomElement) {
  image_picker_inherits(ImagePicker, _CustomElement);
  var _super = image_picker_createSuper(ImagePicker);
  function ImagePicker() {
    image_picker_classCallCheck(this, ImagePicker);
    return _super.apply(this, arguments);
  }
  image_picker_createClass(ImagePicker, [{
    key: "render",
    value: function render() {
      return (0,external_lit_namespaceObject.html)(image_picker_templateObject || (image_picker_templateObject = image_picker_taggedTemplateLiteral(["\n            <a class=\"change-avatar\" @click=", " title=\"", "\">\n                <converse-avatar class=\"avatar\" .data=", " height=\"", "\" width=\"", "\"></converse-avatar>\n            </a>\n            <input @change=", " class=\"hidden\" name=\"image\" type=\"file\"/>\n        "])), this.openFileSelection, i18n_profile_picture, this.data, this.height, this.width, this.updateFilePreview);
    }
  }, {
    key: "openFileSelection",
    value: function openFileSelection(ev) {
      ev.preventDefault();
      this.querySelector('input[type="file"]').click();
    }
  }, {
    key: "updateFilePreview",
    value: function updateFilePreview(ev) {
      var _this = this;
      var file = ev.target.files[0];
      var reader = new FileReader();
      reader.onloadend = function () {
        _this.data = {
          'data_uri': reader.result,
          'image_type': file.type
        };
      };
      reader.readAsDataURL(file);
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'height': {
          type: Number
        },
        'data': {
          type: Object
        },
        'width': {
          type: Number
        }
      };
    }
  }]);
  return ImagePicker;
}(CustomElement);

shared_api.elements.define('converse-image-picker', ImagePicker);
;// CONCATENATED MODULE: ./src/plugins/profile/templates/profile_modal.js
function profile_modal_typeof(obj) {
  "@babel/helpers - typeof";

  return profile_modal_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;
  }, profile_modal_typeof(obj);
}
var profile_modal_templateObject, profile_modal_templateObject2, profile_modal_templateObject3, profile_modal_templateObject4, profile_modal_templateObject5, profile_modal_templateObject6, profile_modal_templateObject7;
function profile_modal_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 profile_modal_objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? profile_modal_ownKeys(Object(source), !0).forEach(function (key) {
      profile_modal_defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : profile_modal_ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function profile_modal_defineProperty(obj, key, value) {
  key = profile_modal_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 profile_modal_toPropertyKey(arg) {
  var key = profile_modal_toPrimitive(arg, "string");
  return profile_modal_typeof(key) === "symbol" ? key : String(key);
}
function profile_modal_toPrimitive(input, hint) {
  if (profile_modal_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (profile_modal_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function profile_modal_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var tplOmemoPage = function tplOmemoPage(el) {
  return (0,external_lit_namespaceObject.html)(profile_modal_templateObject || (profile_modal_templateObject = profile_modal_taggedTemplateLiteral(["\n    <div class=\"tab-pane ", "\" id=\"omemo-tabpanel\" role=\"tabpanel\" aria-labelledby=\"omemo-tab\">\n        ", "\n    </div>"])), el.tab === 'omemo' ? 'active' : '', el.tab === 'omemo' ? (0,external_lit_namespaceObject.html)(profile_modal_templateObject2 || (profile_modal_templateObject2 = profile_modal_taggedTemplateLiteral(["<converse-omemo-profile></converse-omemo-profile>"]))) : '');
};
/* harmony default export */ const profile_modal = (function (el) {
  var _converse$pluggable$p, _converse$pluggable$p2;
  var o = profile_modal_objectSpread(profile_modal_objectSpread({}, el.model.toJSON()), el.model.vcard.toJSON());
  var i18n_email = __('Email');
  var i18n_fullname = __('Full Name');
  var i18n_jid = __('XMPP Address');
  var i18n_nickname = __('Nickname');
  var i18n_role = __('Role');
  var i18n_save = __('Save and close');
  var i18n_role_help = __('Use commas to separate multiple roles. Your roles are shown next to your name on your chat messages.');
  var i18n_url = __('URL');
  var i18n_omemo = __('OMEMO');
  var i18n_profile = __('Profile');
  var ii18n_reset_password = __('Reset Password');
  var navigation_tabs = [(0,external_lit_namespaceObject.html)(profile_modal_templateObject3 || (profile_modal_templateObject3 = profile_modal_taggedTemplateLiteral(["<li role=\"presentation\" class=\"nav-item\">\n            <a class=\"nav-link ", "\"\n               id=\"profile-tab\"\n               href=\"#profile-tabpanel\"\n               aria-controls=\"profile-tabpanel\"\n               role=\"tab\"\n               @click=", "\n               data-name=\"profile\"\n               data-toggle=\"tab\">", "</a>\n            </li>"])), el.tab === "profile" ? "active" : "", function (ev) {
    return el.switchTab(ev);
  }, i18n_profile)];
  navigation_tabs.push((0,external_lit_namespaceObject.html)(profile_modal_templateObject4 || (profile_modal_templateObject4 = profile_modal_taggedTemplateLiteral(["<li role=\"presentation\" class=\"nav-item\">\n                <a class=\"nav-link ", "\"\n                id=\"passwordreset-tab\"\n                href=\"#passwordreset-tabpanel\"\n                aria-controls=\"passwordreset-tabpanel\"\n                role=\"tab\"\n                @click=", "\n                data-name=\"passwordreset\"\n                data-toggle=\"tab\">", "</a>\n        </li>"])), el.tab === "passwordreset" ? "active" : "", function (ev) {
    return el.switchTab(ev);
  }, ii18n_reset_password));
  if ((_converse$pluggable$p = shared_converse.pluggable.plugins['converse-omemo']) !== null && _converse$pluggable$p !== void 0 && _converse$pluggable$p.enabled(shared_converse)) {
    navigation_tabs.push((0,external_lit_namespaceObject.html)(profile_modal_templateObject5 || (profile_modal_templateObject5 = profile_modal_taggedTemplateLiteral(["<li role=\"presentation\" class=\"nav-item\">\n                <a class=\"nav-link ", "\"\n                   id=\"omemo-tab\"\n                   href=\"#omemo-tabpanel\"\n                   aria-controls=\"omemo-tabpanel\"\n                   role=\"tab\"\n                   @click=", "\n                   data-name=\"omemo\"\n                   data-toggle=\"tab\">", "</a>\n            </li>"])), el.tab === "omemo" ? "active" : "", function (ev) {
      return el.switchTab(ev);
    }, i18n_omemo));
  }
  return (0,external_lit_namespaceObject.html)(profile_modal_templateObject6 || (profile_modal_templateObject6 = profile_modal_taggedTemplateLiteral(["\n        <ul class=\"nav nav-pills justify-content-center\">", "</ul>\n        <div class=\"tab-content\">\n            <div class=\"tab-pane ", "\" id=\"profile-tabpanel\" role=\"tabpanel\" aria-labelledby=\"profile-tab\">\n                <form class=\"converse-form converse-form--modal profile-form\" action=\"#\" @submit=", ">\n                    <div class=\"row\">\n                        <div class=\"col-auto\">\n                            <converse-image-picker .data=\"", "\" width=\"128\" height=\"128\"></converse-image-picker>\n                        </div>\n                        <div class=\"col\">\n                            <div class=\"form-group\">\n                                <label class=\"col-form-label\">", ":</label>\n                                <div>", "</div>\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"form-group\">\n                        <label for=\"vcard-fullname\" class=\"col-form-label\">", ":</label>\n                        <input id=\"vcard-fullname\" type=\"text\" class=\"form-control\" name=\"fn\" value=\"", "\"/>\n                    </div>\n                    <div class=\"form-group\">\n                        <label for=\"vcard-nickname\" class=\"col-form-label\">", ":</label>\n                        <input id=\"vcard-nickname\" type=\"text\" class=\"form-control\" name=\"nickname\" value=\"", "\"/>\n                    </div>\n                    <div class=\"form-group\">\n                        <label for=\"vcard-url\" class=\"col-form-label\">", ":</label>\n                        <input id=\"vcard-url\" type=\"url\" class=\"form-control\" name=\"url\" value=\"", "\"/>\n                    </div>\n                    <div class=\"form-group\">\n                        <label for=\"vcard-email\" class=\"col-form-label\">", ":</label>\n                        <input id=\"vcard-email\" type=\"email\" class=\"form-control\" name=\"email\" value=\"", "\"/>\n                    </div>\n                    <div class=\"form-group\">\n                        <label for=\"vcard-role\" class=\"col-form-label\">", ":</label>\n                        <input id=\"vcard-role\" type=\"text\" class=\"form-control\" name=\"role\" value=\"", "\" aria-describedby=\"vcard-role-help\"/>\n                        <small id=\"vcard-role-help\" class=\"form-text text-muted\">", "</small>\n                    </div>\n                    <hr/>\n                    <div class=\"form-group\">\n                        <button type=\"submit\" class=\"save-form btn btn-primary\">", "</button>\n                    </div>\n                </form>\n            </div>\n\n            <div class=\"tab-pane ", "\" id=\"passwordreset-tabpanel\" role=\"tabpanel\" aria-labelledby=\"passwordreset-tab\">\n                ", "\n            </div>\n\n            ", "\n        </div>\n    </div>"])), navigation_tabs, el.tab === 'profile' ? 'active' : '', function (ev) {
    return el.onFormSubmitted(ev);
  }, {
    image: o.image,
    image_type: o.image_type
  }, i18n_jid, o.jid, i18n_fullname, o.fullname || '', i18n_nickname, o.nickname || '', i18n_url, o.url || '', i18n_email, o.email || '', i18n_role, o.role || '', i18n_role_help, i18n_save, el.tab === 'passwordreset' ? 'active' : '', el.tab === 'passwordreset' ? (0,external_lit_namespaceObject.html)(profile_modal_templateObject7 || (profile_modal_templateObject7 = profile_modal_taggedTemplateLiteral(["<converse-change-password-form></converse-change-password-form>"]))) : '', (_converse$pluggable$p2 = shared_converse.pluggable.plugins['converse-omemo']) !== null && _converse$pluggable$p2 !== void 0 && _converse$pluggable$p2.enabled(shared_converse) ? tplOmemoPage(el) : '');
});
// EXTERNAL MODULE: ./node_modules/client-compress/dist/index.js
var dist = __webpack_require__(5542);
var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
;// CONCATENATED MODULE: ./src/plugins/profile/templates/password-reset.js
var password_reset_templateObject, password_reset_templateObject2, password_reset_templateObject3;
function password_reset_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const password_reset = (function (el) {
  var i18n_submit = __('Submit');
  var i18n_passwords_must_match = __('The new passwords must match');
  var i18n_new_password = __('New password');
  var i18n_confirm_password = __('Confirm new password');
  return (0,external_lit_namespaceObject.html)(password_reset_templateObject || (password_reset_templateObject = password_reset_taggedTemplateLiteral(["<form class=\"converse-form passwordreset-form\" method=\"POST\" @submit=", ">\n        ", "\n\n        <div class=\"form-group\">\n            <label for=\"converse_password_reset_new\">", "</label>\n            <input\n                class=\"form-control ", "\"\n                type=\"password\"\n                value=\"\"\n                name=\"password\"\n                required=\"required\"\n                id=\"converse_password_reset_new\"\n                autocomplete=\"new-password\"\n                minlength=\"8\"\n                ?disabled=\"", "\"\n            />\n        </div>\n        <div class=\"form-group\">\n            <label for=\"converse_password_reset_check\">", "</label>\n            <input\n                class=\"form-control ", "\"\n                type=\"password\"\n                value=\"\"\n                name=\"password_check\"\n                required=\"required\"\n                id=\"converse_password_reset_check\"\n                autocomplete=\"new-password\"\n                minlength=\"8\"\n                ?disabled=\"", "\"\n                @input=", "\n            />\n            ", "\n        </div>\n\n        <input class=\"save-form btn btn-primary\"\n               type=\"submit\"\n               value=", "\n               ?disabled=\"", "\" />\n    </form>"])), function (ev) {
    return el.onSubmit(ev);
  }, el.alert_message ? (0,external_lit_namespaceObject.html)(password_reset_templateObject2 || (password_reset_templateObject2 = password_reset_taggedTemplateLiteral(["<div class=\"alert alert-danger\" role=\"alert\">", "</div>"])), el.alert_message) : '', i18n_new_password, el.passwords_mismatched ? 'error' : '', el.alert_message, i18n_confirm_password, el.passwords_mismatched ? 'error' : '', el.alert_message, function (ev) {
    return el.checkPasswordsMatch(ev);
  }, el.passwords_mismatched ? (0,external_lit_namespaceObject.html)(password_reset_templateObject3 || (password_reset_templateObject3 = password_reset_taggedTemplateLiteral(["<span class=\"error\">", "</span>"])), i18n_passwords_must_match) : '', i18n_submit, el.alert_message);
});
;// CONCATENATED MODULE: ./src/plugins/profile/password-reset.js
function password_reset_typeof(obj) {
  "@babel/helpers - typeof";

  return password_reset_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;
  }, password_reset_typeof(obj);
}
function password_reset_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  password_reset_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" == password_reset_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 password_reset_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 password_reset_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        password_reset_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        password_reset_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function password_reset_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function password_reset_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, password_reset_toPropertyKey(descriptor.key), descriptor);
  }
}
function password_reset_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) password_reset_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) password_reset_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function password_reset_toPropertyKey(arg) {
  var key = password_reset_toPrimitive(arg, "string");
  return password_reset_typeof(key) === "symbol" ? key : String(key);
}
function password_reset_toPrimitive(input, hint) {
  if (password_reset_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (password_reset_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function password_reset_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) password_reset_setPrototypeOf(subClass, superClass);
}
function password_reset_setPrototypeOf(o, p) {
  password_reset_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return password_reset_setPrototypeOf(o, p);
}
function password_reset_createSuper(Derived) {
  var hasNativeReflectConstruct = password_reset_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = password_reset_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = password_reset_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return password_reset_possibleConstructorReturn(this, result);
  };
}
function password_reset_possibleConstructorReturn(self, call) {
  if (call && (password_reset_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 password_reset_assertThisInitialized(self);
}
function password_reset_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function password_reset_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 password_reset_getPrototypeOf(o) {
  password_reset_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return password_reset_getPrototypeOf(o);
}





var password_reset_converse$env = public_converse.env,
  password_reset_Strophe = password_reset_converse$env.Strophe,
  password_reset_$iq = password_reset_converse$env.$iq,
  password_reset_sizzle = password_reset_converse$env.sizzle,
  password_reset_u = password_reset_converse$env.u;
var PasswordReset = /*#__PURE__*/function (_CustomElement) {
  password_reset_inherits(PasswordReset, _CustomElement);
  var _super = password_reset_createSuper(PasswordReset);
  function PasswordReset() {
    password_reset_classCallCheck(this, PasswordReset);
    return _super.apply(this, arguments);
  }
  password_reset_createClass(PasswordReset, [{
    key: "initialize",
    value: function initialize() {
      this.passwords_mismatched = false;
      this.alert_message = '';
    }
  }, {
    key: "render",
    value: function render() {
      return password_reset(this);
    }
  }, {
    key: "checkPasswordsMatch",
    value: function checkPasswordsMatch(ev) {
      var _ev$target$form;
      var form_data = new FormData((_ev$target$form = ev.target.form) !== null && _ev$target$form !== void 0 ? _ev$target$form : ev.target);
      var password = form_data.get('password');
      var password_check = form_data.get('password_check');
      this.passwords_mismatched = password && password !== password_check;
      return this.passwords_mismatched;
    }
  }, {
    key: "onSubmit",
    value: function () {
      var _onSubmit = password_reset_asyncToGenerator( /*#__PURE__*/password_reset_regeneratorRuntime().mark(function _callee(ev) {
        var iq, iq_response, username, data, password, reset_iq, iq_result;
        return password_reset_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev.preventDefault();
              if (!this.checkPasswordsMatch(ev)) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return");
            case 3:
              iq = password_reset_$iq({
                'type': 'get',
                'to': shared_converse.domain
              }).c('query', {
                'xmlns': password_reset_Strophe.NS.REGISTER
              });
              _context.next = 6;
              return shared_api.sendIQ(iq);
            case 6:
              iq_response = _context.sent;
              if (!(iq_response === null)) {
                _context.next = 12;
                break;
              }
              this.alert_message = __('Timeout error');
              return _context.abrupt("return");
            case 12:
              if (!password_reset_sizzle("error service-unavailable[xmlns=\"".concat(password_reset_Strophe.NS.STANZAS, "\"]"), iq_response).length) {
                _context.next = 17;
                break;
              }
              this.alert_message = __('Your server does not support in-band password reset');
              return _context.abrupt("return");
            case 17:
              if (!password_reset_u.isErrorStanza(iq_response)) {
                _context.next = 22;
                break;
              }
              this.alert_message = __('Your server responded with an unknown error, check the console for details');
              log.error("Could not set password");
              log.error(iq_response);
              return _context.abrupt("return");
            case 22:
              username = iq_response.querySelector('username').textContent;
              data = new FormData(ev.target);
              password = data.get('password');
              reset_iq = password_reset_$iq({
                'type': 'set',
                'to': shared_converse.domain
              }).c('query', {
                'xmlns': password_reset_Strophe.NS.REGISTER
              }).c('username', {}, username).c('password', {}, password);
              _context.next = 28;
              return shared_api.sendIQ(reset_iq);
            case 28:
              iq_result = _context.sent;
              if (iq_result === null) {
                this.alert_message = __('Timeout error while trying to set your password');
              } else if (password_reset_sizzle("error not-allowed[xmlns=\"".concat(password_reset_Strophe.NS.STANZAS, "\"]"), iq_result).length) {
                this.alert_message = __('Your server does not allow in-band password reset');
              } else if (password_reset_sizzle("error forbidden[xmlns=\"".concat(password_reset_Strophe.NS.STANZAS, "\"]"), iq_result).length) {
                this.alert_message = __('You are not allowed to change your password');
              } else if (password_reset_u.isErrorStanza(iq_result)) {
                this.alert_message = __('You are not allowed to change your password');
              } else {
                shared_api.alert('info', __('Success'), [__('Your new password has been set')]);
              }
            case 30:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function onSubmit(_x) {
        return _onSubmit.apply(this, arguments);
      }
      return onSubmit;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        passwords_mismatched: {
          type: Boolean
        },
        alert_message: {
          type: String
        }
      };
    }
  }]);
  return PasswordReset;
}(CustomElement);
shared_api.elements.define('converse-change-password-form', PasswordReset);
;// CONCATENATED MODULE: ./src/plugins/profile/modals/profile.js
function profile_typeof(obj) {
  "@babel/helpers - typeof";

  return profile_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;
  }, profile_typeof(obj);
}
function profile_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  profile_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" == profile_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 profile_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 profile_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        profile_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        profile_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function profile_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function profile_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, profile_toPropertyKey(descriptor.key), descriptor);
  }
}
function profile_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) profile_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) profile_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function profile_toPropertyKey(arg) {
  var key = profile_toPrimitive(arg, "string");
  return profile_typeof(key) === "symbol" ? key : String(key);
}
function profile_toPrimitive(input, hint) {
  if (profile_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (profile_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function profile_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    profile_get = Reflect.get.bind();
  } else {
    profile_get = function _get(target, property, receiver) {
      var base = profile_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return profile_get.apply(this, arguments);
}
function profile_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = profile_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function profile_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) profile_setPrototypeOf(subClass, superClass);
}
function profile_setPrototypeOf(o, p) {
  profile_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return profile_setPrototypeOf(o, p);
}
function profile_createSuper(Derived) {
  var hasNativeReflectConstruct = profile_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = profile_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = profile_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return profile_possibleConstructorReturn(this, result);
  };
}
function profile_possibleConstructorReturn(self, call) {
  if (call && (profile_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 profile_assertThisInitialized(self);
}
function profile_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function profile_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 profile_getPrototypeOf(o) {
  profile_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return profile_getPrototypeOf(o);
}







var compress = new (dist_default())({
  targetSize: 0.1,
  quality: 0.75,
  maxWidth: 256,
  maxHeight: 256
});
var ProfileModal = /*#__PURE__*/function (_BaseModal) {
  profile_inherits(ProfileModal, _BaseModal);
  var _super = profile_createSuper(ProfileModal);
  function ProfileModal(options) {
    var _this;
    profile_classCallCheck(this, ProfileModal);
    _this = _super.call(this, options);
    _this.tab = 'profile';
    return _this;
  }
  profile_createClass(ProfileModal, [{
    key: "initialize",
    value: function initialize() {
      profile_get(profile_getPrototypeOf(ProfileModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', this.render);
      /**
       * Triggered when the _converse.ProfileModal has been created and initialized.
       * @event _converse#profileModalInitialized
       * @type { _converse.XMPPStatus }
       * @example _converse.api.listen.on('profileModalInitialized', status => { ... });
       */
      shared_api.trigger('profileModalInitialized', this.model);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return profile_modal(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Your Profile');
    }
  }, {
    key: "setVCard",
    value: function () {
      var _setVCard = profile_asyncToGenerator( /*#__PURE__*/profile_regeneratorRuntime().mark(function _callee(data) {
        return profile_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return shared_api.vcard.set(shared_converse.bare_jid, data);
            case 3:
              _context.next = 10;
              break;
            case 5:
              _context.prev = 5;
              _context.t0 = _context["catch"](0);
              log.fatal(_context.t0);
              this.alert([__("Sorry, an error happened while trying to save your profile data."), __("You can check your browser's developer console for any error output.")].join(" "));
              return _context.abrupt("return");
            case 10:
              this.modal.hide();
            case 11:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[0, 5]]);
      }));
      function setVCard(_x) {
        return _setVCard.apply(this, arguments);
      }
      return setVCard;
    }()
  }, {
    key: "onFormSubmitted",
    value: function onFormSubmitted(ev) {
      var _this2 = this;
      ev.preventDefault();
      var reader = new FileReader();
      var form_data = new FormData(ev.target);
      var image_file = form_data.get('image');
      var data = {
        'fn': form_data.get('fn'),
        'nickname': form_data.get('nickname'),
        'role': form_data.get('role'),
        'email': form_data.get('email'),
        'url': form_data.get('url')
      };
      if (!image_file.size) {
        Object.assign(data, {
          'image': this.model.vcard.get('image'),
          'image_type': this.model.vcard.get('image_type')
        });
        this.setVCard(data);
      } else {
        var files = [image_file];
        compress.compress(files).then(function (conversions) {
          var photo = conversions[0].photo;
          reader.onloadend = function () {
            Object.assign(data, {
              'image': btoa(reader.result),
              'image_type': image_file.type
            });
            _this2.setVCard(data);
          };
          reader.readAsBinaryString(photo.data);
        });
      }
    }
  }]);
  return ProfileModal;
}(modal_modal);

shared_api.elements.define('converse-profile-modal', ProfileModal);
;// CONCATENATED MODULE: ./src/plugins/profile/modals/templates/user-settings.js
var user_settings_templateObject, user_settings_templateObject2, user_settings_templateObject3, user_settings_templateObject4;
function user_settings_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





var user_settings_tplNavigation = function tplNavigation(el) {
  var i18n_about = __('About');
  var i18n_commands = __('Commands');
  return (0,external_lit_namespaceObject.html)(user_settings_templateObject || (user_settings_templateObject = user_settings_taggedTemplateLiteral(["\n        <ul class=\"nav nav-pills justify-content-center\">\n            <li role=\"presentation\" class=\"nav-item\">\n                <a class=\"nav-link ", "\"\n                   id=\"about-tab\"\n                   href=\"#about-tabpanel\"\n                   aria-controls=\"about-tabpanel\"\n                   role=\"tab\"\n                   data-toggle=\"tab\"\n                   data-name=\"about\"\n                   @click=", ">", "</a>\n            </li>\n            <li role=\"presentation\" class=\"nav-item\">\n                <a class=\"nav-link ", "\"\n                   id=\"commands-tab\"\n                   href=\"#commands-tabpanel\"\n                   aria-controls=\"commands-tabpanel\"\n                   role=\"tab\"\n                   data-toggle=\"tab\"\n                   data-name=\"commands\"\n                   @click=", ">", "</a>\n            </li>\n        </ul>\n    "])), el.tab === "about" ? "active" : "", function (ev) {
    return el.switchTab(ev);
  }, i18n_about, el.tab === "commands" ? "active" : "", function (ev) {
    return el.switchTab(ev);
  }, i18n_commands);
};
/* harmony default export */ const templates_user_settings = (function (el) {
  var first_subtitle = __('%1$s Open Source %2$s XMPP chat client brought to you by %3$s Opkode %2$s', '<a target="_blank" rel="nofollow" href="https://conversejs.org">', '</a>', '<a target="_blank" rel="nofollow" href="https://opkode.com">');
  var second_subtitle = __('%1$s Translate %2$s it into your own language', '<a target="_blank" rel="nofollow" href="https://hosted.weblate.org/projects/conversejs/#languages">', '</a>');
  var show_client_info = shared_api.settings.get('show_client_info');
  var allow_adhoc_commands = shared_api.settings.get('allow_adhoc_commands');
  var show_both_tabs = show_client_info && allow_adhoc_commands;
  return (0,external_lit_namespaceObject.html)(user_settings_templateObject2 || (user_settings_templateObject2 = user_settings_taggedTemplateLiteral(["\n        ", "\n\n        <div class=\"tab-content\">\n            ", "\n\n            ", "\n        </div>\n"])), show_both_tabs ? user_settings_tplNavigation(el) : '', show_client_info ? (0,external_lit_namespaceObject.html)(user_settings_templateObject3 || (user_settings_templateObject3 = user_settings_taggedTemplateLiteral(["\n                <div class=\"tab-pane tab-pane--columns ", "\"\n                        id=\"about-tabpanel\" role=\"tabpanel\" aria-labelledby=\"about-tab\">\n\n                    <span class=\"modal-alert\"></span>\n                    <br/>\n                    <div class=\"container\">\n                        <h6 class=\"brand-heading\">Converse</h6>\n                        <p class=\"brand-subtitle\">", "</p>\n                        <p class=\"brand-subtitle\">", "</p>\n                        <p class=\"brand-subtitle\">", "</p>\n                    </div>\n                </div>"])), el.tab === 'about' ? 'active' : '', shared_converse.VERSION_NAME, unsafe_html_o(purify_default().sanitize(first_subtitle)), unsafe_html_o(purify_default().sanitize(second_subtitle))) : '', allow_adhoc_commands ? (0,external_lit_namespaceObject.html)(user_settings_templateObject4 || (user_settings_templateObject4 = user_settings_taggedTemplateLiteral(["\n                <div class=\"tab-pane tab-pane--columns ", "\"\n                        id=\"commands-tabpanel\"\n                        role=\"tabpanel\"\n                        aria-labelledby=\"commands-tab\">\n                    <converse-adhoc-commands/>\n                </div> "])), el.tab === 'commands' ? 'active' : '') : '');
});
;// CONCATENATED MODULE: ./src/plugins/profile/modals/user-settings.js
function user_settings_typeof(obj) {
  "@babel/helpers - typeof";

  return user_settings_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;
  }, user_settings_typeof(obj);
}
function user_settings_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function user_settings_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, user_settings_toPropertyKey(descriptor.key), descriptor);
  }
}
function user_settings_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) user_settings_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) user_settings_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function user_settings_toPropertyKey(arg) {
  var key = user_settings_toPrimitive(arg, "string");
  return user_settings_typeof(key) === "symbol" ? key : String(key);
}
function user_settings_toPrimitive(input, hint) {
  if (user_settings_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (user_settings_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function user_settings_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) user_settings_setPrototypeOf(subClass, superClass);
}
function user_settings_setPrototypeOf(o, p) {
  user_settings_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return user_settings_setPrototypeOf(o, p);
}
function user_settings_createSuper(Derived) {
  var hasNativeReflectConstruct = user_settings_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = user_settings_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = user_settings_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return user_settings_possibleConstructorReturn(this, result);
  };
}
function user_settings_possibleConstructorReturn(self, call) {
  if (call && (user_settings_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 user_settings_assertThisInitialized(self);
}
function user_settings_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function user_settings_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 user_settings_getPrototypeOf(o) {
  user_settings_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return user_settings_getPrototypeOf(o);
}




var UserSettingsModal = /*#__PURE__*/function (_BaseModal) {
  user_settings_inherits(UserSettingsModal, _BaseModal);
  var _super = user_settings_createSuper(UserSettingsModal);
  function UserSettingsModal(options) {
    var _this;
    user_settings_classCallCheck(this, UserSettingsModal);
    _this = _super.call(this, options);
    var show_client_info = shared_api.settings.get('show_client_info');
    var allow_adhoc_commands = shared_api.settings.get('allow_adhoc_commands');
    var show_both_tabs = show_client_info && allow_adhoc_commands;
    if (show_both_tabs || show_client_info) {
      _this.tab = 'about';
    } else if (allow_adhoc_commands) {
      _this.tab = 'commands';
    }
    return _this;
  }
  user_settings_createClass(UserSettingsModal, [{
    key: "renderModal",
    value: function renderModal() {
      return templates_user_settings(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Settings');
    }
  }]);
  return UserSettingsModal;
}(modal_modal);

shared_api.elements.define('converse-user-settings-modal', UserSettingsModal);
;// CONCATENATED MODULE: ./src/plugins/profile/utils.js
function profile_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return profile_utils_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;
  }, profile_utils_typeof(obj);
}
function profile_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  profile_utils_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" == profile_utils_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 profile_utils_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 profile_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        profile_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        profile_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var profile_utils_converse$env = public_converse.env,
  profile_utils_Strophe = profile_utils_converse$env.Strophe,
  profile_utils_$iq = profile_utils_converse$env.$iq,
  profile_utils_sizzle = profile_utils_converse$env.sizzle,
  profile_utils_u = profile_utils_converse$env.u;
function getPrettyStatus(stat) {
  if (stat === 'chat') {
    return __('online');
  } else if (stat === 'dnd') {
    return __('busy');
  } else if (stat === 'xa') {
    return __('away for long');
  } else if (stat === 'away') {
    return __('away');
  } else if (stat === 'offline') {
    return __('offline');
  } else {
    return __(stat) || __('online');
  }
}
function logOut(_x) {
  return _logOut.apply(this, arguments);
}
function _logOut() {
  _logOut = profile_utils_asyncToGenerator( /*#__PURE__*/profile_utils_regeneratorRuntime().mark(function _callee(ev) {
    var result;
    return profile_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          ev === null || ev === void 0 ? void 0 : ev.preventDefault();
          _context.next = 3;
          return shared_api.confirm(__("Are you sure you want to log out?"));
        case 3:
          result = _context.sent;
          if (result) {
            shared_api.user.logout();
          }
        case 5:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _logOut.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/plugins/profile/templates/profile.js
var profile_templateObject, profile_templateObject2, profile_templateObject3;
function profile_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}





function tplSignout() {
  var i18n_logout = __('Log out');
  return (0,external_lit_namespaceObject.html)(profile_templateObject || (profile_templateObject = profile_taggedTemplateLiteral(["<a class=\"controlbox-heading__btn logout align-self-center\" title=\"", "\" @click=", ">\n        <converse-icon class=\"fa fa-sign-out-alt\" size=\"1em\"></converse-icon>\n    </a>"])), i18n_logout, logOut);
}
function tplUserSettingsButton(o) {
  var i18n_details = __('Show details about this chat client');
  return (0,external_lit_namespaceObject.html)(profile_templateObject2 || (profile_templateObject2 = profile_taggedTemplateLiteral(["<a class=\"controlbox-heading__btn show-client-info align-self-center\" title=\"", "\" @click=", ">\n        <converse-icon class=\"fa fa-cog\" size=\"1em\"></converse-icon>\n    </a>"])), i18n_details, o.showUserSettingsModal);
}
/* harmony default export */ const profile = (function (el) {
  var _el$model$vcard, _el$model$vcard2;
  var chat_status = el.model.get('status') || 'offline';
  var status_message = el.model.get('status_message') || __("I am %1$s", getPrettyStatus(chat_status));
  var i18n_change_status = __('Click to change your chat status');
  var show_settings_button = shared_api.settings.get('show_client_info') || shared_api.settings.get('allow_adhoc_commands');
  var classes, color;
  if (chat_status === 'online') {
    classes = 'fa fa-circle chat-status';
    color = 'chat-status-online';
  } else if (chat_status === 'dnd') {
    classes = 'fa fa-minus-circle chat-status';
    color = 'chat-status-busy';
  } else if (chat_status === 'away') {
    classes = 'fa fa-circle chat-status';
    color = 'chat-status-away';
  } else {
    classes = 'fa fa-circle chat-status';
    color = 'subdued-color';
  }
  return (0,external_lit_namespaceObject.html)(profile_templateObject3 || (profile_templateObject3 = profile_taggedTemplateLiteral(["\n        <div class=\"userinfo controlbox-padded\">\n            <div class=\"controlbox-section profile d-flex\">\n                <a class=\"show-profile\" href=\"#\" @click=", ">\n                    <converse-avatar class=\"avatar align-self-center\"\n                        .data=", "\n                        nonce=", "\n                        height=\"40\" width=\"40\"></converse-avatar>\n                </a>\n                <span class=\"username w-100 align-self-center\">", "</span>\n                ", "\n                ", "\n            </div>\n            <div class=\"d-flex xmpp-status\">\n                <a class=\"change-status\" title=\"", "\" data-toggle=\"modal\" data-target=\"#changeStatusModal\" @click=", ">\n                    <span class=\"", " w-100 align-self-center\" data-value=\"", "\">\n                    <converse-icon color=\"var(--", ")\" style=\"margin-top: -0.1em\" size=\"0.82em\" class=\"", "\"></converse-icon> ", "</span>\n                </a>\n            </div>\n        </div>"])), el.showProfileModal, (_el$model$vcard = el.model.vcard) === null || _el$model$vcard === void 0 ? void 0 : _el$model$vcard.attributes, (_el$model$vcard2 = el.model.vcard) === null || _el$model$vcard2 === void 0 ? void 0 : _el$model$vcard2.get('vcard_updated'), el.model.getDisplayName(), show_settings_button ? tplUserSettingsButton(el) : '', shared_api.settings.get('allow_logout') ? tplSignout() : '', i18n_change_status, el.showStatusChangeModal, chat_status, chat_status, color, classes, status_message);
});
;// CONCATENATED MODULE: ./src/plugins/profile/statusview.js
function statusview_typeof(obj) {
  "@babel/helpers - typeof";

  return statusview_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;
  }, statusview_typeof(obj);
}
function statusview_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function statusview_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, statusview_toPropertyKey(descriptor.key), descriptor);
  }
}
function statusview_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) statusview_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) statusview_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function statusview_toPropertyKey(arg) {
  var key = statusview_toPrimitive(arg, "string");
  return statusview_typeof(key) === "symbol" ? key : String(key);
}
function statusview_toPrimitive(input, hint) {
  if (statusview_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (statusview_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function statusview_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) statusview_setPrototypeOf(subClass, superClass);
}
function statusview_setPrototypeOf(o, p) {
  statusview_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return statusview_setPrototypeOf(o, p);
}
function statusview_createSuper(Derived) {
  var hasNativeReflectConstruct = statusview_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = statusview_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = statusview_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return statusview_possibleConstructorReturn(this, result);
  };
}
function statusview_possibleConstructorReturn(self, call) {
  if (call && (statusview_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 statusview_assertThisInitialized(self);
}
function statusview_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function statusview_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 statusview_getPrototypeOf(o) {
  statusview_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return statusview_getPrototypeOf(o);
}



var Profile = /*#__PURE__*/function (_CustomElement) {
  statusview_inherits(Profile, _CustomElement);
  var _super = statusview_createSuper(Profile);
  function Profile() {
    statusview_classCallCheck(this, Profile);
    return _super.apply(this, arguments);
  }
  statusview_createClass(Profile, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.model = shared_converse.xmppstatus;
      this.listenTo(this.model, "change", function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, "vcard:add", function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, "vcard:change", function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      return profile(this);
    }
  }, {
    key: "showProfileModal",
    value: function showProfileModal(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      shared_api.modal.show('converse-profile-modal', {
        model: this.model
      }, ev);
    }
  }, {
    key: "showStatusChangeModal",
    value: function showStatusChangeModal(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      shared_api.modal.show('converse-chat-status-modal', {
        model: this.model
      }, ev);
    }
  }, {
    key: "showUserSettingsModal",
    value: function showUserSettingsModal(ev) {
      ev === null || ev === void 0 ? void 0 : ev.preventDefault();
      shared_api.modal.show('converse-user-settings-modal', {
        model: this.model,
        _converse: shared_converse
      }, ev);
    }
  }]);
  return Profile;
}(CustomElement);
shared_api.elements.define('converse-user-profile', Profile);
;// CONCATENATED MODULE: ./src/plugins/profile/index.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */








public_converse.plugins.add('converse-profile', {
  dependencies: ['converse-status', 'converse-modal', 'converse-vcard', 'converse-chatboxviews', 'converse-adhoc-views'],
  initialize: function initialize() {
    shared_api.settings.extend({
      'show_client_info': true
    });
  }
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/concat.js





/**
 * Creates a new array concatenating `array` with any additional arrays
 * and/or values.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to concatenate.
 * @param {...*} [values] The values to concatenate.
 * @returns {Array} Returns the new concatenated array.
 * @example
 *
 * var array = [1];
 * var other = _.concat(array, 2, [3], [[4]]);
 *
 * console.log(other);
 * // => [1, 2, 3, [4]]
 *
 * console.log(array);
 * // => [1]
 */
function concat() {
  var length = arguments.length;
  if (!length) {
    return [];
  }
  var args = Array(length - 1),
    array = arguments[0],
    index = length;
  while (index--) {
    args[index - 1] = arguments[index];
  }
  return _arrayPush(lodash_es_isArray(array) ? _copyArray(array) : [array], _baseFlatten(args, 1));
}
/* harmony default export */ const lodash_es_concat = (concat);
;// CONCATENATED MODULE: ./src/plugins/omemo/consts.js
var UNDECIDED = 0;
var TRUSTED = 1;
var UNTRUSTED = -1;
var TAG_LENGTH = 128;
var KEY_ALGO = {
  'name': 'AES-GCM',
  'length': 128
};
;// CONCATENATED MODULE: ./src/utils/file.js
var MIMETYPES_MAP = {
  'aac': 'audio/aac',
  'abw': 'application/x-abiword',
  'arc': 'application/x-freearc',
  'avi': 'video/x-msvideo',
  'azw': 'application/vnd.amazon.ebook',
  'bin': 'application/octet-stream',
  'bmp': 'image/bmp',
  'bz': 'application/x-bzip',
  'bz2': 'application/x-bzip2',
  'cda': 'application/x-cdf',
  'csh': 'application/x-csh',
  'css': 'text/css',
  'csv': 'text/csv',
  'doc': 'application/msword',
  'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'eot': 'application/vnd.ms-fontobject',
  'epub': 'application/epub+zip',
  'gif': 'image/gif',
  'gz': 'application/gzip',
  'htm': 'text/html',
  'html': 'text/html',
  'ico': 'image/vnd.microsoft.icon',
  'ics': 'text/calendar',
  'jar': 'application/java-archive',
  'jpeg': 'image/jpeg',
  'jpg': 'image/jpeg',
  'js': 'text/javascript',
  'json': 'application/json',
  'jsonld': 'application/ld+json',
  'm4a': 'audio/mp4',
  'mid': 'audio/midi',
  'midi': 'audio/midi',
  'mjs': 'text/javascript',
  'mp3': 'audio/mpeg',
  'mp4': 'video/mp4',
  'mpeg': 'video/mpeg',
  'mpkg': 'application/vnd.apple.installer+xml',
  'odp': 'application/vnd.oasis.opendocument.presentation',
  'ods': 'application/vnd.oasis.opendocument.spreadsheet',
  'odt': 'application/vnd.oasis.opendocument.text',
  'oga': 'audio/ogg',
  'ogv': 'video/ogg',
  'ogx': 'application/ogg',
  'opus': 'audio/opus',
  'otf': 'font/otf',
  'png': 'image/png',
  'pdf': 'application/pdf',
  'php': 'application/x-httpd-php',
  'ppt': 'application/vnd.ms-powerpoint',
  'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'rar': 'application/vnd.rar',
  'rtf': 'application/rtf',
  'sh': 'application/x-sh',
  'svg': 'image/svg+xml',
  'swf': 'application/x-shockwave-flash',
  'tar': 'application/x-tar',
  'tif': 'image/tiff',
  'tiff': 'image/tiff',
  'ts': 'video/mp2t',
  'ttf': 'font/ttf',
  'txt': 'text/plain',
  'vsd': 'application/vnd.visio',
  'wav': 'audio/wav',
  'weba': 'audio/webm',
  'webm': 'video/webm',
  'webp': 'image/webp',
  'woff': 'font/woff',
  'woff2': 'font/woff2',
  'xhtml': 'application/xhtml+xml',
  'xls': 'application/vnd.ms-excel',
  'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'xml': 'text/xml',
  'xul': 'application/vnd.mozilla.xul+xml',
  'zip': 'application/zip',
  '3gp': 'video/3gpp',
  '3g2': 'video/3gpp2',
  '7z': 'application/x-7z-compressed'
};
;// CONCATENATED MODULE: ./src/plugins/omemo/utils.js
function omemo_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return omemo_utils_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;
  }, omemo_utils_typeof(obj);
}
var omemo_utils_templateObject, omemo_utils_templateObject2, omemo_utils_templateObject3;
function omemo_utils_toConsumableArray(arr) {
  return omemo_utils_arrayWithoutHoles(arr) || omemo_utils_iterableToArray(arr) || omemo_utils_unsupportedIterableToArray(arr) || omemo_utils_nonIterableSpread();
}
function omemo_utils_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function omemo_utils_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function omemo_utils_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return omemo_utils_arrayLikeToArray(arr);
}
function utils_slicedToArray(arr, i) {
  return utils_arrayWithHoles(arr) || utils_iterableToArrayLimit(arr, i) || omemo_utils_unsupportedIterableToArray(arr, i) || utils_nonIterableRest();
}
function utils_nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function omemo_utils_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return omemo_utils_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 omemo_utils_arrayLikeToArray(o, minLen);
}
function omemo_utils_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 utils_iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function utils_arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function omemo_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  omemo_utils_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" == omemo_utils_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 omemo_utils_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function omemo_utils_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 omemo_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        omemo_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        omemo_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/* global libsignal */

















var omemo_utils_converse$env = public_converse.env,
  omemo_utils_Strophe = omemo_utils_converse$env.Strophe,
  utils_URI = omemo_utils_converse$env.URI,
  omemo_utils_sizzle = omemo_utils_converse$env.sizzle,
  omemo_utils_u = omemo_utils_converse$env.u;
function formatFingerprint(fp) {
  fp = fp.replace(/^05/, '');
  for (var i = 1; i < 8; i++) {
    var idx = i * 8 + i - 1;
    fp = fp.slice(0, idx) + ' ' + fp.slice(idx);
  }
  return fp;
}
function handleMessageSendError(e, chat) {
  if (e.name === 'IQError') {
    chat.save('omemo_supported', false);
    var err_msgs = [];
    if (omemo_utils_sizzle("presence-subscription-required[xmlns=\"".concat(omemo_utils_Strophe.NS.PUBSUB_ERROR, "\"]"), e.iq).length) {
      err_msgs.push(__("Sorry, we're unable to send an encrypted message because %1$s " + 'requires you to be subscribed to their presence in order to see their OMEMO information', e.iq.getAttribute('from')));
    } else if (omemo_utils_sizzle("remote-server-not-found[xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"]", e.iq).length) {
      err_msgs.push(__("Sorry, we're unable to send an encrypted message because the remote server for %1$s could not be found", e.iq.getAttribute('from')));
    } else {
      err_msgs.push(__('Unable to send an encrypted message due to an unexpected error.'));
      err_msgs.push(e.iq.outerHTML);
    }
    shared_api.alert('error', __('Error'), err_msgs);
  } else if (e.user_facing) {
    shared_api.alert('error', __('Error'), [e.message]);
  }
  throw e;
}
function getOutgoingMessageAttributes(chat, attrs) {
  if (chat.get('omemo_active') && attrs.body) {
    attrs['is_encrypted'] = true;
    attrs['plaintext'] = attrs.body;
    attrs['body'] = __('This is an OMEMO encrypted message which your client doesn’t seem to support. ' + 'Find more information on https://conversations.im/omemo');
  }
  return attrs;
}
function encryptMessage(_x) {
  return _encryptMessage.apply(this, arguments);
}
function _encryptMessage() {
  _encryptMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee2(plaintext) {
    var iv, key, algo, encrypted, length, ciphertext, tag, exported_key;
    return omemo_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          // The client MUST use fresh, randomly generated key/IV pairs
          // with AES-128 in Galois/Counter Mode (GCM).
          // For GCM a 12 byte IV is strongly suggested as other IV lengths
          // will require additional calculations. In principle any IV size
          // can be used as long as the IV doesn't ever repeat. NIST however
          // suggests that only an IV size of 12 bytes needs to be supported
          // by implementations.
          //
          // https://crypto.stackexchange.com/questions/26783/ciphertext-and-tag-size-and-iv-transmission-with-aes-in-gcm-mode
          iv = crypto.getRandomValues(new window.Uint8Array(12));
          _context2.next = 3;
          return crypto.subtle.generateKey(KEY_ALGO, true, ['encrypt', 'decrypt']);
        case 3:
          key = _context2.sent;
          algo = {
            'name': 'AES-GCM',
            'iv': iv,
            'tagLength': TAG_LENGTH
          };
          _context2.next = 7;
          return crypto.subtle.encrypt(algo, key, stringToArrayBuffer(plaintext));
        case 7:
          encrypted = _context2.sent;
          length = encrypted.byteLength - (128 + 7 >> 3);
          ciphertext = encrypted.slice(0, length);
          tag = encrypted.slice(length);
          _context2.next = 13;
          return crypto.subtle.exportKey('raw', key);
        case 13:
          exported_key = _context2.sent;
          return _context2.abrupt("return", {
            'key': exported_key,
            'tag': tag,
            'key_and_tag': appendArrayBuffer(exported_key, tag),
            'payload': arrayBufferToBase64(ciphertext),
            'iv': arrayBufferToBase64(iv)
          });
        case 15:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _encryptMessage.apply(this, arguments);
}
function decryptMessage(_x2) {
  return _decryptMessage.apply(this, arguments);
}
function _decryptMessage() {
  _decryptMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee3(obj) {
    var key_obj, cipher, algo;
    return omemo_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return crypto.subtle.importKey('raw', obj.key, KEY_ALGO, true, ['encrypt', 'decrypt']);
        case 2:
          key_obj = _context3.sent;
          cipher = appendArrayBuffer(base64ToArrayBuffer(obj.payload), obj.tag);
          algo = {
            'name': 'AES-GCM',
            'iv': base64ToArrayBuffer(obj.iv),
            'tagLength': TAG_LENGTH
          };
          _context3.t0 = arrayBufferToString;
          _context3.next = 8;
          return crypto.subtle.decrypt(algo, key_obj, cipher);
        case 8:
          _context3.t1 = _context3.sent;
          return _context3.abrupt("return", (0, _context3.t0)(_context3.t1));
        case 10:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _decryptMessage.apply(this, arguments);
}
function encryptFile(_x3) {
  return _encryptFile.apply(this, arguments);
}
function _encryptFile() {
  _encryptFile = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee4(file) {
    var iv, key, encrypted, exported_key, encrypted_file;
    return omemo_utils_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          iv = crypto.getRandomValues(new Uint8Array(12));
          _context4.next = 3;
          return crypto.subtle.generateKey({
            name: 'AES-GCM',
            length: 256
          }, true, ['encrypt', 'decrypt']);
        case 3:
          key = _context4.sent;
          _context4.t0 = crypto.subtle;
          _context4.t1 = {
            name: 'AES-GCM',
            iv: iv
          };
          _context4.t2 = key;
          _context4.next = 9;
          return file.arrayBuffer();
        case 9:
          _context4.t3 = _context4.sent;
          _context4.next = 12;
          return _context4.t0.encrypt.call(_context4.t0, _context4.t1, _context4.t2, _context4.t3);
        case 12:
          encrypted = _context4.sent;
          _context4.next = 15;
          return window.crypto.subtle.exportKey('raw', key);
        case 15:
          exported_key = _context4.sent;
          encrypted_file = new File([encrypted], file.name, {
            type: file.type,
            lastModified: file.lastModified
          });
          encrypted_file.xep454_ivkey = arrayBufferToHex(iv) + arrayBufferToHex(exported_key);
          return _context4.abrupt("return", encrypted_file);
        case 19:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return _encryptFile.apply(this, arguments);
}
function setEncryptedFileURL(message, attrs) {
  var url = attrs.oob_url.replace(/^https?:/, 'aesgcm:') + '#' + message.file.xep454_ivkey;
  return Object.assign(attrs, {
    'oob_url': null,
    // Since only the body gets encrypted, we don't set the oob_url
    'message': url,
    'body': url
  });
}
function decryptFile(_x4, _x5, _x6) {
  return _decryptFile.apply(this, arguments);
}
function _decryptFile() {
  _decryptFile = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee5(iv, key, cipher) {
    var key_obj, algo;
    return omemo_utils_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          _context5.next = 2;
          return crypto.subtle.importKey('raw', hexToArrayBuffer(key), 'AES-GCM', false, ['decrypt']);
        case 2:
          key_obj = _context5.sent;
          algo = {
            'name': 'AES-GCM',
            'iv': hexToArrayBuffer(iv)
          };
          return _context5.abrupt("return", crypto.subtle.decrypt(algo, key_obj, cipher));
        case 5:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
  return _decryptFile.apply(this, arguments);
}
function downloadFile(_x7) {
  return _downloadFile.apply(this, arguments);
}
function _downloadFile() {
  _downloadFile = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee6(url) {
    var response;
    return omemo_utils_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          _context6.prev = 0;
          _context6.next = 3;
          return fetch(url);
        case 3:
          response = _context6.sent;
          _context6.next = 11;
          break;
        case 6:
          _context6.prev = 6;
          _context6.t0 = _context6["catch"](0);
          log.error("".concat(_context6.t0.name, ": Failed to download encrypted media: ").concat(url));
          log.error(_context6.t0);
          return _context6.abrupt("return", null);
        case 11:
          if (!(response.status >= 200 && response.status < 400)) {
            _context6.next = 13;
            break;
          }
          return _context6.abrupt("return", response.arrayBuffer());
        case 13:
        case "end":
          return _context6.stop();
      }
    }, _callee6, null, [[0, 6]]);
  }));
  return _downloadFile.apply(this, arguments);
}
function getAndDecryptFile(_x8) {
  return _getAndDecryptFile.apply(this, arguments);
}
function _getAndDecryptFile() {
  _getAndDecryptFile = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee7(uri) {
    var protocol, http_url, cipher, hash, key, iv, content, _uri$filename$split, _uri$filename$split2, filename, extension, mimetype, file;
    return omemo_utils_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) switch (_context7.prev = _context7.next) {
        case 0:
          protocol = window.location.hostname === 'localhost' && uri.domain() === 'localhost' ? 'http' : 'https';
          http_url = uri.toString().replace(/^aesgcm/, protocol);
          _context7.next = 4;
          return downloadFile(http_url);
        case 4:
          cipher = _context7.sent;
          if (!(cipher === null)) {
            _context7.next = 8;
            break;
          }
          log.error("Could not decrypt a received encrypted file ".concat(uri.toString(), " since it could not be downloaded"));
          return _context7.abrupt("return", new Error(__('Error: could not decrypt a received encrypted file, because it could not be downloaded')));
        case 8:
          hash = uri.hash().slice(1);
          key = hash.substring(hash.length - 64);
          iv = hash.replace(key, '');
          _context7.prev = 11;
          _context7.next = 14;
          return decryptFile(iv, key, cipher);
        case 14:
          content = _context7.sent;
          _context7.next = 22;
          break;
        case 17:
          _context7.prev = 17;
          _context7.t0 = _context7["catch"](11);
          log.error("Could not decrypt file ".concat(uri.toString()));
          log.error(_context7.t0);
          return _context7.abrupt("return", null);
        case 22:
          _uri$filename$split = uri.filename().split('.'), _uri$filename$split2 = utils_slicedToArray(_uri$filename$split, 2), filename = _uri$filename$split2[0], extension = _uri$filename$split2[1];
          mimetype = MIMETYPES_MAP[extension];
          _context7.prev = 24;
          file = new File([content], filename, {
            'type': mimetype
          });
          return _context7.abrupt("return", URL.createObjectURL(file));
        case 29:
          _context7.prev = 29;
          _context7.t1 = _context7["catch"](24);
          log.error("Could not decrypt file ".concat(uri.toString()));
          log.error(_context7.t1);
          return _context7.abrupt("return", null);
        case 34:
        case "end":
          return _context7.stop();
      }
    }, _callee7, null, [[11, 17], [24, 29]]);
  }));
  return _getAndDecryptFile.apply(this, arguments);
}
function getTemplateForObjectURL(uri, obj_url, richtext) {
  if (isError(obj_url)) {
    return (0,external_lit_namespaceObject.html)(omemo_utils_templateObject || (omemo_utils_templateObject = omemo_utils_taggedTemplateLiteral(["<p class=\"error\">", "</p>"])), obj_url.message);
  }
  var file_url = uri.toString();
  if (isImageURL(file_url)) {
    return src_templates_image({
      'src': obj_url,
      'onClick': richtext.onImgClick,
      'onLoad': richtext.onImgLoad
    });
  } else if (isAudioURL(file_url)) {
    return audio(obj_url);
  } else if (isVideoURL(file_url)) {
    return video(obj_url);
  } else {
    return file(obj_url, uri.filename());
  }
}
function addEncryptedFiles(text, offset, richtext) {
  var objs = [];
  try {
    var parse_options = {
      'start': /\b(aesgcm:\/\/)/gi
    };
    utils_URI.withinString(text, function (url, start, end) {
      objs.push({
        url: url,
        start: start,
        end: end
      });
      return url;
    }, parse_options);
  } catch (error) {
    log.debug(error);
    return;
  }
  objs.forEach(function (o) {
    var uri = getURI(text.slice(o.start, o.end));
    var promise = getAndDecryptFile(uri).then(function (obj_url) {
      return getTemplateForObjectURL(uri, obj_url, richtext);
    });
    var template = (0,external_lit_namespaceObject.html)(omemo_utils_templateObject2 || (omemo_utils_templateObject2 = omemo_utils_taggedTemplateLiteral(["", ""])), until_m(promise, ''));
    richtext.addTemplateResult(o.start + offset, o.end + offset, template);
  });
}
function handleEncryptedFiles(richtext) {
  if (!shared_converse.config.get('trusted')) {
    return;
  }
  richtext.addAnnotations(function (text, offset) {
    return addEncryptedFiles(text, offset, richtext);
  });
}

/**
 * Hook handler for { @link parseMessage } and { @link parseMUCMessage }, which
 * parses the passed in `message` stanza for OMEMO attributes and then sets
 * them on the attrs object.
 * @param { Element } stanza - The message stanza
 * @param { (MUCMessageAttributes|MessageAttributes) } attrs
 * @returns (MUCMessageAttributes|MessageAttributes)
 */
function parseEncryptedMessage(_x9, _x10) {
  return _parseEncryptedMessage.apply(this, arguments);
}
function _parseEncryptedMessage() {
  _parseEncryptedMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee8(stanza, attrs) {
    var _api$omemo;
    var encrypted_el, header, device_id, key, _encrypted_el$querySe;
    return omemo_utils_regeneratorRuntime().wrap(function _callee8$(_context8) {
      while (1) switch (_context8.prev = _context8.next) {
        case 0:
          if (!(shared_api.settings.get('clear_cache_on_logout') || !attrs.is_encrypted || attrs.encryption_namespace !== omemo_utils_Strophe.NS.OMEMO)) {
            _context8.next = 2;
            break;
          }
          return _context8.abrupt("return", attrs);
        case 2:
          encrypted_el = omemo_utils_sizzle("encrypted[xmlns=\"".concat(omemo_utils_Strophe.NS.OMEMO, "\"]"), stanza).pop();
          header = encrypted_el.querySelector('header');
          attrs.encrypted = {
            'device_id': header.getAttribute('sid')
          };
          _context8.next = 7;
          return (_api$omemo = shared_api.omemo) === null || _api$omemo === void 0 ? void 0 : _api$omemo.getDeviceID();
        case 7:
          device_id = _context8.sent;
          key = device_id && omemo_utils_sizzle("key[rid=\"".concat(device_id, "\"]"), encrypted_el).pop();
          if (!key) {
            _context8.next = 13;
            break;
          }
          Object.assign(attrs.encrypted, {
            'iv': header.querySelector('iv').textContent,
            'key': key.textContent,
            'payload': ((_encrypted_el$querySe = encrypted_el.querySelector('payload')) === null || _encrypted_el$querySe === void 0 ? void 0 : _encrypted_el$querySe.textContent) || null,
            'prekey': ['true', '1'].includes(key.getAttribute('prekey'))
          });
          _context8.next = 14;
          break;
        case 13:
          return _context8.abrupt("return", Object.assign(attrs, {
            'error_condition': 'not-encrypted-for-this-device',
            'error_type': 'Decryption',
            'is_ephemeral': true,
            'is_error': true,
            'type': 'error'
          }));
        case 14:
          if (!(attrs.encrypted.prekey === true)) {
            _context8.next = 18;
            break;
          }
          return _context8.abrupt("return", decryptPrekeyWhisperMessage(attrs));
        case 18:
          return _context8.abrupt("return", decryptWhisperMessage(attrs));
        case 19:
        case "end":
          return _context8.stop();
      }
    }, _callee8);
  }));
  return _parseEncryptedMessage.apply(this, arguments);
}
function utils_onChatBoxesInitialized() {
  shared_converse.chatboxes.on('add', function (chatbox) {
    checkOMEMOSupported(chatbox);
    if (chatbox.get('type') === shared_converse.CHATROOMS_TYPE) {
      chatbox.occupants.on('add', function (o) {
        return onOccupantAdded(chatbox, o);
      });
      chatbox.features.on('change', function () {
        return checkOMEMOSupported(chatbox);
      });
    }
  });
}
function onChatInitialized(el) {
  el.listenTo(el.model.messages, 'add', function (message) {
    if (message.get('is_encrypted') && !message.get('is_error')) {
      el.model.save('omemo_supported', true);
    }
  });
  el.listenTo(el.model, 'change:omemo_supported', function () {
    if (!el.model.get('omemo_supported') && el.model.get('omemo_active')) {
      el.model.set('omemo_active', false);
    } else {
      var _el$querySelector;
      // Manually trigger an update, setting omemo_active to
      // false above will automatically trigger one.
      (_el$querySelector = el.querySelector('converse-chat-toolbar')) === null || _el$querySelector === void 0 ? void 0 : _el$querySelector.requestUpdate();
    }
  });
  el.listenTo(el.model, 'change:omemo_active', function () {
    el.querySelector('converse-chat-toolbar').requestUpdate();
  });
}
function getSessionCipher(jid, id) {
  var address = new libsignal.SignalProtocolAddress(jid, id);
  return new window.libsignal.SessionCipher(shared_converse.omemo_store, address);
}
function getJIDForDecryption(attrs) {
  var from_jid = attrs.from_muc ? attrs.from_real_jid : attrs.from;
  if (!from_jid) {
    Object.assign(attrs, {
      'error_text': __("Sorry, could not decrypt a received OMEMO " + "message because we don't have the XMPP address for that user."),
      'error_type': 'Decryption',
      'is_ephemeral': true,
      'is_error': true,
      'type': 'error'
    });
    throw new Error("Could not find JID to decrypt OMEMO message for");
  }
  return from_jid;
}
function handleDecryptedWhisperMessage(_x11, _x12) {
  return _handleDecryptedWhisperMessage.apply(this, arguments);
}
function _handleDecryptedWhisperMessage() {
  _handleDecryptedWhisperMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee9(attrs, key_and_tag) {
    var from_jid, devicelist, encrypted, device, key, tag, result;
    return omemo_utils_regeneratorRuntime().wrap(function _callee9$(_context9) {
      while (1) switch (_context9.prev = _context9.next) {
        case 0:
          from_jid = getJIDForDecryption(attrs);
          _context9.next = 3;
          return shared_api.omemo.devicelists.get(from_jid, true);
        case 3:
          devicelist = _context9.sent;
          encrypted = attrs.encrypted;
          device = devicelist.devices.get(encrypted.device_id);
          if (device) {
            _context9.next = 10;
            break;
          }
          _context9.next = 9;
          return devicelist.devices.create({
            'id': encrypted.device_id,
            'jid': from_jid
          }, {
            'promise': true
          });
        case 9:
          device = _context9.sent;
        case 10:
          if (!encrypted.payload) {
            _context9.next = 18;
            break;
          }
          key = key_and_tag.slice(0, 16);
          tag = key_and_tag.slice(16);
          _context9.next = 15;
          return omemo.decryptMessage(Object.assign(encrypted, {
            'key': key,
            'tag': tag
          }));
        case 15:
          result = _context9.sent;
          device.save('active', true);
          return _context9.abrupt("return", result);
        case 18:
        case "end":
          return _context9.stop();
      }
    }, _callee9);
  }));
  return _handleDecryptedWhisperMessage.apply(this, arguments);
}
function getDecryptionErrorAttributes(e) {
  return {
    'error_text': __('Sorry, could not decrypt a received OMEMO message due to an error.') + " ".concat(e.name, " ").concat(e.message),
    'error_condition': e.name,
    'error_message': e.message,
    'error_type': 'Decryption',
    'is_ephemeral': true,
    'is_error': true,
    'type': 'error'
  };
}
function decryptPrekeyWhisperMessage(_x13) {
  return _decryptPrekeyWhisperMessage.apply(this, arguments);
}
function _decryptPrekeyWhisperMessage() {
  _decryptPrekeyWhisperMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee10(attrs) {
    var from_jid, session_cipher, key, key_and_tag, plaintext;
    return omemo_utils_regeneratorRuntime().wrap(function _callee10$(_context10) {
      while (1) switch (_context10.prev = _context10.next) {
        case 0:
          from_jid = getJIDForDecryption(attrs);
          session_cipher = getSessionCipher(from_jid, parseInt(attrs.encrypted.device_id, 10));
          key = base64ToArrayBuffer(attrs.encrypted.key);
          _context10.prev = 3;
          _context10.next = 6;
          return session_cipher.decryptPreKeyWhisperMessage(key, 'binary');
        case 6:
          key_and_tag = _context10.sent;
          _context10.next = 13;
          break;
        case 9:
          _context10.prev = 9;
          _context10.t0 = _context10["catch"](3);
          // TODO from the XEP:
          // There are various reasons why decryption of an
          // OMEMOKeyExchange or an OMEMOAuthenticatedMessage
          // could fail. One reason is if the message was
          // received twice and already decrypted once, in this
          // case the client MUST ignore the decryption failure
          // and not show any warnings/errors. In all other cases
          // of decryption failure, clients SHOULD respond by
          // forcibly doing a new key exchange and sending a new
          // OMEMOKeyExchange with a potentially empty SCE
          // payload. By building a new session with the original
          // sender this way, the invalid session of the original
          // sender will get overwritten with this newly created,
          // valid session.
          log.error("".concat(_context10.t0.name, " ").concat(_context10.t0.message));
          return _context10.abrupt("return", Object.assign(attrs, getDecryptionErrorAttributes(_context10.t0)));
        case 13:
          _context10.prev = 13;
          _context10.next = 16;
          return handleDecryptedWhisperMessage(attrs, key_and_tag);
        case 16:
          plaintext = _context10.sent;
          _context10.next = 19;
          return shared_converse.omemo_store.generateMissingPreKeys();
        case 19:
          _context10.next = 21;
          return shared_converse.omemo_store.publishBundle();
        case 21:
          if (!plaintext) {
            _context10.next = 25;
            break;
          }
          return _context10.abrupt("return", Object.assign(attrs, {
            'plaintext': plaintext
          }));
        case 25:
          return _context10.abrupt("return", Object.assign(attrs, {
            'is_only_key': true
          }));
        case 26:
          _context10.next = 32;
          break;
        case 28:
          _context10.prev = 28;
          _context10.t1 = _context10["catch"](13);
          log.error("".concat(_context10.t1.name, " ").concat(_context10.t1.message));
          return _context10.abrupt("return", Object.assign(attrs, getDecryptionErrorAttributes(_context10.t1)));
        case 32:
        case "end":
          return _context10.stop();
      }
    }, _callee10, null, [[3, 9], [13, 28]]);
  }));
  return _decryptPrekeyWhisperMessage.apply(this, arguments);
}
function decryptWhisperMessage(_x14) {
  return _decryptWhisperMessage.apply(this, arguments);
}
function _decryptWhisperMessage() {
  _decryptWhisperMessage = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee11(attrs) {
    var from_jid, session_cipher, key, key_and_tag, plaintext;
    return omemo_utils_regeneratorRuntime().wrap(function _callee11$(_context11) {
      while (1) switch (_context11.prev = _context11.next) {
        case 0:
          from_jid = getJIDForDecryption(attrs);
          session_cipher = getSessionCipher(from_jid, parseInt(attrs.encrypted.device_id, 10));
          key = base64ToArrayBuffer(attrs.encrypted.key);
          _context11.prev = 3;
          _context11.next = 6;
          return session_cipher.decryptWhisperMessage(key, 'binary');
        case 6:
          key_and_tag = _context11.sent;
          _context11.next = 9;
          return handleDecryptedWhisperMessage(attrs, key_and_tag);
        case 9:
          plaintext = _context11.sent;
          return _context11.abrupt("return", Object.assign(attrs, {
            'plaintext': plaintext
          }));
        case 13:
          _context11.prev = 13;
          _context11.t0 = _context11["catch"](3);
          log.error("".concat(_context11.t0.name, " ").concat(_context11.t0.message));
          return _context11.abrupt("return", Object.assign(attrs, getDecryptionErrorAttributes(_context11.t0)));
        case 17:
        case "end":
          return _context11.stop();
      }
    }, _callee11, null, [[3, 13]]);
  }));
  return _decryptWhisperMessage.apply(this, arguments);
}
function addKeysToMessageStanza(stanza, dicts, iv) {
  for (var i in dicts) {
    if (Object.prototype.hasOwnProperty.call(dicts, i)) {
      var payload = dicts[i].payload;
      var device = dicts[i].device;
      var prekey = 3 == parseInt(payload.type, 10);
      stanza.c('key', {
        'rid': device.get('id')
      }).t(btoa(payload.body));
      if (prekey) {
        stanza.attrs({
          'prekey': prekey
        });
      }
      stanza.up();
      if (i == dicts.length - 1) {
        stanza.c('iv').t(iv).up().up();
      }
    }
  }
  return Promise.resolve(stanza);
}

/**
 * Given an XML element representing a user's OMEMO bundle, parse it
 * and return a map.
 */
function parseBundle(bundle_el) {
  var signed_prekey_public_el = bundle_el.querySelector('signedPreKeyPublic');
  var signed_prekey_signature_el = bundle_el.querySelector('signedPreKeySignature');
  var prekeys = omemo_utils_sizzle("prekeys > preKeyPublic", bundle_el).map(function (el) {
    return {
      'id': parseInt(el.getAttribute('preKeyId'), 10),
      'key': el.textContent
    };
  });
  return {
    'identity_key': bundle_el.querySelector('identityKey').textContent.trim(),
    'signed_prekey': {
      'id': parseInt(signed_prekey_public_el.getAttribute('signedPreKeyId'), 10),
      'public_key': signed_prekey_public_el.textContent,
      'signature': signed_prekey_signature_el.textContent
    },
    'prekeys': prekeys
  };
}
function generateFingerprint(_x15) {
  return _generateFingerprint.apply(this, arguments);
}
function _generateFingerprint() {
  _generateFingerprint = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee12(device) {
    var _device$get;
    var bundle;
    return omemo_utils_regeneratorRuntime().wrap(function _callee12$(_context12) {
      while (1) switch (_context12.prev = _context12.next) {
        case 0:
          if (!((_device$get = device.get('bundle')) !== null && _device$get !== void 0 && _device$get.fingerprint)) {
            _context12.next = 2;
            break;
          }
          return _context12.abrupt("return");
        case 2:
          _context12.next = 4;
          return device.getBundle();
        case 4:
          bundle = _context12.sent;
          bundle['fingerprint'] = arrayBufferToHex(base64ToArrayBuffer(bundle['identity_key']));
          device.save('bundle', bundle);
          device.trigger('change:bundle');
        // Doesn't get triggered automatically due to pass-by-reference
        case 8:
        case "end":
          return _context12.stop();
      }
    }, _callee12);
  }));
  return _generateFingerprint.apply(this, arguments);
}
function getDevicesForContact(_x16) {
  return _getDevicesForContact.apply(this, arguments);
}
function _getDevicesForContact() {
  _getDevicesForContact = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee13(jid) {
    var devicelist;
    return omemo_utils_regeneratorRuntime().wrap(function _callee13$(_context13) {
      while (1) switch (_context13.prev = _context13.next) {
        case 0:
          _context13.next = 2;
          return shared_api.waitUntil('OMEMOInitialized');
        case 2:
          _context13.next = 4;
          return shared_api.omemo.devicelists.get(jid, true);
        case 4:
          devicelist = _context13.sent;
          _context13.next = 7;
          return devicelist.fetchDevices();
        case 7:
          return _context13.abrupt("return", devicelist.devices);
        case 8:
        case "end":
          return _context13.stop();
      }
    }, _callee13);
  }));
  return _getDevicesForContact.apply(this, arguments);
}
function generateDeviceID() {
  return _generateDeviceID.apply(this, arguments);
}
function _generateDeviceID() {
  _generateDeviceID = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee14() {
    var devicelist, existing_ids, device_id, i;
    return omemo_utils_regeneratorRuntime().wrap(function _callee14$(_context14) {
      while (1) switch (_context14.prev = _context14.next) {
        case 0:
          _context14.next = 2;
          return shared_api.omemo.devicelists.get(shared_converse.bare_jid, true);
        case 2:
          devicelist = _context14.sent;
          existing_ids = devicelist.devices.pluck('id');
          device_id = libsignal.KeyHelper.generateRegistrationId(); // Before publishing a freshly generated device id for the first time,
          // a device MUST check whether that device id already exists, and if so, generate a new one.
          i = 0;
        case 6:
          if (!existing_ids.includes(device_id)) {
            _context14.next = 13;
            break;
          }
          device_id = libsignal.KeyHelper.generateRegistrationId();
          i++;
          if (!(i === 10)) {
            _context14.next = 11;
            break;
          }
          throw new Error('Unable to generate a unique device ID');
        case 11:
          _context14.next = 6;
          break;
        case 13:
          return _context14.abrupt("return", device_id.toString());
        case 14:
        case "end":
          return _context14.stop();
      }
    }, _callee14);
  }));
  return _generateDeviceID.apply(this, arguments);
}
function buildSession(_x17) {
  return _buildSession.apply(this, arguments);
}
function _buildSession() {
  _buildSession = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee15(device) {
    var address, sessionBuilder, prekey, bundle;
    return omemo_utils_regeneratorRuntime().wrap(function _callee15$(_context15) {
      while (1) switch (_context15.prev = _context15.next) {
        case 0:
          address = new libsignal.SignalProtocolAddress(device.get('jid'), device.get('id'));
          sessionBuilder = new libsignal.SessionBuilder(shared_converse.omemo_store, address);
          prekey = device.getRandomPreKey();
          _context15.next = 5;
          return device.getBundle();
        case 5:
          bundle = _context15.sent;
          return _context15.abrupt("return", sessionBuilder.processPreKey({
            'registrationId': parseInt(device.get('id'), 10),
            'identityKey': base64ToArrayBuffer(bundle.identity_key),
            'signedPreKey': {
              'keyId': bundle.signed_prekey.id,
              // <Number>
              'publicKey': base64ToArrayBuffer(bundle.signed_prekey.public_key),
              'signature': base64ToArrayBuffer(bundle.signed_prekey.signature)
            },
            'preKey': {
              'keyId': prekey.id,
              // <Number>
              'publicKey': base64ToArrayBuffer(prekey.key)
            }
          }));
        case 7:
        case "end":
          return _context15.stop();
      }
    }, _callee15);
  }));
  return _buildSession.apply(this, arguments);
}
function getSession(_x18) {
  return _getSession.apply(this, arguments);
}
function _getSession() {
  _getSession = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee16(device) {
    var address, session, _session;
    return omemo_utils_regeneratorRuntime().wrap(function _callee16$(_context16) {
      while (1) switch (_context16.prev = _context16.next) {
        case 0:
          if (device.get('bundle')) {
            _context16.next = 3;
            break;
          }
          log.error("Could not build an OMEMO session for device ".concat(device.get('id'), " because we don't have its bundle"));
          return _context16.abrupt("return", null);
        case 3:
          address = new libsignal.SignalProtocolAddress(device.get('jid'), device.get('id'));
          _context16.next = 6;
          return shared_converse.omemo_store.loadSession(address.toString());
        case 6:
          session = _context16.sent;
          if (!session) {
            _context16.next = 11;
            break;
          }
          return _context16.abrupt("return", session);
        case 11:
          _context16.prev = 11;
          _context16.next = 14;
          return buildSession(device);
        case 14:
          _session = _context16.sent;
          return _context16.abrupt("return", _session);
        case 18:
          _context16.prev = 18;
          _context16.t0 = _context16["catch"](11);
          log.error("Could not build an OMEMO session for device ".concat(device.get('id')));
          log.error(_context16.t0);
          return _context16.abrupt("return", null);
        case 23:
        case "end":
          return _context16.stop();
      }
    }, _callee16, null, [[11, 18]]);
  }));
  return _getSession.apply(this, arguments);
}
function updateBundleFromStanza(_x19) {
  return _updateBundleFromStanza.apply(this, arguments);
}
function _updateBundleFromStanza() {
  _updateBundleFromStanza = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee17(stanza) {
    var items_el, device_id, jid, bundle_el, devicelist, device;
    return omemo_utils_regeneratorRuntime().wrap(function _callee17$(_context17) {
      while (1) switch (_context17.prev = _context17.next) {
        case 0:
          items_el = omemo_utils_sizzle("items", stanza).pop();
          if (!(!items_el || !items_el.getAttribute('node').startsWith(omemo_utils_Strophe.NS.OMEMO_BUNDLES))) {
            _context17.next = 3;
            break;
          }
          return _context17.abrupt("return");
        case 3:
          device_id = items_el.getAttribute('node').split(':')[1];
          jid = stanza.getAttribute('from');
          bundle_el = omemo_utils_sizzle("item > bundle", items_el).pop();
          _context17.next = 8;
          return shared_api.omemo.devicelists.get(jid, true);
        case 8:
          devicelist = _context17.sent;
          device = devicelist.devices.get(device_id) || devicelist.devices.create({
            'id': device_id,
            jid: jid
          });
          device.save({
            'bundle': parseBundle(bundle_el)
          });
        case 11:
        case "end":
          return _context17.stop();
      }
    }, _callee17);
  }));
  return _updateBundleFromStanza.apply(this, arguments);
}
function updateDevicesFromStanza(_x20) {
  return _updateDevicesFromStanza.apply(this, arguments);
}
function _updateDevicesFromStanza() {
  _updateDevicesFromStanza = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee18(stanza) {
    var items_el, device_selector, device_ids, jid, devicelist, devices, removed_ids;
    return omemo_utils_regeneratorRuntime().wrap(function _callee18$(_context18) {
      while (1) switch (_context18.prev = _context18.next) {
        case 0:
          items_el = omemo_utils_sizzle("items[node=\"".concat(omemo_utils_Strophe.NS.OMEMO_DEVICELIST, "\"]"), stanza).pop();
          if (items_el) {
            _context18.next = 3;
            break;
          }
          return _context18.abrupt("return");
        case 3:
          device_selector = "item list[xmlns=\"".concat(omemo_utils_Strophe.NS.OMEMO, "\"] device");
          device_ids = omemo_utils_sizzle(device_selector, items_el).map(function (d) {
            return d.getAttribute('id');
          });
          jid = stanza.getAttribute('from');
          _context18.next = 8;
          return shared_api.omemo.devicelists.get(jid, true);
        case 8:
          devicelist = _context18.sent;
          devices = devicelist.devices;
          removed_ids = lodash_es_difference(devices.pluck('id'), device_ids);
          removed_ids.forEach(function (id) {
            if (jid === shared_converse.bare_jid && id === shared_converse.omemo_store.get('device_id')) {
              return; // We don't set the current device as inactive
            }

            devices.get(id).save('active', false);
          });
          device_ids.forEach(function (device_id) {
            var device = devices.get(device_id);
            if (device) {
              device.save('active', true);
            } else {
              devices.create({
                'id': device_id,
                'jid': jid
              });
            }
          });
          if (omemo_utils_u.isSameBareJID(jid, shared_converse.bare_jid)) {
            // Make sure our own device is on the list
            // (i.e. if it was removed, add it again).
            devicelist.publishCurrentDevice(device_ids);
          }
        case 14:
        case "end":
          return _context18.stop();
      }
    }, _callee18);
  }));
  return _updateDevicesFromStanza.apply(this, arguments);
}
function registerPEPPushHandler() {
  // Add a handler for devices pushed from other connected clients
  shared_converse.connection.addHandler( /*#__PURE__*/function () {
    var _ref = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee(message) {
      return omemo_utils_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            if (!omemo_utils_sizzle("event[xmlns=\"".concat(omemo_utils_Strophe.NS.PUBSUB, "#event\"]"), message).length) {
              _context.next = 8;
              break;
            }
            _context.next = 4;
            return shared_api.waitUntil('OMEMOInitialized');
          case 4:
            _context.next = 6;
            return updateDevicesFromStanza(message);
          case 6:
            _context.next = 8;
            return updateBundleFromStanza(message);
          case 8:
            _context.next = 13;
            break;
          case 10:
            _context.prev = 10;
            _context.t0 = _context["catch"](0);
            log.error(_context.t0.message);
          case 13:
            return _context.abrupt("return", true);
          case 14:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[0, 10]]);
    }));
    return function (_x21) {
      return _ref.apply(this, arguments);
    };
  }(), null, 'message', 'headline');
}
function restoreOMEMOSession() {
  return _restoreOMEMOSession.apply(this, arguments);
}
function _restoreOMEMOSession() {
  _restoreOMEMOSession = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee19() {
    var id;
    return omemo_utils_regeneratorRuntime().wrap(function _callee19$(_context19) {
      while (1) switch (_context19.prev = _context19.next) {
        case 0:
          if (shared_converse.omemo_store === undefined) {
            id = "converse.omemosession-".concat(shared_converse.bare_jid);
            shared_converse.omemo_store = new shared_converse.OMEMOStore({
              id: id
            });
            initStorage(shared_converse.omemo_store, id);
          }
          _context19.next = 3;
          return shared_converse.omemo_store.fetchSession();
        case 3:
        case "end":
          return _context19.stop();
      }
    }, _callee19);
  }));
  return _restoreOMEMOSession.apply(this, arguments);
}
function fetchDeviceLists() {
  return _fetchDeviceLists.apply(this, arguments);
}
function _fetchDeviceLists() {
  _fetchDeviceLists = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee20() {
    var id;
    return omemo_utils_regeneratorRuntime().wrap(function _callee20$(_context20) {
      while (1) switch (_context20.prev = _context20.next) {
        case 0:
          shared_converse.devicelists = new shared_converse.DeviceLists();
          id = "converse.devicelists-".concat(shared_converse.bare_jid);
          initStorage(shared_converse.devicelists, id);
          _context20.next = 5;
          return new Promise(function (resolve) {
            shared_converse.devicelists.fetch({
              'success': resolve,
              'error': function error(_m, e) {
                log.error(e);
                resolve();
              }
            });
          });
        case 5:
          _context20.next = 7;
          return shared_api.omemo.devicelists.get(shared_converse.bare_jid, true);
        case 7:
        case "end":
          return _context20.stop();
      }
    }, _callee20);
  }));
  return _fetchDeviceLists.apply(this, arguments);
}
function initOMEMO(_x22) {
  return _initOMEMO.apply(this, arguments);
}
function _initOMEMO() {
  _initOMEMO = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee21(reconnecting) {
    return omemo_utils_regeneratorRuntime().wrap(function _callee21$(_context21) {
      while (1) switch (_context21.prev = _context21.next) {
        case 0:
          if (!reconnecting) {
            _context21.next = 2;
            break;
          }
          return _context21.abrupt("return");
        case 2:
          if (!(!shared_converse.config.get('trusted') || shared_api.settings.get('clear_cache_on_logout'))) {
            _context21.next = 5;
            break;
          }
          log.warn('Not initializing OMEMO, since this browser is not trusted or clear_cache_on_logout is set to true');
          return _context21.abrupt("return");
        case 5:
          _context21.prev = 5;
          _context21.next = 8;
          return fetchDeviceLists();
        case 8:
          _context21.next = 10;
          return restoreOMEMOSession();
        case 10:
          _context21.next = 12;
          return shared_converse.omemo_store.publishBundle();
        case 12:
          _context21.next = 19;
          break;
        case 14:
          _context21.prev = 14;
          _context21.t0 = _context21["catch"](5);
          log.error('Could not initialize OMEMO support');
          log.error(_context21.t0);
          return _context21.abrupt("return");
        case 19:
          /**
           * Triggered once OMEMO support has been initialized
           * @event _converse#OMEMOInitialized
           * @example _converse.api.listen.on('OMEMOInitialized', () => { ... });
           */
          shared_api.trigger('OMEMOInitialized');
        case 20:
        case "end":
          return _context21.stop();
      }
    }, _callee21, null, [[5, 14]]);
  }));
  return _initOMEMO.apply(this, arguments);
}
function onOccupantAdded(_x23, _x24) {
  return _onOccupantAdded.apply(this, arguments);
}
function _onOccupantAdded() {
  _onOccupantAdded = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee22(chatroom, occupant) {
    var supported;
    return omemo_utils_regeneratorRuntime().wrap(function _callee22$(_context22) {
      while (1) switch (_context22.prev = _context22.next) {
        case 0:
          if (!(occupant.isSelf() || !chatroom.features.get('nonanonymous') || !chatroom.features.get('membersonly'))) {
            _context22.next = 2;
            break;
          }
          return _context22.abrupt("return");
        case 2:
          if (!chatroom.get('omemo_active')) {
            _context22.next = 7;
            break;
          }
          _context22.next = 5;
          return shared_converse.contactHasOMEMOSupport(occupant.get('jid'));
        case 5:
          supported = _context22.sent;
          if (!supported) {
            chatroom.createMessage({
              'message': __("%1$s doesn't appear to have a client that supports OMEMO. " + 'Encrypted chat will no longer be possible in this grouchat.', occupant.get('nick')),
              'type': 'error'
            });
            chatroom.save({
              'omemo_active': false,
              'omemo_supported': false
            });
          }
        case 7:
        case "end":
          return _context22.stop();
      }
    }, _callee22);
  }));
  return _onOccupantAdded.apply(this, arguments);
}
function checkOMEMOSupported(_x25) {
  return _checkOMEMOSupported.apply(this, arguments);
}
function _checkOMEMOSupported() {
  _checkOMEMOSupported = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee23(chatbox) {
    var supported;
    return omemo_utils_regeneratorRuntime().wrap(function _callee23$(_context23) {
      while (1) switch (_context23.prev = _context23.next) {
        case 0:
          if (!(chatbox.get('type') === shared_converse.CHATROOMS_TYPE)) {
            _context23.next = 6;
            break;
          }
          _context23.next = 3;
          return shared_api.waitUntil('OMEMOInitialized');
        case 3:
          supported = chatbox.features.get('nonanonymous') && chatbox.features.get('membersonly');
          _context23.next = 10;
          break;
        case 6:
          if (!(chatbox.get('type') === shared_converse.PRIVATE_CHAT_TYPE)) {
            _context23.next = 10;
            break;
          }
          _context23.next = 9;
          return shared_converse.contactHasOMEMOSupport(chatbox.get('jid'));
        case 9:
          supported = _context23.sent;
        case 10:
          chatbox.set('omemo_supported', supported);
          if (supported && shared_api.settings.get('omemo_default')) {
            chatbox.set('omemo_active', true);
          }
        case 12:
        case "end":
          return _context23.stop();
      }
    }, _callee23);
  }));
  return _checkOMEMOSupported.apply(this, arguments);
}
function toggleOMEMO(ev) {
  ev.stopPropagation();
  ev.preventDefault();
  var toolbar_el = omemo_utils_u.ancestor(ev.target, 'converse-chat-toolbar');
  if (!toolbar_el.model.get('omemo_supported')) {
    var messages;
    if (toolbar_el.model.get('type') === shared_converse.CHATROOMS_TYPE) {
      messages = [__('Cannot use end-to-end encryption in this groupchat, ' + 'either the groupchat has some anonymity or not all participants support OMEMO.')];
    } else {
      messages = [__("Cannot use end-to-end encryption because %1$s uses a client that doesn't support OMEMO.", toolbar_el.model.contact.getDisplayName())];
    }
    return shared_api.alert('error', __('Error'), messages);
  }
  toolbar_el.model.save({
    'omemo_active': !toolbar_el.model.get('omemo_active')
  });
}
function getOMEMOToolbarButton(toolbar_el, buttons) {
  var model = toolbar_el.model;
  var is_muc = model.get('type') === shared_converse.CHATROOMS_TYPE;
  var title;
  if (model.get('omemo_supported')) {
    var i18n_plaintext = __('Messages are being sent in plaintext');
    var i18n_encrypted = __('Messages are sent encrypted');
    title = model.get('omemo_active') ? i18n_encrypted : i18n_plaintext;
  } else if (is_muc) {
    title = __('This groupchat needs to be members-only and non-anonymous in ' + 'order to support OMEMO encrypted messages');
  } else {
    title = __('OMEMO encryption is not supported');
  }
  var color;
  if (model.get('omemo_supported')) {
    if (model.get('omemo_active')) {
      color = is_muc ? "var(--muc-color)" : "var(--chat-toolbar-btn-color)";
    } else {
      color = "var(--error-color)";
    }
  } else {
    color = "var(--muc-toolbar-btn-disabled-color)";
  }
  buttons.push((0,external_lit_namespaceObject.html)(omemo_utils_templateObject3 || (omemo_utils_templateObject3 = omemo_utils_taggedTemplateLiteral(["\n        <button class=\"toggle-omemo\" title=\"", "\" data-disabled=", " @click=", ">\n            <converse-icon\n                class=\"fa ", "\"\n                path-prefix=\"", "\"\n                size=\"1em\"\n                color=\"", "\"\n            ></converse-icon>\n        </button>\n    "])), title, !model.get('omemo_supported'), toggleOMEMO, model.get('omemo_active') ? "fa-lock" : "fa-unlock", shared_api.settings.get('assets_path'), color));
  return buttons;
}
function getBundlesAndBuildSessions(_x26) {
  return _getBundlesAndBuildSessions.apply(this, arguments);
}
function _getBundlesAndBuildSessions() {
  _getBundlesAndBuildSessions = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee24(chatbox) {
    var no_devices_err, devices, collections, their_devices, err, own_list, own_devices, id, sessions, _err;
    return omemo_utils_regeneratorRuntime().wrap(function _callee24$(_context24) {
      while (1) switch (_context24.prev = _context24.next) {
        case 0:
          no_devices_err = __('Sorry, no devices found to which we can send an OMEMO encrypted message.');
          if (!(chatbox.get('type') === shared_converse.CHATROOMS_TYPE)) {
            _context24.next = 8;
            break;
          }
          _context24.next = 4;
          return Promise.all(chatbox.occupants.map(function (o) {
            return getDevicesForContact(o.get('jid'));
          }));
        case 4:
          collections = _context24.sent;
          devices = collections.reduce(function (a, b) {
            return lodash_es_concat(a, b.models);
          }, []);
          _context24.next = 21;
          break;
        case 8:
          if (!(chatbox.get('type') === shared_converse.PRIVATE_CHAT_TYPE)) {
            _context24.next = 21;
            break;
          }
          _context24.next = 11;
          return getDevicesForContact(chatbox.get('jid'));
        case 11:
          their_devices = _context24.sent;
          if (!(their_devices.length === 0)) {
            _context24.next = 16;
            break;
          }
          err = new Error(no_devices_err);
          err.user_facing = true;
          throw err;
        case 16:
          _context24.next = 18;
          return shared_api.omemo.devicelists.get(shared_converse.bare_jid);
        case 18:
          own_list = _context24.sent;
          own_devices = own_list.devices;
          devices = [].concat(omemo_utils_toConsumableArray(own_devices.models), omemo_utils_toConsumableArray(their_devices.models));
        case 21:
          // Filter out our own device
          id = shared_converse.omemo_store.get('device_id');
          devices = devices.filter(function (d) {
            return d.get('id') !== id;
          });
          // Fetch bundles if necessary
          _context24.next = 25;
          return Promise.all(devices.map(function (d) {
            return d.getBundle();
          }));
        case 25:
          sessions = devices.filter(function (d) {
            return d;
          }).map(function (d) {
            return getSession(d);
          });
          _context24.next = 28;
          return Promise.all(sessions);
        case 28:
          if (!sessions.includes(null)) {
            _context24.next = 34;
            break;
          }
          // We couldn't build a session for certain devices.
          devices = devices.filter(function (d) {
            return sessions[devices.indexOf(d)];
          });
          if (!(devices.length === 0)) {
            _context24.next = 34;
            break;
          }
          _err = new Error(no_devices_err);
          _err.user_facing = true;
          throw _err;
        case 34:
          return _context24.abrupt("return", devices);
        case 35:
        case "end":
          return _context24.stop();
      }
    }, _callee24);
  }));
  return _getBundlesAndBuildSessions.apply(this, arguments);
}
function encryptKey(key_and_tag, device) {
  return getSessionCipher(device.get('jid'), device.get('id')).encrypt(key_and_tag).then(function (payload) {
    return {
      'payload': payload,
      'device': device
    };
  });
}
function createOMEMOMessageStanza(_x27, _x28) {
  return _createOMEMOMessageStanza.apply(this, arguments);
}
function _createOMEMOMessageStanza() {
  _createOMEMOMessageStanza = omemo_utils_asyncToGenerator( /*#__PURE__*/omemo_utils_regeneratorRuntime().mark(function _callee25(chat, data) {
    var stanza, message, devices, _yield$omemo$encryptM, key_and_tag, iv, payload, dicts;
    return omemo_utils_regeneratorRuntime().wrap(function _callee25$(_context25) {
      while (1) switch (_context25.prev = _context25.next) {
        case 0:
          stanza = data.stanza;
          message = data.message;
          if (message.get('is_encrypted')) {
            _context25.next = 4;
            break;
          }
          return _context25.abrupt("return", data);
        case 4:
          if (message.get('body')) {
            _context25.next = 6;
            break;
          }
          throw new Error('No message body to encrypt!');
        case 6:
          _context25.next = 8;
          return getBundlesAndBuildSessions(chat);
        case 8:
          devices = _context25.sent;
          // An encrypted header is added to the message for
          // each device that is supposed to receive it.
          // These headers simply contain the key that the
          // payload message is encrypted with,
          // and they are separately encrypted using the
          // session corresponding to the counterpart device.
          stanza.c('encrypted', {
            'xmlns': omemo_utils_Strophe.NS.OMEMO
          }).c('header', {
            'sid': shared_converse.omemo_store.get('device_id')
          });
          _context25.next = 12;
          return omemo.encryptMessage(message.get('plaintext'));
        case 12:
          _yield$omemo$encryptM = _context25.sent;
          key_and_tag = _yield$omemo$encryptM.key_and_tag;
          iv = _yield$omemo$encryptM.iv;
          payload = _yield$omemo$encryptM.payload;
          _context25.next = 18;
          return Promise.all(devices.filter(function (device) {
            return device.get('trusted') != UNTRUSTED && device.get('active');
          }).map(function (device) {
            return encryptKey(key_and_tag, device);
          }));
        case 18:
          dicts = _context25.sent;
          _context25.next = 21;
          return addKeysToMessageStanza(stanza, dicts, iv);
        case 21:
          stanza = _context25.sent;
          stanza.c('payload').t(payload).up().up();
          stanza.c('store', {
            'xmlns': omemo_utils_Strophe.NS.HINTS
          }).up();
          stanza.c('encryption', {
            'xmlns': omemo_utils_Strophe.NS.EME,
            namespace: omemo_utils_Strophe.NS.OMEMO
          });
          return _context25.abrupt("return", {
            message: message,
            stanza: stanza
          });
        case 26:
        case "end":
          return _context25.stop();
      }
    }, _callee25);
  }));
  return _createOMEMOMessageStanza.apply(this, arguments);
}
var omemo = {
  decryptMessage: decryptMessage,
  encryptMessage: encryptMessage,
  formatFingerprint: formatFingerprint
};
;// CONCATENATED MODULE: ./src/plugins/omemo/templates/fingerprints.js
var fingerprints_templateObject, fingerprints_templateObject2, fingerprints_templateObject3;
function fingerprints_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



var device_fingerprint = function device_fingerprint(el, device) {
  var i18n_trusted = __('Trusted');
  var i18n_untrusted = __('Untrusted');
  if (device.get('bundle') && device.get('bundle').fingerprint) {
    return (0,external_lit_namespaceObject.html)(fingerprints_templateObject || (fingerprints_templateObject = fingerprints_taggedTemplateLiteral(["\n            <li class=\"list-group-item\">\n                <form class=\"fingerprint-trust\">\n                    <div class=\"btn-group btn-group-toggle\">\n                        <label class=\"btn btn--small ", "\"\n                                @click=", ">\n                            <input type=\"radio\" name=\"", "\" value=\"1\"\n                                ?checked=", ">", "\n                        </label>\n                        <label class=\"btn btn--small ", "\"\n                                @click=", ">\n                            <input type=\"radio\" name=\"", "\" value=\"-1\"\n                                ?checked=", ">", "\n                        </label>\n                    </div>\n                    <code class=\"fingerprint\">", "</code>\n                </form>\n            </li>\n        "])), device.get('trusted') === 1 ? 'btn-primary active' : 'btn-secondary', el.toggleDeviceTrust, device.get('id'), device.get('trusted') !== -1, i18n_trusted, device.get('trusted') === -1 ? 'btn-primary active' : 'btn-secondary', el.toggleDeviceTrust, device.get('id'), device.get('trusted') === -1, i18n_untrusted, formatFingerprint(device.get('bundle').fingerprint));
  } else {
    return '';
  }
};
/* harmony default export */ const fingerprints = (function (el) {
  var i18n_fingerprints = __('OMEMO Fingerprints');
  var i18n_no_devices = __("No OMEMO-enabled devices found");
  var devices = el.devicelist.devices;
  return (0,external_lit_namespaceObject.html)(fingerprints_templateObject2 || (fingerprints_templateObject2 = fingerprints_taggedTemplateLiteral(["\n        <hr/>\n        <ul class=\"list-group fingerprints\">\n            <li class=\"list-group-item active\">", "</li>\n            ", "\n        </ul>\n    "])), i18n_fingerprints, devices.length ? devices.map(function (device) {
    return device_fingerprint(el, device);
  }) : (0,external_lit_namespaceObject.html)(fingerprints_templateObject3 || (fingerprints_templateObject3 = fingerprints_taggedTemplateLiteral(["<li class=\"list-group-item\"> ", " </li>"])), i18n_no_devices));
});
;// CONCATENATED MODULE: ./src/plugins/omemo/fingerprints.js
function fingerprints_typeof(obj) {
  "@babel/helpers - typeof";

  return fingerprints_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;
  }, fingerprints_typeof(obj);
}
function fingerprints_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  fingerprints_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" == fingerprints_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 fingerprints_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 fingerprints_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        fingerprints_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        fingerprints_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function fingerprints_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function fingerprints_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, fingerprints_toPropertyKey(descriptor.key), descriptor);
  }
}
function fingerprints_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) fingerprints_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) fingerprints_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function fingerprints_toPropertyKey(arg) {
  var key = fingerprints_toPrimitive(arg, "string");
  return fingerprints_typeof(key) === "symbol" ? key : String(key);
}
function fingerprints_toPrimitive(input, hint) {
  if (fingerprints_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (fingerprints_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function fingerprints_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) fingerprints_setPrototypeOf(subClass, superClass);
}
function fingerprints_setPrototypeOf(o, p) {
  fingerprints_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return fingerprints_setPrototypeOf(o, p);
}
function fingerprints_createSuper(Derived) {
  var hasNativeReflectConstruct = fingerprints_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = fingerprints_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = fingerprints_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return fingerprints_possibleConstructorReturn(this, result);
  };
}
function fingerprints_possibleConstructorReturn(self, call) {
  if (call && (fingerprints_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 fingerprints_assertThisInitialized(self);
}
function fingerprints_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function fingerprints_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 fingerprints_getPrototypeOf(o) {
  fingerprints_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return fingerprints_getPrototypeOf(o);
}



var Fingerprints = /*#__PURE__*/function (_CustomElement) {
  fingerprints_inherits(Fingerprints, _CustomElement);
  var _super = fingerprints_createSuper(Fingerprints);
  function Fingerprints() {
    fingerprints_classCallCheck(this, Fingerprints);
    return _super.apply(this, arguments);
  }
  fingerprints_createClass(Fingerprints, [{
    key: "initialize",
    value: function () {
      var _initialize = fingerprints_asyncToGenerator( /*#__PURE__*/fingerprints_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return fingerprints_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.omemo.devicelists.get(this.jid, true);
            case 2:
              this.devicelist = _context.sent;
              this.listenTo(this.devicelist.devices, 'change:bundle', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'change:trusted', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'reset', function () {
                return _this.requestUpdate();
              });
              this.requestUpdate();
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return this.devicelist ? fingerprints(this) : '';
    }
  }, {
    key: "toggleDeviceTrust",
    value: function toggleDeviceTrust(ev) {
      var radio = ev.target;
      var device = this.devicelist.devices.get(radio.getAttribute('name'));
      device.save('trusted', parseInt(radio.value, 10));
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        'jid': {
          type: String
        }
      };
    }
  }]);
  return Fingerprints;
}(CustomElement);
shared_api.elements.define('converse-omemo-fingerprints', Fingerprints);
;// CONCATENATED MODULE: ./src/plugins/omemo/templates/profile.js
var templates_profile_templateObject, templates_profile_templateObject2, templates_profile_templateObject3, profile_templateObject4, profile_templateObject5, profile_templateObject6;
function templates_profile_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var fingerprint = function fingerprint(el) {
  return (0,external_lit_namespaceObject.html)(templates_profile_templateObject || (templates_profile_templateObject = templates_profile_taggedTemplateLiteral(["\n    <span class=\"fingerprint\">", "</span>"])), formatFingerprint(el.current_device.get('bundle').fingerprint));
};
var device_with_fingerprint = function device_with_fingerprint(el) {
  var i18n_fingerprint_checkbox_label = __('Checkbox for selecting the following fingerprint');
  return (0,external_lit_namespaceObject.html)(templates_profile_templateObject2 || (templates_profile_templateObject2 = templates_profile_taggedTemplateLiteral(["\n        <li class=\"fingerprint-removal-item list-group-item\">\n            <label>\n            <input type=\"checkbox\" value=\"", "\"\n                aria-label=\"", "\"/>\n            <span class=\"fingerprint\">", "</span>\n            </label>\n        </li>\n    "])), el.device.get('id'), i18n_fingerprint_checkbox_label, formatFingerprint(el.device.get('bundle').fingerprint));
};
var device_without_fingerprint = function device_without_fingerprint(el) {
  var i18n_device_without_fingerprint = __('Device without a fingerprint');
  var i18n_fingerprint_checkbox_label = __('Checkbox for selecting the following device');
  return (0,external_lit_namespaceObject.html)(templates_profile_templateObject3 || (templates_profile_templateObject3 = templates_profile_taggedTemplateLiteral(["\n        <li class=\"fingerprint-removal-item list-group-item\">\n            <label>\n            <input type=\"checkbox\" value=\"", "\"\n                aria-label=\"", "\"/>\n            <span>", "</span>\n            </label>\n        </li>\n    "])), el.device.get('id'), i18n_fingerprint_checkbox_label, i18n_device_without_fingerprint);
};
var device_item = function device_item(el) {
  return (0,external_lit_namespaceObject.html)(profile_templateObject4 || (profile_templateObject4 = templates_profile_taggedTemplateLiteral(["\n    ", "\n"])), el.device.get('bundle') && el.device.get('bundle').fingerprint ? device_with_fingerprint(el) : device_without_fingerprint(el));
};
var device_list = function device_list(el) {
  var _el$other_devices;
  var i18n_other_devices = __('Other OMEMO-enabled devices');
  var i18n_other_devices_label = __('Checkbox to select fingerprints of all other OMEMO devices');
  var i18n_remove_devices = __('Remove checked devices and close');
  var i18n_select_all = __('Select all');
  return (0,external_lit_namespaceObject.html)(profile_templateObject5 || (profile_templateObject5 = templates_profile_taggedTemplateLiteral(["\n        <ul class=\"list-group fingerprints\">\n            <li class=\"list-group-item active\">\n                <label>\n                    <input type=\"checkbox\" class=\"select-all\" @change=", " title=\"", "\" aria-label=\"", "\"/>\n                    ", "\n                </label>\n            </li>\n            ", "\n        </ul>\n        <div class=\"form-group\"><button type=\"submit\" class=\"save-form btn btn-primary\">", "</button></div>\n    "])), el.selectAll, i18n_select_all, i18n_other_devices_label, i18n_other_devices, (_el$other_devices = el.other_devices) === null || _el$other_devices === void 0 ? void 0 : _el$other_devices.map(function (device) {
    return device_item(Object.assign({
      device: device
    }, el));
  }), i18n_remove_devices);
};
/* harmony default export */ const templates_profile = (function (el) {
  var _el$other_devices2;
  var i18n_fingerprint = __("This device's OMEMO fingerprint");
  var i18n_generate = __('Generate new keys and fingerprint');
  return (0,external_lit_namespaceObject.html)(profile_templateObject6 || (profile_templateObject6 = templates_profile_taggedTemplateLiteral(["\n        <form class=\"converse-form fingerprint-removal\" @submit=", ">\n            <ul class=\"list-group fingerprints\">\n                <li class=\"list-group-item active\">", "</li>\n                <li class=\"list-group-item\">\n                    ", "\n                </li>\n            </ul>\n            <div class=\"form-group\">\n                <button type=\"button\" class=\"generate-bundle btn btn-danger\" @click=", ">", "</button>\n            </div>\n            ", "\n        </form>"])), el.removeSelectedFingerprints, i18n_fingerprint, el.current_device && el.current_device.get('bundle') && el.current_device.get('bundle').fingerprint ? fingerprint(el) : spinner(), el.generateOMEMODeviceBundle, i18n_generate, (_el$other_devices2 = el.other_devices) !== null && _el$other_devices2 !== void 0 && _el$other_devices2.length ? device_list(el) : '');
});
;// CONCATENATED MODULE: ./src/plugins/omemo/profile.js
function omemo_profile_typeof(obj) {
  "@babel/helpers - typeof";

  return omemo_profile_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;
  }, omemo_profile_typeof(obj);
}
function omemo_profile_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  omemo_profile_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" == omemo_profile_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 omemo_profile_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 omemo_profile_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        omemo_profile_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        omemo_profile_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function omemo_profile_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function omemo_profile_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, omemo_profile_toPropertyKey(descriptor.key), descriptor);
  }
}
function omemo_profile_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) omemo_profile_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) omemo_profile_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function omemo_profile_toPropertyKey(arg) {
  var key = omemo_profile_toPrimitive(arg, "string");
  return omemo_profile_typeof(key) === "symbol" ? key : String(key);
}
function omemo_profile_toPrimitive(input, hint) {
  if (omemo_profile_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (omemo_profile_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function omemo_profile_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) omemo_profile_setPrototypeOf(subClass, superClass);
}
function omemo_profile_setPrototypeOf(o, p) {
  omemo_profile_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return omemo_profile_setPrototypeOf(o, p);
}
function omemo_profile_createSuper(Derived) {
  var hasNativeReflectConstruct = omemo_profile_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = omemo_profile_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = omemo_profile_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return omemo_profile_possibleConstructorReturn(this, result);
  };
}
function omemo_profile_possibleConstructorReturn(self, call) {
  if (call && (omemo_profile_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 omemo_profile_assertThisInitialized(self);
}
function omemo_profile_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function omemo_profile_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 omemo_profile_getPrototypeOf(o) {
  omemo_profile_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return omemo_profile_getPrototypeOf(o);
}






var profile_converse$env = public_converse.env,
  profile_Strophe = profile_converse$env.Strophe,
  profile_sizzle = profile_converse$env.sizzle,
  profile_u = profile_converse$env.u;
var profile_Profile = /*#__PURE__*/function (_CustomElement) {
  omemo_profile_inherits(Profile, _CustomElement);
  var _super = omemo_profile_createSuper(Profile);
  function Profile() {
    omemo_profile_classCallCheck(this, Profile);
    return _super.apply(this, arguments);
  }
  omemo_profile_createClass(Profile, [{
    key: "initialize",
    value: function () {
      var _initialize = omemo_profile_asyncToGenerator( /*#__PURE__*/omemo_profile_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return omemo_profile_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.omemo.devicelists.get(shared_converse.bare_jid, true);
            case 2:
              this.devicelist = _context.sent;
              _context.next = 5;
              return this.setAttributes();
            case 5:
              this.listenTo(this.devicelist.devices, 'change:bundle', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'reset', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'reset', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.devicelist.devices, 'add', function () {
                return _this.requestUpdate();
              });
              this.requestUpdate();
            case 11:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "setAttributes",
    value: function () {
      var _setAttributes = omemo_profile_asyncToGenerator( /*#__PURE__*/omemo_profile_regeneratorRuntime().mark(function _callee2() {
        var _this2 = this;
        return omemo_profile_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return shared_api.omemo.getDeviceID();
            case 2:
              this.device_id = _context2.sent;
              this.current_device = this.devicelist.devices.get(this.device_id);
              this.other_devices = this.devicelist.devices.filter(function (d) {
                return d.get('id') !== _this2.device_id;
              });
            case 5:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function setAttributes() {
        return _setAttributes.apply(this, arguments);
      }
      return setAttributes;
    }()
  }, {
    key: "render",
    value: function render() {
      return this.devicelist ? templates_profile(this) : spinner();
    }
  }, {
    key: "selectAll",
    value: function selectAll(ev) {
      // eslint-disable-line class-methods-use-this
      var sibling = profile_u.ancestor(ev.target, 'li');
      while (sibling) {
        sibling.querySelector('input[type="checkbox"]').checked = ev.target.checked;
        sibling = sibling.nextElementSibling;
      }
    }
  }, {
    key: "removeSelectedFingerprints",
    value: function () {
      var _removeSelectedFingerprints = omemo_profile_asyncToGenerator( /*#__PURE__*/omemo_profile_regeneratorRuntime().mark(function _callee3(ev) {
        var device_ids;
        return omemo_profile_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              ev.preventDefault();
              ev.stopPropagation();
              ev.target.querySelector('.select-all').checked = false;
              device_ids = profile_sizzle('.fingerprint-removal-item input[type="checkbox"]:checked', ev.target).map(function (c) {
                return c.value;
              });
              _context3.prev = 4;
              _context3.next = 7;
              return this.devicelist.removeOwnDevices(device_ids);
            case 7:
              _context3.next = 13;
              break;
            case 9:
              _context3.prev = 9;
              _context3.t0 = _context3["catch"](4);
              log.error(_context3.t0);
              shared_converse.api.alert(profile_Strophe.LogLevel.ERROR, __('Error'), [__('Sorry, an error occurred while trying to remove the devices.')]);
            case 13:
              _context3.next = 15;
              return this.setAttributes();
            case 15:
              this.requestUpdate();
            case 16:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this, [[4, 9]]);
      }));
      function removeSelectedFingerprints(_x) {
        return _removeSelectedFingerprints.apply(this, arguments);
      }
      return removeSelectedFingerprints;
    }()
  }, {
    key: "generateOMEMODeviceBundle",
    value: function () {
      var _generateOMEMODeviceBundle = omemo_profile_asyncToGenerator( /*#__PURE__*/omemo_profile_regeneratorRuntime().mark(function _callee4(ev) {
        var result;
        return omemo_profile_regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              ev.preventDefault();
              _context4.next = 3;
              return shared_api.confirm(__('Are you sure you want to generate new OMEMO keys? ' + 'This will remove your old keys and all previously ' + 'encrypted messages will no longer be decryptable on this device.'));
            case 3:
              result = _context4.sent;
              if (!result) {
                _context4.next = 10;
                break;
              }
              _context4.next = 7;
              return shared_api.omemo.bundle.generate();
            case 7:
              _context4.next = 9;
              return this.setAttributes();
            case 9:
              this.requestUpdate();
            case 10:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function generateOMEMODeviceBundle(_x2) {
        return _generateOMEMODeviceBundle.apply(this, arguments);
      }
      return generateOMEMODeviceBundle;
    }()
  }]);
  return Profile;
}(CustomElement);
shared_api.elements.define('converse-omemo-profile', profile_Profile);
;// CONCATENATED MODULE: ./src/plugins/omemo/mixins/converse.js
function converse_typeof(obj) {
  "@babel/helpers - typeof";

  return converse_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;
  }, converse_typeof(obj);
}
function converse_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  converse_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" == converse_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 converse_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 converse_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        converse_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        converse_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

var ConverseMixins = {
  generateFingerprints: function generateFingerprints(jid) {
    return converse_asyncToGenerator( /*#__PURE__*/converse_regeneratorRuntime().mark(function _callee() {
      var devices;
      return converse_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getDevicesForContact(jid);
          case 2:
            devices = _context.sent;
            return _context.abrupt("return", Promise.all(devices.map(function (d) {
              return generateFingerprint(d);
            })));
          case 4:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  getDeviceForContact: function getDeviceForContact(jid, device_id) {
    return getDevicesForContact(jid).then(function (devices) {
      return devices.get(device_id);
    });
  },
  contactHasOMEMOSupport: function contactHasOMEMOSupport(jid) {
    return converse_asyncToGenerator( /*#__PURE__*/converse_regeneratorRuntime().mark(function _callee2() {
      var devices;
      return converse_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return getDevicesForContact(jid);
          case 2:
            devices = _context2.sent;
            return _context2.abrupt("return", devices.length > 0);
          case 4:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  }
};
/* harmony default export */ const mixins_converse = (ConverseMixins);
;// CONCATENATED MODULE: ./src/plugins/omemo/errors.js
function omemo_errors_typeof(obj) {
  "@babel/helpers - typeof";

  return omemo_errors_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;
  }, omemo_errors_typeof(obj);
}
function omemo_errors_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, omemo_errors_toPropertyKey(descriptor.key), descriptor);
  }
}
function omemo_errors_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) omemo_errors_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) omemo_errors_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function omemo_errors_toPropertyKey(arg) {
  var key = omemo_errors_toPrimitive(arg, "string");
  return omemo_errors_typeof(key) === "symbol" ? key : String(key);
}
function omemo_errors_toPrimitive(input, hint) {
  if (omemo_errors_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (omemo_errors_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function omemo_errors_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function omemo_errors_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) omemo_errors_setPrototypeOf(subClass, superClass);
}
function omemo_errors_createSuper(Derived) {
  var hasNativeReflectConstruct = omemo_errors_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = omemo_errors_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = omemo_errors_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return omemo_errors_possibleConstructorReturn(this, result);
  };
}
function omemo_errors_possibleConstructorReturn(self, call) {
  if (call && (omemo_errors_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 omemo_errors_assertThisInitialized(self);
}
function omemo_errors_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function omemo_errors_wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  omemo_errors_wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !omemo_errors_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return omemo_errors_construct(Class, arguments, omemo_errors_getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return omemo_errors_setPrototypeOf(Wrapper, Class);
  };
  return omemo_errors_wrapNativeSuper(Class);
}
function omemo_errors_construct(Parent, args, Class) {
  if (omemo_errors_isNativeReflectConstruct()) {
    omemo_errors_construct = Reflect.construct.bind();
  } else {
    omemo_errors_construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) omemo_errors_setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return omemo_errors_construct.apply(null, arguments);
}
function omemo_errors_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 omemo_errors_isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function omemo_errors_setPrototypeOf(o, p) {
  omemo_errors_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return omemo_errors_setPrototypeOf(o, p);
}
function omemo_errors_getPrototypeOf(o) {
  omemo_errors_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return omemo_errors_getPrototypeOf(o);
}
var IQError = /*#__PURE__*/function (_Error) {
  omemo_errors_inherits(IQError, _Error);
  var _super = omemo_errors_createSuper(IQError);
  function IQError(message, iq) {
    var _this;
    omemo_errors_classCallCheck(this, IQError);
    _this = _super.call(this, message, iq);
    _this.name = 'IQError';
    _this.iq = iq;
    return _this;
  }
  return omemo_errors_createClass(IQError);
}( /*#__PURE__*/omemo_errors_wrapNativeSuper(Error));
;// CONCATENATED MODULE: ./src/plugins/omemo/device.js
function device_typeof(obj) {
  "@babel/helpers - typeof";

  return device_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;
  }, device_typeof(obj);
}
function device_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  device_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" == device_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 device_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 device_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        device_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        device_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}







var device_converse$env = public_converse.env,
  device_Strophe = device_converse$env.Strophe,
  device_sizzle = device_converse$env.sizzle,
  device_$iq = device_converse$env.$iq;

/**
 * @class
 * @namespace _converse.Device
 * @memberOf _converse
 */
var Device = Model.extend({
  defaults: {
    'trusted': UNDECIDED,
    'active': true
  },
  getRandomPreKey: function getRandomPreKey() {
    // XXX: assumes that the bundle has already been fetched
    var bundle = this.get('bundle');
    return bundle.prekeys[getRandomInt(bundle.prekeys.length)];
  },
  fetchBundleFromServer: function fetchBundleFromServer() {
    var _this = this;
    return device_asyncToGenerator( /*#__PURE__*/device_regeneratorRuntime().mark(function _callee() {
      var stanza, iq, publish_el, bundle_el, bundle;
      return device_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            stanza = device_$iq({
              'type': 'get',
              'from': shared_converse.bare_jid,
              'to': _this.get('jid')
            }).c('pubsub', {
              'xmlns': device_Strophe.NS.PUBSUB
            }).c('items', {
              'node': "".concat(device_Strophe.NS.OMEMO_BUNDLES, ":").concat(_this.get('id'))
            });
            _context.prev = 1;
            _context.next = 4;
            return shared_api.sendIQ(stanza);
          case 4:
            iq = _context.sent;
            _context.next = 12;
            break;
          case 7:
            _context.prev = 7;
            _context.t0 = _context["catch"](1);
            log.error("Could not fetch bundle for device ".concat(_this.get('id'), " from ").concat(_this.get('jid')));
            log.error(_context.t0);
            return _context.abrupt("return", null);
          case 12:
            if (!iq.querySelector('error')) {
              _context.next = 14;
              break;
            }
            throw new IQError('Could not fetch bundle', iq);
          case 14:
            publish_el = device_sizzle("items[node=\"".concat(device_Strophe.NS.OMEMO_BUNDLES, ":").concat(_this.get('id'), "\"]"), iq).pop();
            bundle_el = device_sizzle("bundle[xmlns=\"".concat(device_Strophe.NS.OMEMO, "\"]"), publish_el).pop();
            bundle = parseBundle(bundle_el);
            _this.save('bundle', bundle);
            return _context.abrupt("return", bundle);
          case 19:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[1, 7]]);
    }))();
  },
  /**
   * Fetch and save the bundle information associated with
   * this device, if the information is not cached already.
   * @method _converse.Device#getBundle
   */
  getBundle: function getBundle() {
    if (this.get('bundle')) {
      return Promise.resolve(this.get('bundle'), this);
    } else {
      return this.fetchBundleFromServer();
    }
  }
});
/* harmony default export */ const device = (Device);
;// CONCATENATED MODULE: ./src/plugins/omemo/devicelist.js
function devicelist_typeof(obj) {
  "@babel/helpers - typeof";

  return devicelist_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;
  }, devicelist_typeof(obj);
}
function devicelist_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  devicelist_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" == devicelist_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 devicelist_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 devicelist_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        devicelist_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        devicelist_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}






var devicelist_converse$env = public_converse.env,
  devicelist_Strophe = devicelist_converse$env.Strophe,
  devicelist_$build = devicelist_converse$env.$build,
  devicelist_$iq = devicelist_converse$env.$iq,
  devicelist_sizzle = devicelist_converse$env.sizzle;

/**
 * @class
 * @namespace _converse.DeviceList
 * @memberOf _converse
 */
var DeviceList = Model.extend({
  idAttribute: 'jid',
  initialize: function initialize() {
    var _this = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee() {
      return devicelist_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.initialized = getOpenPromise();
            _context.next = 3;
            return _this.initDevices();
          case 3:
            _this.initialized.resolve();
          case 4:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  initDevices: function initDevices() {
    this.devices = new shared_converse.Devices();
    var id = "converse.devicelist-".concat(shared_converse.bare_jid, "-").concat(this.get('jid'));
    initStorage(this.devices, id);
    return this.fetchDevices();
  },
  onDevicesFound: function onDevicesFound(collection) {
    var _this2 = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee2() {
      var ids;
      return devicelist_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            if (!(collection.length === 0)) {
              _context2.next = 13;
              break;
            }
            ids = [];
            _context2.prev = 2;
            _context2.next = 5;
            return _this2.fetchDevicesFromServer();
          case 5:
            ids = _context2.sent;
            _context2.next = 12;
            break;
          case 8:
            _context2.prev = 8;
            _context2.t0 = _context2["catch"](2);
            if (_context2.t0 === null) {
              log.error("Timeout error while fetching devices for ".concat(_this2.get('jid')));
            } else {
              log.error("Could not fetch devices for ".concat(_this2.get('jid')));
              log.error(_context2.t0);
            }
            _this2.destroy();
          case 12:
            if (_this2.get('jid') === shared_converse.bare_jid) {
              _this2.publishCurrentDevice(ids);
            }
          case 13:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[2, 8]]);
    }))();
  },
  fetchDevices: function fetchDevices() {
    var _this3 = this;
    if (this._devices_promise === undefined) {
      this._devices_promise = new Promise(function (resolve) {
        _this3.devices.fetch({
          'success': function success(c) {
            return resolve(_this3.onDevicesFound(c));
          },
          'error': function error(_, e) {
            log.error(e);
            resolve();
          }
        });
      });
    }
    return this._devices_promise;
  },
  getOwnDeviceId: function getOwnDeviceId() {
    var _this4 = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee3() {
      var device_id;
      return devicelist_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            device_id = shared_converse.omemo_store.get('device_id');
            if (_this4.devices.get(device_id)) {
              _context3.next = 5;
              break;
            }
            _context3.next = 4;
            return shared_converse.omemo_store.generateBundle();
          case 4:
            device_id = shared_converse.omemo_store.get('device_id');
          case 5:
            return _context3.abrupt("return", device_id);
          case 6:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  },
  publishCurrentDevice: function publishCurrentDevice(device_ids) {
    var _this5 = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee4() {
      return devicelist_regeneratorRuntime().wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            if (!(_this5.get('jid') !== shared_converse.bare_jid)) {
              _context4.next = 2;
              break;
            }
            return _context4.abrupt("return");
          case 2:
            _context4.next = 4;
            return restoreOMEMOSession();
          case 4:
            if (shared_converse.omemo_store) {
              _context4.next = 7;
              break;
            }
            // Happens during tests. The connection gets torn down
            // before publishCurrentDevice has time to finish.
            log.warn('publishCurrentDevice: omemo_store is not defined, likely a timing issue');
            return _context4.abrupt("return");
          case 7:
            _context4.t0 = device_ids;
            _context4.next = 10;
            return _this5.getOwnDeviceId();
          case 10:
            _context4.t1 = _context4.sent;
            if (_context4.t0.includes.call(_context4.t0, _context4.t1)) {
              _context4.next = 13;
              break;
            }
            return _context4.abrupt("return", _this5.publishDevices());
          case 13:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }))();
  },
  fetchDevicesFromServer: function fetchDevicesFromServer() {
    var _this6 = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee5() {
      var stanza, iq, selector, device_ids, jid;
      return devicelist_regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            stanza = devicelist_$iq({
              'type': 'get',
              'from': shared_converse.bare_jid,
              'to': _this6.get('jid')
            }).c('pubsub', {
              'xmlns': devicelist_Strophe.NS.PUBSUB
            }).c('items', {
              'node': devicelist_Strophe.NS.OMEMO_DEVICELIST
            });
            _context5.next = 3;
            return shared_api.sendIQ(stanza);
          case 3:
            iq = _context5.sent;
            selector = "list[xmlns=\"".concat(devicelist_Strophe.NS.OMEMO, "\"] device");
            device_ids = devicelist_sizzle(selector, iq).map(function (d) {
              return d.getAttribute('id');
            });
            jid = _this6.get('jid');
            return _context5.abrupt("return", Promise.all(device_ids.map(function (id) {
              return _this6.devices.create({
                id: id,
                jid: jid
              }, {
                'promise': true
              });
            })));
          case 8:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    }))();
  },
  /**
   * Send an IQ stanza to the current user's "devices" PEP node to
   * ensure that all devices are published for potential chat partners to see.
   * See: https://xmpp.org/extensions/xep-0384.html#usecases-announcing
   */
  publishDevices: function publishDevices() {
    var item = devicelist_$build('item', {
      'id': 'current'
    }).c('list', {
      'xmlns': devicelist_Strophe.NS.OMEMO
    });
    this.devices.filter(function (d) {
      return d.get('active');
    }).forEach(function (d) {
      return item.c('device', {
        'id': d.get('id')
      }).up();
    });
    var options = {
      'pubsub#access_model': 'open'
    };
    return shared_api.pubsub.publish(null, devicelist_Strophe.NS.OMEMO_DEVICELIST, item, options, false);
  },
  removeOwnDevices: function removeOwnDevices(device_ids) {
    var _this7 = this;
    return devicelist_asyncToGenerator( /*#__PURE__*/devicelist_regeneratorRuntime().mark(function _callee6() {
      return devicelist_regeneratorRuntime().wrap(function _callee6$(_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            if (!(_this7.get('jid') !== shared_converse.bare_jid)) {
              _context6.next = 2;
              break;
            }
            throw new Error("Cannot remove devices from someone else's device list");
          case 2:
            _context6.next = 4;
            return Promise.all(device_ids.map(function (id) {
              return _this7.devices.get(id);
            }).map(function (d) {
              return new Promise(function (resolve) {
                return d.destroy({
                  'success': resolve,
                  'error': function error(_, e) {
                    log.error(e);
                    resolve();
                  }
                });
              });
            }));
          case 4:
            return _context6.abrupt("return", _this7.publishDevices());
          case 5:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    }))();
  }
});
/* harmony default export */ const devicelist = (DeviceList);
;// CONCATENATED MODULE: ./src/plugins/omemo/devicelists.js



/**
 * @class
 * @namespace _converse.DeviceLists
 * @memberOf _converse
 */
var DeviceLists = Collection.extend({
  model: devicelist
});
/* harmony default export */ const devicelists = (DeviceLists);
;// CONCATENATED MODULE: ./src/plugins/omemo/devices.js


/* harmony default export */ const devices = (Collection.extend({
  model: device
}));
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRange.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
  _baseRange_nativeMax = Math.max;

/**
 * The base implementation of `_.range` and `_.rangeRight` which doesn't
 * coerce arguments.
 *
 * @private
 * @param {number} start The start of the range.
 * @param {number} end The end of the range.
 * @param {number} step The value to increment or decrement by.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Array} Returns the range of numbers.
 */
function baseRange(start, end, step, fromRight) {
  var index = -1,
    length = _baseRange_nativeMax(nativeCeil((end - start) / (step || 1)), 0),
    result = Array(length);
  while (length--) {
    result[fromRight ? length : ++index] = start;
    start += step;
  }
  return result;
}
/* harmony default export */ const _baseRange = (baseRange);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createRange.js




/**
 * Creates a `_.range` or `_.rangeRight` function.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new range function.
 */
function createRange(fromRight) {
  return function (start, end, step) {
    if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) {
      end = step = undefined;
    }
    // Ensure the sign of `-0` is preserved.
    start = lodash_es_toFinite(start);
    if (end === undefined) {
      end = start;
      start = 0;
    } else {
      end = lodash_es_toFinite(end);
    }
    step = step === undefined ? start < end ? 1 : -1 : lodash_es_toFinite(step);
    return _baseRange(start, end, step, fromRight);
  };
}
/* harmony default export */ const _createRange = (createRange);
;// CONCATENATED MODULE: ./node_modules/lodash-es/range.js


/**
 * Creates an array of numbers (positive and/or negative) progressing from
 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
 * `start` is specified without an `end` or `step`. If `end` is not specified,
 * it's set to `start` with `start` then set to `0`.
 *
 * **Note:** JavaScript follows the IEEE-754 standard for resolving
 * floating-point values which can produce unexpected results.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {number} [start=0] The start of the range.
 * @param {number} end The end of the range.
 * @param {number} [step=1] The value to increment or decrement by.
 * @returns {Array} Returns the range of numbers.
 * @see _.inRange, _.rangeRight
 * @example
 *
 * _.range(4);
 * // => [0, 1, 2, 3]
 *
 * _.range(-4);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 5);
 * // => [1, 2, 3, 4]
 *
 * _.range(0, 20, 5);
 * // => [0, 5, 10, 15]
 *
 * _.range(0, -4, -1);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 4, 0);
 * // => [1, 1, 1]
 *
 * _.range(0);
 * // => []
 */
var range = _createRange();
/* harmony default export */ const lodash_es_range = (range);
;// CONCATENATED MODULE: ./src/plugins/omemo/store.js
function store_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  store_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" == store_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 store_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 store_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        store_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        store_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function store_typeof(obj) {
  "@babel/helpers - typeof";

  return store_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;
  }, store_typeof(obj);
}
/* global libsignal */








var store_converse$env = public_converse.env,
  store_Strophe = store_converse$env.Strophe,
  store_$build = store_converse$env.$build,
  store_u = store_converse$env.u;
var OMEMOStore = Model.extend({
  Direction: {
    SENDING: 1,
    RECEIVING: 2
  },
  getIdentityKeyPair: function getIdentityKeyPair() {
    var keypair = this.get('identity_keypair');
    return Promise.resolve({
      'privKey': store_u.base64ToArrayBuffer(keypair.privKey),
      'pubKey': store_u.base64ToArrayBuffer(keypair.pubKey)
    });
  },
  getLocalRegistrationId: function getLocalRegistrationId() {
    return Promise.resolve(parseInt(this.get('device_id'), 10));
  },
  isTrustedIdentity: function isTrustedIdentity(identifier, identity_key, direction) {
    // eslint-disable-line no-unused-vars
    if (identifier === null || identifier === undefined) {
      throw new Error("Can't check identity key for invalid key");
    }
    if (!(identity_key instanceof ArrayBuffer)) {
      throw new Error('Expected identity_key to be an ArrayBuffer');
    }
    var trusted = this.get('identity_key' + identifier);
    if (trusted === undefined) {
      return Promise.resolve(true);
    }
    return Promise.resolve(store_u.arrayBufferToBase64(identity_key) === trusted);
  },
  loadIdentityKey: function loadIdentityKey(identifier) {
    if (identifier === null || identifier === undefined) {
      throw new Error("Can't load identity_key for invalid identifier");
    }
    return Promise.resolve(store_u.base64ToArrayBuffer(this.get('identity_key' + identifier)));
  },
  saveIdentity: function saveIdentity(identifier, identity_key) {
    if (identifier === null || identifier === undefined) {
      throw new Error("Can't save identity_key for invalid identifier");
    }
    var address = new libsignal.SignalProtocolAddress.fromString(identifier);
    var existing = this.get('identity_key' + address.getName());
    var b64_idkey = store_u.arrayBufferToBase64(identity_key);
    this.save('identity_key' + address.getName(), b64_idkey);
    if (existing && b64_idkey !== existing) {
      return Promise.resolve(true);
    } else {
      return Promise.resolve(false);
    }
  },
  getPreKeys: function getPreKeys() {
    return this.get('prekeys') || {};
  },
  loadPreKey: function loadPreKey(key_id) {
    var res = this.getPreKeys()[key_id];
    if (res) {
      return Promise.resolve({
        'privKey': store_u.base64ToArrayBuffer(res.privKey),
        'pubKey': store_u.base64ToArrayBuffer(res.pubKey)
      });
    }
    return Promise.resolve();
  },
  storePreKey: function storePreKey(key_id, key_pair) {
    var prekey = {};
    prekey[key_id] = {
      'pubKey': store_u.arrayBufferToBase64(key_pair.pubKey),
      'privKey': store_u.arrayBufferToBase64(key_pair.privKey)
    };
    this.save('prekeys', Object.assign(this.getPreKeys(), prekey));
    return Promise.resolve();
  },
  removePreKey: function removePreKey(key_id) {
    this.save('prekeys', lodash_es_omit(this.getPreKeys(), key_id));
    return Promise.resolve();
  },
  loadSignedPreKey: function loadSignedPreKey(keyId) {
    // eslint-disable-line no-unused-vars
    var res = this.get('signed_prekey');
    if (res) {
      return Promise.resolve({
        'privKey': store_u.base64ToArrayBuffer(res.privKey),
        'pubKey': store_u.base64ToArrayBuffer(res.pubKey)
      });
    }
    return Promise.resolve();
  },
  storeSignedPreKey: function storeSignedPreKey(spk) {
    if (store_typeof(spk) !== 'object') {
      // XXX: We've changed the signature of this method from the
      // example given in InMemorySignalProtocolStore.
      // Should be fine because the libsignal code doesn't
      // actually call this method.
      throw new Error('storeSignedPreKey: expected an object');
    }
    this.save('signed_prekey', {
      'id': spk.keyId,
      'privKey': store_u.arrayBufferToBase64(spk.keyPair.privKey),
      'pubKey': store_u.arrayBufferToBase64(spk.keyPair.pubKey),
      // XXX: The InMemorySignalProtocolStore does not pass
      // in or store the signature, but we need it when we
      // publish our bundle and this method isn't called from
      // within libsignal code, so we modify it to also store
      // the signature.
      'signature': store_u.arrayBufferToBase64(spk.signature)
    });
    return Promise.resolve();
  },
  removeSignedPreKey: function removeSignedPreKey(key_id) {
    if (this.get('signed_prekey')['id'] === key_id) {
      this.unset('signed_prekey');
      this.save();
    }
    return Promise.resolve();
  },
  loadSession: function loadSession(identifier) {
    return Promise.resolve(this.get('session' + identifier));
  },
  storeSession: function storeSession(identifier, record) {
    return Promise.resolve(this.save('session' + identifier, record));
  },
  removeSession: function removeSession(identifier) {
    return Promise.resolve(this.unset('session' + identifier));
  },
  removeAllSessions: function removeAllSessions(identifier) {
    var keys = Object.keys(this.attributes).filter(function (key) {
      return key.startsWith('session' + identifier) ? key : false;
    });
    var attrs = {};
    keys.forEach(function (key) {
      attrs[key] = undefined;
    });
    this.save(attrs);
    return Promise.resolve();
  },
  publishBundle: function publishBundle() {
    var signed_prekey = this.get('signed_prekey');
    var node = "".concat(store_Strophe.NS.OMEMO_BUNDLES, ":").concat(this.get('device_id'));
    var item = store_$build('item').c('bundle', {
      'xmlns': store_Strophe.NS.OMEMO
    }).c('signedPreKeyPublic', {
      'signedPreKeyId': signed_prekey.id
    }).t(signed_prekey.pubKey).up().c('signedPreKeySignature').t(signed_prekey.signature).up().c('identityKey').t(this.get('identity_keypair').pubKey).up().c('prekeys');
    Object.values(this.get('prekeys')).forEach(function (prekey, id) {
      return item.c('preKeyPublic', {
        'preKeyId': id
      }).t(prekey.pubKey).up();
    });
    var options = {
      'pubsub#access_model': 'open'
    };
    return shared_api.pubsub.publish(null, node, item, options, false);
  },
  generateMissingPreKeys: function generateMissingPreKeys() {
    var _this = this;
    return store_asyncToGenerator( /*#__PURE__*/store_regeneratorRuntime().mark(function _callee() {
      var missing_keys, keys, marshalled_keys, devicelist, device, bundle;
      return store_regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            missing_keys = lodash_es_difference(lodash_es_invokeMap(lodash_es_range(0, shared_converse.NUM_PREKEYS), Number.prototype.toString), Object.keys(_this.getPreKeys()));
            if (!(missing_keys.length < 1)) {
              _context.next = 4;
              break;
            }
            log.warn('No missing prekeys to generate for our own device');
            return _context.abrupt("return", Promise.resolve());
          case 4:
            _context.next = 6;
            return Promise.all(missing_keys.map(function (id) {
              return libsignal.KeyHelper.generatePreKey(parseInt(id, 10));
            }));
          case 6:
            keys = _context.sent;
            keys.forEach(function (k) {
              return _this.storePreKey(k.keyId, k.keyPair);
            });
            marshalled_keys = Object.keys(_this.getPreKeys()).map(function (k) {
              return {
                'id': k.keyId,
                'key': store_u.arrayBufferToBase64(k.pubKey)
              };
            });
            _context.next = 11;
            return shared_api.omemo.devicelists.get(shared_converse.bare_jid);
          case 11:
            devicelist = _context.sent;
            device = devicelist.devices.get(_this.get('device_id'));
            _context.next = 15;
            return device.getBundle();
          case 15:
            bundle = _context.sent;
            device.save('bundle', Object.assign(bundle, {
              'prekeys': marshalled_keys
            }));
          case 17:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }))();
  },
  /**
   * Generates, stores and then returns pre-keys.
   *
   * Pre-keys are one half of a X3DH key exchange and are published as part
   * of the device bundle.
   *
   * For a new contact or device to establish an encrypted session, it needs
   * to use a pre-key, which it chooses randomly from the list of available
   * ones.
   */
  generatePreKeys: function generatePreKeys() {
    var _this2 = this;
    return store_asyncToGenerator( /*#__PURE__*/store_regeneratorRuntime().mark(function _callee2() {
      var amount, _libsignal, KeyHelper, keys;
      return store_regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            amount = shared_converse.NUM_PREKEYS;
            _libsignal = libsignal, KeyHelper = _libsignal.KeyHelper;
            _context2.next = 4;
            return Promise.all(lodash_es_range(0, amount).map(function (id) {
              return KeyHelper.generatePreKey(id);
            }));
          case 4:
            keys = _context2.sent;
            keys.forEach(function (k) {
              return _this2.storePreKey(k.keyId, k.keyPair);
            });
            return _context2.abrupt("return", keys.map(function (k) {
              return {
                'id': k.keyId,
                'key': store_u.arrayBufferToBase64(k.keyPair.pubKey)
              };
            }));
          case 7:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }))();
  },
  /**
   * Generate the cryptographic data used by the X3DH key agreement protocol
   * in order to build a session with other devices.
   *
   * By generating a bundle, and publishing it via PubSub, we allow other
   * clients to download it and start asynchronous encrypted sessions with us,
   * even if we're offline at that time.
   */
  generateBundle: function generateBundle() {
    var _this3 = this;
    return store_asyncToGenerator( /*#__PURE__*/store_regeneratorRuntime().mark(function _callee3() {
      var identity_keypair, identity_key, device_id, signed_prekey, prekeys, bundle, devicelist, device;
      return store_regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return libsignal.KeyHelper.generateIdentityKeyPair();
          case 2:
            identity_keypair = _context3.sent;
            identity_key = store_u.arrayBufferToBase64(identity_keypair.pubKey); // The Device ID is a randomly generated integer between 1 and 2^31 - 1.
            _context3.next = 6;
            return generateDeviceID();
          case 6:
            device_id = _context3.sent;
            _this3.save({
              'device_id': device_id,
              'identity_keypair': {
                'privKey': store_u.arrayBufferToBase64(identity_keypair.privKey),
                'pubKey': identity_key
              },
              'identity_key': identity_key
            });
            _context3.next = 10;
            return libsignal.KeyHelper.generateSignedPreKey(identity_keypair, 0);
          case 10:
            signed_prekey = _context3.sent;
            _this3.storeSignedPreKey(signed_prekey);
            _context3.next = 14;
            return _this3.generatePreKeys();
          case 14:
            prekeys = _context3.sent;
            bundle = {
              identity_key: identity_key,
              device_id: device_id,
              prekeys: prekeys
            };
            bundle['signed_prekey'] = {
              'id': signed_prekey.keyId,
              'public_key': store_u.arrayBufferToBase64(signed_prekey.keyPair.pubKey),
              'signature': store_u.arrayBufferToBase64(signed_prekey.signature)
            };
            _context3.next = 19;
            return shared_api.omemo.devicelists.get(shared_converse.bare_jid);
          case 19:
            devicelist = _context3.sent;
            _context3.next = 22;
            return devicelist.devices.create({
              'id': bundle.device_id,
              'jid': shared_converse.bare_jid
            }, {
              'promise': true
            });
          case 22:
            device = _context3.sent;
            device.save('bundle', bundle);
          case 24:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }))();
  },
  fetchSession: function fetchSession() {
    var _this4 = this;
    if (this._setup_promise === undefined) {
      this._setup_promise = new Promise(function (resolve, reject) {
        _this4.fetch({
          'success': function success() {
            if (!_this4.get('device_id')) {
              _this4.generateBundle().then(resolve).catch(reject);
            } else {
              resolve();
            }
          },
          'error': function error(model, resp) {
            log.warn("Could not fetch OMEMO session from cache, we'll generate a new one.");
            log.warn(resp);
            _this4.generateBundle().then(resolve).catch(reject);
          }
        });
      });
    }
    return this._setup_promise;
  }
});
/* harmony default export */ const store = (OMEMOStore);
;// CONCATENATED MODULE: ./src/plugins/omemo/api.js
function omemo_api_typeof(obj) {
  "@babel/helpers - typeof";

  return omemo_api_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;
  }, omemo_api_typeof(obj);
}
function omemo_api_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  omemo_api_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" == omemo_api_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 omemo_api_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 omemo_api_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        omemo_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        omemo_api_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


/* harmony default export */ const omemo_api = ({
  /**
   * The "omemo" namespace groups methods relevant to OMEMO
   * encryption.
   *
   * @namespace _converse.api.omemo
   * @memberOf _converse.api
   */
  'omemo': {
    /**
     * Returns the device ID of the current device.
     */
    getDeviceID: function getDeviceID() {
      return omemo_api_asyncToGenerator( /*#__PURE__*/omemo_api_regeneratorRuntime().mark(function _callee() {
        return omemo_api_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('OMEMOInitialized');
            case 2:
              return _context.abrupt("return", shared_converse.omemo_store.get('device_id'));
            case 3:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    /**
     * The "devicelists" namespace groups methods related to OMEMO device lists
     *
     * @namespace _converse.api.omemo.devicelists
     * @memberOf _converse.api.omemo
     */
    'devicelists': {
      /**
       * Returns the {@link _converse.DeviceList} for a particular JID.
       * The device list will be created if it doesn't exist already.
       * @method _converse.api.omemo.devicelists.get
       * @param { String } jid - The Jabber ID for which the device list will be returned.
       * @param { bool } create=false - Set to `true` if the device list
       *      should be created if it cannot be found.
       */
      get: function get(jid) {
        var _arguments = arguments;
        return omemo_api_asyncToGenerator( /*#__PURE__*/omemo_api_regeneratorRuntime().mark(function _callee2() {
          var create, list;
          return omemo_api_regeneratorRuntime().wrap(function _callee2$(_context2) {
            while (1) switch (_context2.prev = _context2.next) {
              case 0:
                create = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;
                list = shared_converse.devicelists.get(jid) || (create ? shared_converse.devicelists.create({
                  jid: jid
                }) : null);
                _context2.next = 4;
                return list === null || list === void 0 ? void 0 : list.initialized;
              case 4:
                return _context2.abrupt("return", list);
              case 5:
              case "end":
                return _context2.stop();
            }
          }, _callee2);
        }))();
      }
    },
    /**
     * The "bundle" namespace groups methods relevant to the user's
     * OMEMO bundle.
     *
     * @namespace _converse.api.omemo.bundle
     * @memberOf _converse.api.omemo
     */
    'bundle': {
      /**
       * Lets you generate a new OMEMO device bundle
       *
       * @method _converse.api.omemo.bundle.generate
       * @returns {promise} Promise which resolves once we have a result from the server.
       */
      'generate': function () {
        var _generate = omemo_api_asyncToGenerator( /*#__PURE__*/omemo_api_regeneratorRuntime().mark(function _callee3() {
          var devicelist, device_id, _device, device, fp;
          return omemo_api_regeneratorRuntime().wrap(function _callee3$(_context3) {
            while (1) switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return shared_api.waitUntil('OMEMOInitialized');
              case 2:
                _context3.next = 4;
                return shared_api.omemo.devicelists.get(shared_converse.bare_jid);
              case 4:
                devicelist = _context3.sent;
                device_id = shared_converse.omemo_store.get('device_id');
                if (!device_id) {
                  _context3.next = 13;
                  break;
                }
                _device = devicelist.devices.get(device_id);
                shared_converse.omemo_store.unset(device_id);
                if (!_device) {
                  _context3.next = 12;
                  break;
                }
                _context3.next = 12;
                return new Promise(function (done) {
                  return _device.destroy({
                    'success': done,
                    'error': done
                  });
                });
              case 12:
                devicelist.devices.trigger('remove');
              case 13:
                _context3.next = 15;
                return shared_converse.omemo_store.generateBundle();
              case 15:
                _context3.next = 17;
                return devicelist.publishDevices();
              case 17:
                device = devicelist.devices.get(shared_converse.omemo_store.get('device_id'));
                fp = generateFingerprint(device);
                _context3.next = 21;
                return shared_converse.omemo_store.publishBundle();
              case 21:
                return _context3.abrupt("return", fp);
              case 22:
              case "end":
                return _context3.stop();
            }
          }, _callee3);
        }));
        function generate() {
          return _generate.apply(this, arguments);
        }
        return generate;
      }()
    }
  }
});
;// CONCATENATED MODULE: ./src/plugins/omemo/index.js
function omemo_typeof(obj) {
  "@babel/helpers - typeof";

  return omemo_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;
  }, omemo_typeof(obj);
}
function omemo_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  omemo_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" == omemo_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 omemo_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 omemo_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        omemo_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        omemo_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */














var omemo_Strophe = public_converse.env.Strophe;
public_converse.env.omemo = omemo;
omemo_Strophe.addNamespace('OMEMO_DEVICELIST', omemo_Strophe.NS.OMEMO + '.devicelist');
omemo_Strophe.addNamespace('OMEMO_VERIFICATION', omemo_Strophe.NS.OMEMO + '.verification');
omemo_Strophe.addNamespace('OMEMO_WHITELISTED', omemo_Strophe.NS.OMEMO + '.whitelisted');
omemo_Strophe.addNamespace('OMEMO_BUNDLES', omemo_Strophe.NS.OMEMO + '.bundles');
public_converse.plugins.add('converse-omemo', {
  enabled: function enabled(_converse) {
    return window.libsignal && _converse.config.get('trusted') && !shared_api.settings.get('clear_cache_on_logout') && !_converse.api.settings.get('blacklisted_plugins').includes('converse-omemo');
  },
  dependencies: ['converse-chatview', 'converse-pubsub', 'converse-profile'],
  initialize: function initialize() {
    shared_api.settings.extend({
      'omemo_default': false
    });
    shared_api.promises.add(['OMEMOInitialized']);
    shared_converse.NUM_PREKEYS = 100; // Set here so that tests can override

    Object.assign(shared_converse, mixins_converse);
    Object.assign(shared_converse.api, omemo_api);
    shared_converse.OMEMOStore = store;
    shared_converse.Device = device;
    shared_converse.Devices = devices;
    shared_converse.DeviceList = devicelist;
    shared_converse.DeviceLists = devicelists;

    /******************** Event Handlers ********************/
    shared_api.waitUntil('chatBoxesInitialized').then(utils_onChatBoxesInitialized);
    shared_api.listen.on('getOutgoingMessageAttributes', getOutgoingMessageAttributes);
    shared_api.listen.on('createMessageStanza', /*#__PURE__*/function () {
      var _ref = omemo_asyncToGenerator( /*#__PURE__*/omemo_regeneratorRuntime().mark(function _callee(chat, data) {
        return omemo_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return createOMEMOMessageStanza(chat, data);
            case 3:
              data = _context.sent;
              _context.next = 9;
              break;
            case 6:
              _context.prev = 6;
              _context.t0 = _context["catch"](0);
              handleMessageSendError(_context.t0, chat);
            case 9:
              return _context.abrupt("return", data);
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[0, 6]]);
      }));
      return function (_x, _x2) {
        return _ref.apply(this, arguments);
      };
    }());
    shared_api.listen.on('afterFileUploaded', function (msg, attrs) {
      return msg.file.xep454_ivkey ? setEncryptedFileURL(msg, attrs) : attrs;
    });
    shared_api.listen.on('beforeFileUpload', function (chat, file) {
      return chat.get('omemo_active') ? encryptFile(file) : file;
    });
    shared_api.listen.on('parseMessage', parseEncryptedMessage);
    shared_api.listen.on('parseMUCMessage', parseEncryptedMessage);
    shared_api.listen.on('chatBoxViewInitialized', onChatInitialized);
    shared_api.listen.on('chatRoomViewInitialized', onChatInitialized);
    shared_api.listen.on('connected', registerPEPPushHandler);
    shared_api.listen.on('getToolbarButtons', getOMEMOToolbarButton);
    shared_api.listen.on('statusInitialized', initOMEMO);
    shared_api.listen.on('addClientFeatures', function () {
      return shared_api.disco.own.features.add("".concat(omemo_Strophe.NS.OMEMO_DEVICELIST, "+notify"));
    });
    shared_api.listen.on('afterMessageBodyTransformed', handleEncryptedFiles);
    shared_api.listen.on('userDetailsModalInitialized', function (contact) {
      var jid = contact.get('jid');
      shared_converse.generateFingerprints(jid).catch(function (e) {
        return log.error(e);
      });
    });
    shared_api.listen.on('profileModalInitialized', function () {
      shared_converse.generateFingerprints(shared_converse.bare_jid).catch(function (e) {
        return log.error(e);
      });
    });
    shared_api.listen.on('clearSession', function () {
      delete shared_converse.omemo_store;
      if (shouldClearCache() && shared_converse.devicelists) {
        shared_converse.devicelists.clearStore();
        delete shared_converse.devicelists;
      }
    });
  }
});
;// CONCATENATED MODULE: ./src/plugins/push/utils.js
function push_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return push_utils_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;
  }, push_utils_typeof(obj);
}
function push_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  push_utils_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" == push_utils_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 push_utils_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 push_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        push_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        push_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var push_utils_converse$env = public_converse.env,
  push_utils_Strophe = push_utils_converse$env.Strophe,
  push_utils_$iq = push_utils_converse$env.$iq;
function disablePushAppServer(_x, _x2) {
  return _disablePushAppServer.apply(this, arguments);
}
function _disablePushAppServer() {
  _disablePushAppServer = push_utils_asyncToGenerator( /*#__PURE__*/push_utils_regeneratorRuntime().mark(function _callee(domain, push_app_server) {
    var stanza;
    return push_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (push_app_server.jid) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return");
        case 2:
          _context.next = 4;
          return shared_api.disco.supports(push_utils_Strophe.NS.PUSH, domain || shared_converse.bare_jid);
        case 4:
          if (_context.sent) {
            _context.next = 7;
            break;
          }
          log.warn("Not disabling push app server \"".concat(push_app_server.jid, "\", no disco support from your server."));
          return _context.abrupt("return");
        case 7:
          stanza = push_utils_$iq({
            'type': 'set'
          });
          if (domain !== shared_converse.bare_jid) {
            stanza.attrs({
              'to': domain
            });
          }
          stanza.c('disable', {
            'xmlns': push_utils_Strophe.NS.PUSH,
            'jid': push_app_server.jid
          });
          if (push_app_server.node) {
            stanza.attrs({
              'node': push_app_server.node
            });
          }
          shared_api.sendIQ(stanza).catch(function (e) {
            log.error("Could not disable push app server for ".concat(push_app_server.jid));
            log.error(e);
          });
        case 12:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _disablePushAppServer.apply(this, arguments);
}
function enablePushAppServer(_x3, _x4) {
  return _enablePushAppServer.apply(this, arguments);
}
function _enablePushAppServer() {
  _enablePushAppServer = push_utils_asyncToGenerator( /*#__PURE__*/push_utils_regeneratorRuntime().mark(function _callee2(domain, push_app_server) {
    var identity, result, stanza;
    return push_utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(!push_app_server.jid || !push_app_server.node)) {
            _context2.next = 2;
            break;
          }
          return _context2.abrupt("return");
        case 2:
          _context2.next = 4;
          return shared_api.disco.getIdentity('pubsub', 'push', push_app_server.jid);
        case 4:
          identity = _context2.sent;
          if (identity) {
            _context2.next = 7;
            break;
          }
          return _context2.abrupt("return", log.warn("Not enabling push the service \"".concat(push_app_server.jid, "\", it doesn't have the right disco identtiy.")));
        case 7:
          _context2.next = 9;
          return Promise.all([shared_api.disco.supports(push_utils_Strophe.NS.PUSH, push_app_server.jid), shared_api.disco.supports(push_utils_Strophe.NS.PUSH, domain)]);
        case 9:
          result = _context2.sent;
          if (!(!result[0] && !result[1])) {
            _context2.next = 13;
            break;
          }
          log.warn("Not enabling push app server \"".concat(push_app_server.jid, "\", no disco support from your server."));
          return _context2.abrupt("return");
        case 13:
          stanza = push_utils_$iq({
            'type': 'set'
          });
          if (domain !== shared_converse.bare_jid) {
            stanza.attrs({
              'to': domain
            });
          }
          stanza.c('enable', {
            'xmlns': push_utils_Strophe.NS.PUSH,
            'jid': push_app_server.jid,
            'node': push_app_server.node
          });
          if (push_app_server.secret) {
            stanza.c('x', {
              'xmlns': push_utils_Strophe.NS.XFORM,
              'type': 'submit'
            }).c('field', {
              'var': 'FORM_TYPE'
            }).c('value').t("".concat(push_utils_Strophe.NS.PUBSUB, "#publish-options")).up().up().c('field', {
              'var': 'secret'
            }).c('value').t(push_app_server.secret);
          }
          return _context2.abrupt("return", shared_api.sendIQ(stanza));
        case 18:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _enablePushAppServer.apply(this, arguments);
}
function enablePush(_x5) {
  return _enablePush.apply(this, arguments);
}
function _enablePush() {
  _enablePush = push_utils_asyncToGenerator( /*#__PURE__*/push_utils_regeneratorRuntime().mark(function _callee3(domain) {
    var push_enabled, enabled_services, disabled_services, enabled, disabled;
    return push_utils_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          domain = domain || shared_converse.bare_jid;
          push_enabled = shared_converse.session.get('push_enabled') || [];
          if (!push_enabled.includes(domain)) {
            _context3.next = 4;
            break;
          }
          return _context3.abrupt("return");
        case 4:
          enabled_services = shared_api.settings.get('push_app_servers').filter(function (s) {
            return !s.disable;
          });
          disabled_services = shared_api.settings.get('push_app_servers').filter(function (s) {
            return s.disable;
          });
          enabled = enabled_services.map(function (s) {
            return enablePushAppServer(domain, s);
          });
          disabled = disabled_services.map(function (s) {
            return disablePushAppServer(domain, s);
          });
          _context3.prev = 8;
          _context3.next = 11;
          return Promise.all(enabled.concat(disabled));
        case 11:
          _context3.next = 17;
          break;
        case 13:
          _context3.prev = 13;
          _context3.t0 = _context3["catch"](8);
          log.error('Could not enable or disable push App Server');
          if (_context3.t0) log.error(_context3.t0);
        case 17:
          _context3.prev = 17;
          push_enabled.push(domain);
          return _context3.finish(17);
        case 20:
          shared_converse.session.save('push_enabled', push_enabled);
        case 21:
        case "end":
          return _context3.stop();
      }
    }, _callee3, null, [[8, 13, 17, 20]]);
  }));
  return _enablePush.apply(this, arguments);
}
function onChatBoxAdded(model) {
  if (model.get('type') == shared_converse.CHATROOMS_TYPE) {
    enablePush(push_utils_Strophe.getDomainFromJid(model.get('jid')));
  }
}
;// CONCATENATED MODULE: ./src/plugins/push/index.js
/**
 * @description
 * Converse.js plugin which add support for registering
 * an "App Server" as defined in  XEP-0357
 * @copyright 2021, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


var push_Strophe = public_converse.env.Strophe;
push_Strophe.addNamespace('PUSH', 'urn:xmpp:push:0');
public_converse.plugins.add('converse-push', {
  initialize: function initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    shared_api.settings.extend({
      'push_app_servers': [],
      'enable_muc_push': false
    });
    shared_api.listen.on('statusInitialized', function () {
      return enablePush();
    });
    if (shared_api.settings.get('enable_muc_push')) {
      shared_api.listen.on('chatBoxesInitialized', function () {
        return shared_converse.chatboxes.on('add', onChatBoxAdded);
      });
    }
  }
});
;// CONCATENATED MODULE: ./src/plugins/register/templates/switch_form.js
var switch_form_templateObject;
function switch_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const switch_form = (function () {
  var i18n_has_account = __('Already have a chat account?');
  var i18n_login = __('Log in here');
  return (0,external_lit_namespaceObject.html)(switch_form_templateObject || (switch_form_templateObject = switch_form_taggedTemplateLiteral(["\n        <div class=\"switch-form\">\n            <p>", "</p>\n            <p><a class=\"login-here toggle-register-login\" href=\"#converse/login\">", "</a></p>\n        </div>"])), i18n_has_account, i18n_login);
});
;// CONCATENATED MODULE: ./src/plugins/register/templates/registration_form.js
var registration_form_templateObject, registration_form_templateObject2, registration_form_templateObject3;
function registration_form_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const registration_form = (function (el) {
  var i18n_choose_provider = __('Choose a different provider');
  var i18n_legend = __('Account Registration:');
  var i18n_register = __('Register');
  var registration_domain = shared_api.settings.get('registration_domain');
  return (0,external_lit_namespaceObject.html)(registration_form_templateObject || (registration_form_templateObject = registration_form_taggedTemplateLiteral(["\n        <form id=\"converse-register\" class=\"converse-form\" @submit=", ">\n            <legend class=\"col-form-label\">", " ", "</legend>\n            <p class=\"title\">", "</p>\n            <p class=\"form-help instructions\">", "</p>\n            <div class=\"form-errors hidden\"></div>\n            ", "\n\n            <fieldset class=\"buttons form-group\">\n                ", "\n                ", "\n                ", "\n            </fieldset>\n        </form>\n    "])), function (ev) {
    return el.onFormSubmission(ev);
  }, i18n_legend, el.domain, el.title, el.instructions, el.form_fields, el.fields ? (0,external_lit_namespaceObject.html)(registration_form_templateObject2 || (registration_form_templateObject2 = registration_form_taggedTemplateLiteral(["\n                          <input type=\"submit\" class=\"btn btn-primary\" value=\"", "\" />\n                      "])), i18n_register) : '', registration_domain ? '' : (0,external_lit_namespaceObject.html)(registration_form_templateObject3 || (registration_form_templateObject3 = registration_form_taggedTemplateLiteral(["\n                          <input\n                              type=\"button\"\n                              class=\"btn btn-secondary button-cancel\"\n                              value=\"", "\"\n                              @click=", "\n                          />\n                      "])), i18n_choose_provider, function (ev) {
    return el.renderProviderChoiceForm(ev);
  }), switch_form());
});
;// CONCATENATED MODULE: ./src/plugins/register/templates/register_panel.js
var register_panel_templateObject, register_panel_templateObject2, register_panel_templateObject3, register_panel_templateObject4, register_panel_templateObject5, register_panel_templateObject6, register_panel_templateObject7;
function register_panel_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}






var tplFormRequest = function tplFormRequest(el) {
  var default_domain = shared_api.settings.get('registration_domain');
  var i18n_cancel = __('Cancel');
  return (0,external_lit_namespaceObject.html)(register_panel_templateObject || (register_panel_templateObject = register_panel_taggedTemplateLiteral(["\n        <form id=\"converse-register\" class=\"converse-form no-scrolling\" @submit=", ">\n            ", "\n            ", "\n        </form>\n    "])), function (ev) {
    return el.onFormSubmission(ev);
  }, spinner({
    'classes': 'hor_centered'
  }), default_domain ? '' : (0,external_lit_namespaceObject.html)(register_panel_templateObject2 || (register_panel_templateObject2 = register_panel_taggedTemplateLiteral(["\n                    <button class=\"btn btn-secondary button-cancel hor_centered\"\n                            @click=", ">", "</button>\n                  "])), function (ev) {
    return el.renderProviderChoiceForm(ev);
  }, i18n_cancel));
};
var tplDomainInput = function tplDomainInput() {
  var domain_placeholder = shared_api.settings.get('domain_placeholder');
  var i18n_providers = __('Tip: A list of public XMPP providers is available');
  var i18n_providers_link = __('here');
  var href_providers = shared_api.settings.get('providers_link');
  return (0,external_lit_namespaceObject.html)(register_panel_templateObject3 || (register_panel_templateObject3 = register_panel_taggedTemplateLiteral(["\n        <input class=\"form-control\" required=\"required\" type=\"text\" name=\"domain\" placeholder=\"", "\" />\n        <p class=\"form-text text-muted\">\n            ", "\n            <a href=\"", "\" class=\"url\" target=\"_blank\" rel=\"noopener\">", "</a>.\n        </p>\n    "])), domain_placeholder, i18n_providers, href_providers, i18n_providers_link);
};
var tplFetchFormButtons = function tplFetchFormButtons() {
  var i18n_register = __('Fetch registration form');
  var i18n_existing_account = __('Already have a chat account?');
  var i18n_login = __('Log in here');
  return (0,external_lit_namespaceObject.html)(register_panel_templateObject4 || (register_panel_templateObject4 = register_panel_taggedTemplateLiteral(["\n        <fieldset class=\"form-group buttons\">\n            <input class=\"btn btn-primary\" type=\"submit\" value=\"", "\" />\n        </fieldset>\n        <div class=\"switch-form\">\n            <p>", "</p>\n            <p><a class=\"login-here toggle-register-login\" href=\"#converse/login\">", "</a></p>\n        </div>\n    "])), i18n_register, i18n_existing_account, i18n_login);
};
var tplChooseProvider = function tplChooseProvider(el) {
  var default_domain = shared_api.settings.get('registration_domain');
  var i18n_create_account = __('Create your account');
  var i18n_choose_provider = __('Please enter the XMPP provider to register with:');
  var show_form_buttons = !default_domain && el.status === CHOOSE_PROVIDER;
  return (0,external_lit_namespaceObject.html)(register_panel_templateObject5 || (register_panel_templateObject5 = register_panel_taggedTemplateLiteral(["\n        <form id=\"converse-register\" class=\"converse-form\" @submit=", ">\n            <legend class=\"col-form-label\">", "</legend>\n            <div class=\"form-group\">\n                <label>", "</label>\n\n                ", "\n            </div>\n            ", "\n        </form>\n    "])), function (ev) {
    return el.onFormSubmission(ev);
  }, i18n_create_account, i18n_choose_provider, default_domain ? default_domain : tplDomainInput(), show_form_buttons ? tplFetchFormButtons() : '');
};
var CHOOSE_PROVIDER = 0;
var FETCHING_FORM = 1;
var REGISTRATION_FORM = 2;
var REGISTRATION_FORM_ERROR = 3;
/* harmony default export */ const register_panel = (function (el) {
  return (0,external_lit_namespaceObject.html)(register_panel_templateObject6 || (register_panel_templateObject6 = register_panel_taggedTemplateLiteral(["\n        <converse-brand-logo></converse-brand-logo>\n        ", "\n        ", "\n        ", "\n        ", "\n        ", "\n    "])), el.alert_message ? (0,external_lit_namespaceObject.html)(register_panel_templateObject7 || (register_panel_templateObject7 = register_panel_taggedTemplateLiteral(["<div class=\"alert alert-", "\" role=\"alert\">", "</div>"])), el.alert_type, el.alert_message) : '', el.status === CHOOSE_PROVIDER ? tplChooseProvider(el) : '', el.status === FETCHING_FORM ? tplFormRequest(el) : '', el.status === REGISTRATION_FORM ? registration_form(el) : '', el.status === REGISTRATION_FORM_ERROR ? switch_form() : '');
});
;// CONCATENATED MODULE: ./src/plugins/register/utils.js
function register_utils_typeof(obj) {
  "@babel/helpers - typeof";

  return register_utils_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;
  }, register_utils_typeof(obj);
}
function register_utils_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  register_utils_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" == register_utils_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 register_utils_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 register_utils_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        register_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        register_utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

function setActiveForm(_x) {
  return _setActiveForm.apply(this, arguments);
}
function _setActiveForm() {
  _setActiveForm = register_utils_asyncToGenerator( /*#__PURE__*/register_utils_regeneratorRuntime().mark(function _callee(value) {
    var controlbox;
    return register_utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return shared_api.waitUntil('controlBoxInitialized');
        case 2:
          controlbox = shared_converse.chatboxes.get('controlbox');
          controlbox.set({
            'active-form': value
          });
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _setActiveForm.apply(this, arguments);
}
;// CONCATENATED MODULE: ./src/headless/utils/form.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the form utilities module.
 */

var tplXformField = function tplXformField(name, value) {
  return "<field var=\"".concat(name, "\">").concat(value, "</field>");
};
var tplXformValue = function tplXformValue(value) {
  return "<value>".concat(value, "</value>");
};

/**
 * Takes an HTML DOM and turns it into an XForm field.
 * @private
 * @method u#webForm2xForm
 * @param { Element } field - the field to convert
 */
function webForm2xForm(field) {
  var name = field.getAttribute('name');
  if (!name) {
    return null; // See #1924
  }

  var value;
  if (field.getAttribute('type') === 'checkbox') {
    value = field.checked && 1 || 0;
  } else if (field.tagName == "TEXTAREA") {
    value = field.value.split('\n').filter(function (s) {
      return s.trim();
    });
  } else if (field.tagName == "SELECT") {
    value = core.getSelectValues(field);
  } else {
    value = field.value;
  }
  return core.toStanza(tplXformField(name, Array.isArray(value) ? value.map(tplXformValue) : tplXformValue(value)));
}
core.webForm2xForm = webForm2xForm;
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/register/styles/register.scss
var register = __webpack_require__(6943);
;// CONCATENATED MODULE: ./src/plugins/register/styles/register.scss

      
      
      
      
      
      
      
      
      

var register_options = {};

register_options.styleTagTransform = (styleTagTransform_default());
register_options.setAttributes = (setAttributesWithoutAttributes_default());

      register_options.insert = insertBySelector_default().bind(null, "head");
    
register_options.domAPI = (styleDomAPI_default());
register_options.insertStyleElement = (insertStyleElement_default());

var register_update = injectStylesIntoStyleTag_default()(register/* default */.Z, register_options);




       /* harmony default export */ const styles_register = (register/* default */.Z && register/* default */.Z.locals ? register/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/register/panel.js
function panel_typeof(obj) {
  "@babel/helpers - typeof";

  return panel_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;
  }, panel_typeof(obj);
}
function panel_toConsumableArray(arr) {
  return panel_arrayWithoutHoles(arr) || panel_iterableToArray(arr) || panel_unsupportedIterableToArray(arr) || panel_nonIterableSpread();
}
function panel_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function panel_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return panel_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 panel_arrayLikeToArray(o, minLen);
}
function panel_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function panel_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return panel_arrayLikeToArray(arr);
}
function panel_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 panel_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function panel_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, panel_toPropertyKey(descriptor.key), descriptor);
  }
}
function panel_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) panel_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) panel_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function panel_toPropertyKey(arg) {
  var key = panel_toPrimitive(arg, "string");
  return panel_typeof(key) === "symbol" ? key : String(key);
}
function panel_toPrimitive(input, hint) {
  if (panel_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (panel_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function panel_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) panel_setPrototypeOf(subClass, superClass);
}
function panel_setPrototypeOf(o, p) {
  panel_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return panel_setPrototypeOf(o, p);
}
function panel_createSuper(Derived) {
  var hasNativeReflectConstruct = panel_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = panel_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = panel_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return panel_possibleConstructorReturn(this, result);
  };
}
function panel_possibleConstructorReturn(self, call) {
  if (call && (panel_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 panel_assertThisInitialized(self);
}
function panel_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function panel_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 panel_getPrototypeOf(o) {
  panel_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return panel_getPrototypeOf(o);
}














// Strophe methods for building stanzas
var panel_converse$env = public_converse.env,
  panel_Strophe = panel_converse$env.Strophe,
  panel_sizzle = panel_converse$env.sizzle,
  panel_$iq = panel_converse$env.$iq;
var panel_u = public_converse.env.utils;
var panel_CHOOSE_PROVIDER = 0;
var panel_FETCHING_FORM = 1;
var panel_REGISTRATION_FORM = 2;
var panel_REGISTRATION_FORM_ERROR = 3;

/**
 * @class
 * @namespace _converse.RegisterPanel
 * @memberOf _converse
 */
var RegisterPanel = /*#__PURE__*/function (_CustomElement) {
  panel_inherits(RegisterPanel, _CustomElement);
  var _super = panel_createSuper(RegisterPanel);
  function RegisterPanel() {
    var _this;
    panel_classCallCheck(this, RegisterPanel);
    _this = _super.call(this);
    _this.alert_type = 'info';
    _this.setErrorMessage = function (m) {
      return _this.setMessage(m, 'danger');
    };
    _this.setFeedbackMessage = function (m) {
      return _this.setMessage(m, 'info');
    };
    return _this;
  }
  panel_createClass(RegisterPanel, [{
    key: "initialize",
    value: function initialize() {
      var _this2 = this;
      this.reset();
      this.listenTo(shared_converse, 'connectionInitialized', function () {
        return _this2.registerHooks();
      });
      var domain = shared_api.settings.get('registration_domain');
      if (domain) {
        this.fetchRegistrationForm(domain);
      } else {
        this.status = panel_CHOOSE_PROVIDER;
      }
    }
  }, {
    key: "render",
    value: function render() {
      return register_panel(this);
    }
  }, {
    key: "setMessage",
    value: function setMessage(message, type) {
      this.alert_type = type;
      this.alert_message = message;
    }

    /**
     * Hook into Strophe's _connect_cb, so that we can send an IQ
     * requesting the registration fields.
     */
  }, {
    key: "registerHooks",
    value: function registerHooks() {
      var _this3 = this;
      var conn = shared_converse.connection;
      var connect_cb = conn._connect_cb.bind(conn);
      conn._connect_cb = function (req, callback, raw) {
        if (!_this3._registering) {
          connect_cb(req, callback, raw);
        } else if (_this3.getRegistrationFields(req, callback)) {
          _this3._registering = false;
        }
      };
    }

    /**
     * Send an IQ stanza to the XMPP server asking for the registration fields.
     * @method _converse.RegisterPanel#getRegistrationFields
     * @param { Strophe.Request } req - The current request
     * @param { Function } callback - The callback function
     */
  }, {
    key: "getRegistrationFields",
    value: function getRegistrationFields(req, _callback) {
      var _this4 = this;
      var conn = shared_converse.connection;
      conn.connected = true;
      var body = conn._proto._reqToData(req);
      if (!body) {
        return;
      }
      if (conn._proto._connect_cb(body) === panel_Strophe.Status.CONNFAIL) {
        this.status = panel_CHOOSE_PROVIDER;
        this.setErrorMessage(__("Sorry, we're unable to connect to your chosen provider."));
        return false;
      }
      var register = body.getElementsByTagName("register");
      var mechanisms = body.getElementsByTagName("mechanism");
      if (register.length === 0 && mechanisms.length === 0) {
        conn._proto._no_auth_received(_callback);
        return false;
      }
      if (register.length === 0) {
        conn._changeConnectStatus(panel_Strophe.Status.REGIFAIL);
        this.alert_type = 'danger';
        this.setErrorMessage(__("Sorry, the given provider does not support in " + "band account registration. Please try with a " + "different provider."));
        return true;
      }
      // Send an IQ stanza to get all required data fields
      conn._addSysHandler(function (s) {
        return _this4.onRegistrationFields(s);
      }, null, "iq", null, null);
      var stanza = panel_$iq({
        type: "get"
      }).c("query", {
        xmlns: panel_Strophe.NS.REGISTER
      }).tree();
      stanza.setAttribute("id", conn.getUniqueId("sendIQ"));
      conn.send(stanza);
      conn.connected = false;
      return true;
    }

    /**
     * Handler for {@link _converse.RegisterPanel#getRegistrationFields}
     * @method _converse.RegisterPanel#onRegistrationFields
     * @param { Element } stanza - The query stanza.
     */
  }, {
    key: "onRegistrationFields",
    value: function onRegistrationFields(stanza) {
      if (stanza.getAttribute("type") === "error") {
        this.reportErrors(stanza);
        if (shared_api.settings.get('registration_domain')) {
          this.status = panel_REGISTRATION_FORM_ERROR;
        } else {
          this.status = panel_CHOOSE_PROVIDER;
        }
        return false;
      }
      this.setFields(stanza);
      if (this.status === panel_FETCHING_FORM) {
        this.renderRegistrationForm(stanza);
      }
      return false;
    }
  }, {
    key: "reset",
    value: function reset(settings) {
      var defaults = {
        fields: {},
        urls: [],
        title: "",
        instructions: "",
        registered: false,
        _registering: false,
        domain: null,
        form_type: null
      };
      Object.assign(this, defaults);
      if (settings) Object.assign(this, settings);
    }

    /**
     * Event handler when the #converse-register form is submitted.
     * Depending on the available input fields, we delegate to other methods.
     * @param { Event } ev
     */
  }, {
    key: "onFormSubmission",
    value: function onFormSubmission(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      if (ev.target.querySelector('input[name=domain]') === null) {
        this.submitRegistrationForm(ev.target);
      } else {
        this.onProviderChosen(ev.target);
      }
    }

    /**
     * Callback method that gets called when the user has chosen an XMPP provider
     * @method _converse.RegisterPanel#onProviderChosen
     * @param { HTMLElement } form - The form that was submitted
     */
  }, {
    key: "onProviderChosen",
    value: function onProviderChosen(form) {
      var _form$querySelector;
      var domain = (_form$querySelector = form.querySelector('input[name=domain]')) === null || _form$querySelector === void 0 ? void 0 : _form$querySelector.value;
      if (domain) this.fetchRegistrationForm(domain.trim());
    }

    /**
     * Fetch a registration form from the requested domain
     * @method _converse.RegisterPanel#fetchRegistrationForm
     * @param { String } domain_name - XMPP server domain
     */
  }, {
    key: "fetchRegistrationForm",
    value: function fetchRegistrationForm(domain_name) {
      var _converse$connection,
        _this5 = this;
      this.status = panel_FETCHING_FORM;
      this.reset({
        'domain': panel_Strophe.getDomainFromJid(domain_name),
        '_registering': true
      });
      initConnection(this.domain);
      // When testing, the test tears down before the async function
      // above finishes. So we use optional chaining here
      (_converse$connection = shared_converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.connect(this.domain, "", function (s) {
        return _this5.onConnectStatusChanged(s);
      });
      return false;
    }

    /**
     * Callback function called by Strophe whenever the connection status changes.
     * Passed to Strophe specifically during a registration attempt.
     * @method _converse.RegisterPanel#onConnectStatusChanged
     * @param { number } status_code - The Strophe.Status status code
     */
  }, {
    key: "onConnectStatusChanged",
    value: function onConnectStatusChanged(status_code) {
      log.debug('converse-register: onConnectStatusChanged');
      if ([panel_Strophe.Status.DISCONNECTED, panel_Strophe.Status.CONNFAIL, panel_Strophe.Status.REGIFAIL, panel_Strophe.Status.NOTACCEPTABLE, panel_Strophe.Status.CONFLICT].includes(status_code)) {
        log.error("Problem during registration: Strophe.Status is ".concat(CONNECTION_STATUS[status_code]));
        this.abortRegistration();
      } else if (status_code === panel_Strophe.Status.REGISTERED) {
        log.debug("Registered successfully.");
        shared_converse.connection.reset();
        if (["converse/login", "converse/register"].includes(shared_converse.router.history.getFragment())) {
          shared_converse.router.navigate('', {
            'replace': true
          });
        }
        setActiveForm('login');
        if (this.fields.password && this.fields.username) {
          // automatically log the user in
          shared_converse.connection.connect(this.fields.username.toLowerCase() + '@' + this.domain.toLowerCase(), this.fields.password, shared_converse.onConnectStatusChanged);
          this.setFeedbackMessage(__('Now logging you in'));
        } else {
          this.setFeedbackMessage(__('Registered successfully'));
        }
        this.reset();
      }
    }
  }, {
    key: "getLegacyFormFields",
    value: function getLegacyFormFields() {
      var _this6 = this;
      var input_fields = Object.keys(this.fields).map(function (key) {
        if (key === "username") {
          return form_username({
            'domain': " @".concat(_this6.domain),
            'name': key,
            'type': "text",
            'label': key,
            'value': '',
            'required': true
          });
        } else {
          return form_input({
            'label': key,
            'name': key,
            'placeholder': key,
            'required': true,
            'type': key === 'password' || key === 'email' ? key : "text",
            'value': ''
          });
        }
      });
      var urls = this.urls.map(function (u) {
        return form_url({
          'label': '',
          'value': u
        });
      });
      return [].concat(panel_toConsumableArray(input_fields), panel_toConsumableArray(urls));
    }
  }, {
    key: "getFormFields",
    value: function getFormFields(stanza) {
      var _this7 = this;
      if (this.form_type === 'xform') {
        return Array.from(stanza.querySelectorAll('field')).map(function (field) {
          return panel_u.xForm2TemplateResult(field, stanza, {
            'domain': _this7.domain
          });
        });
      } else {
        return this.getLegacyFormFields();
      }
    }

    /**
     * Renders the registration form based on the XForm fields
     * received from the XMPP server.
     * @method _converse.RegisterPanel#renderRegistrationForm
     * @param { Element } stanza - The IQ stanza received from the XMPP server.
     */
  }, {
    key: "renderRegistrationForm",
    value: function renderRegistrationForm(stanza) {
      this.form_fields = this.getFormFields(stanza);
      this.status = panel_REGISTRATION_FORM;
    }

    /**
     * Report back to the user any error messages received from the
     * XMPP server after attempted registration.
     * @method _converse.RegisterPanel#reportErrors
     * @param { Element } stanza - The IQ stanza received from the XMPP server
     */
  }, {
    key: "reportErrors",
    value: function reportErrors(stanza) {
      var errors = Array.from(stanza.querySelectorAll('error'));
      if (errors.length) {
        this.setErrorMessage(errors.reduce(function (result, e) {
          return "".concat(result, "\n").concat(e.textContent);
        }, ''));
      } else {
        this.setErrorMessage(__('The provider rejected your registration attempt. ' + 'Please check the values you entered for correctness.'));
      }
    }
  }, {
    key: "renderProviderChoiceForm",
    value: function renderProviderChoiceForm(ev) {
      var _ev$preventDefault2;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
      shared_converse.connection._proto._abortAllRequests();
      shared_converse.connection.reset();
      this.status = panel_CHOOSE_PROVIDER;
    }
  }, {
    key: "abortRegistration",
    value: function abortRegistration() {
      shared_converse.connection._proto._abortAllRequests();
      shared_converse.connection.reset();
      if ([panel_FETCHING_FORM, panel_REGISTRATION_FORM].includes(this.status)) {
        if (shared_api.settings.get('registration_domain')) {
          this.fetchRegistrationForm(shared_api.settings.get('registration_domain'));
        }
      } else {
        this.requestUpdate();
      }
    }

    /**
     * Handler, when the user submits the registration form.
     * Provides form error feedback or starts the registration process.
     * @method _converse.RegisterPanel#submitRegistrationForm
     * @param { HTMLElement } form - The HTML form that was submitted
     */
  }, {
    key: "submitRegistrationForm",
    value: function submitRegistrationForm(form) {
      var _this8 = this;
      var inputs = panel_sizzle(':input:not([type=button]):not([type=submit])', form);
      var iq = panel_$iq({
        'type': 'set',
        'id': panel_u.getUniqueId()
      }).c("query", {
        xmlns: panel_Strophe.NS.REGISTER
      });
      if (this.form_type === 'xform') {
        iq.c("x", {
          xmlns: panel_Strophe.NS.XFORM,
          type: 'submit'
        });
        var xml_nodes = inputs.map(function (i) {
          return webForm2xForm(i);
        }).filter(function (n) {
          return n;
        });
        xml_nodes.forEach(function (n) {
          return iq.cnode(n).up();
        });
      } else {
        inputs.forEach(function (input) {
          return iq.c(input.getAttribute('name'), {}, input.value);
        });
      }
      shared_converse.connection._addSysHandler(function (iq) {
        return _this8._onRegisterIQ(iq);
      }, null, "iq", null, null);
      shared_converse.connection.send(iq);
      this.setFields(iq.tree());
    }

    /**
     * Stores the values that will be sent to the XMPP server during attempted registration.
     * @method _converse.RegisterPanel#setFields
     * @param { Element } stanza - the IQ stanza that will be sent to the XMPP server.
     */
  }, {
    key: "setFields",
    value: function setFields(stanza) {
      var query = stanza.querySelector('query');
      var xform = panel_sizzle("x[xmlns=\"".concat(panel_Strophe.NS.XFORM, "\"]"), query);
      if (xform.length > 0) {
        this._setFieldsFromXForm(xform.pop());
      } else {
        this._setFieldsFromLegacy(query);
      }
    }
  }, {
    key: "_setFieldsFromLegacy",
    value: function _setFieldsFromLegacy(query) {
      var _this9 = this;
      [].forEach.call(query.children, function (field) {
        if (field.tagName.toLowerCase() === 'instructions') {
          _this9.instructions = panel_Strophe.getText(field);
          return;
        } else if (field.tagName.toLowerCase() === 'x') {
          if (field.getAttribute('xmlns') === 'jabber:x:oob') {
            _this9.urls.concat(panel_sizzle('url', field).map(function (u) {
              return u.textContent;
            }));
          }
          return;
        }
        _this9.fields[field.tagName.toLowerCase()] = panel_Strophe.getText(field);
      });
      this.form_type = 'legacy';
    }
  }, {
    key: "_setFieldsFromXForm",
    value: function _setFieldsFromXForm(xform) {
      var _xform$querySelector$,
        _xform$querySelector,
        _xform$querySelector$2,
        _xform$querySelector2,
        _this10 = this;
      this.title = (_xform$querySelector$ = (_xform$querySelector = xform.querySelector('title')) === null || _xform$querySelector === void 0 ? void 0 : _xform$querySelector.textContent) !== null && _xform$querySelector$ !== void 0 ? _xform$querySelector$ : '';
      this.instructions = (_xform$querySelector$2 = (_xform$querySelector2 = xform.querySelector('instructions')) === null || _xform$querySelector2 === void 0 ? void 0 : _xform$querySelector2.textContent) !== null && _xform$querySelector$2 !== void 0 ? _xform$querySelector$2 : '';
      xform.querySelectorAll('field').forEach(function (field) {
        var _var = field.getAttribute('var');
        if (_var) {
          var _field$querySelector$, _field$querySelector;
          _this10.fields[_var.toLowerCase()] = (_field$querySelector$ = (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent) !== null && _field$querySelector$ !== void 0 ? _field$querySelector$ : '';
        } else {
          // TODO: other option seems to be type="fixed"
          log.warn("Found field we couldn't parse");
        }
      });
      this.form_type = 'xform';
    }

    /**
     * Callback method that gets called when a return IQ stanza
     * is received from the XMPP server, after attempting to
     * register a new user.
     * @method _converse.RegisterPanel#reportErrors
     * @param { Element } stanza - The IQ stanza.
     */
  }, {
    key: "_onRegisterIQ",
    value: function _onRegisterIQ(stanza) {
      if (stanza.getAttribute("type") === "error") {
        log.error("Registration failed.");
        this.reportErrors(stanza);
        var error = stanza.getElementsByTagName("error");
        if (error.length !== 1) {
          shared_converse.connection._changeConnectStatus(panel_Strophe.Status.REGIFAIL, "unknown");
          return false;
        }
        error = error[0].firstElementChild.tagName.toLowerCase();
        if (error === 'conflict') {
          shared_converse.connection._changeConnectStatus(panel_Strophe.Status.CONFLICT, error);
        } else if (error === 'not-acceptable') {
          shared_converse.connection._changeConnectStatus(panel_Strophe.Status.NOTACCEPTABLE, error);
        } else {
          shared_converse.connection._changeConnectStatus(panel_Strophe.Status.REGIFAIL, error);
        }
      } else {
        shared_converse.connection._changeConnectStatus(panel_Strophe.Status.REGISTERED, null);
      }
      return false;
    }
  }], [{
    key: "properties",
    get: function get() {
      return {
        status: {
          type: String
        },
        alert_message: {
          type: String
        },
        alert_type: {
          type: String
        }
      };
    }
  }]);
  return RegisterPanel;
}(CustomElement);
shared_api.elements.define('converse-register-panel', RegisterPanel);
;// CONCATENATED MODULE: ./src/plugins/register/index.js
/**
 * @module converse-register
 * @description
 * This is a Converse.js plugin which add support for in-band registration
 * as specified in XEP-0077.
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






// Strophe methods for building stanzas
var register_Strophe = public_converse.env.Strophe;

// Add Strophe Namespaces
register_Strophe.addNamespace('REGISTER', 'jabber:iq:register');

// Add Strophe Statuses
var register_i = Object.keys(register_Strophe.Status).reduce(function (max, k) {
  return Math.max(max, register_Strophe.Status[k]);
}, 0);
register_Strophe.Status.REGIFAIL = register_i + 1;
register_Strophe.Status.REGISTERED = register_i + 2;
register_Strophe.Status.CONFLICT = register_i + 3;
register_Strophe.Status.NOTACCEPTABLE = register_i + 5;
public_converse.plugins.add('converse-register', {
  dependencies: ['converse-controlbox'],
  enabled: function enabled() {
    return true;
  },
  initialize: function initialize() {
    var router = shared_converse.router;
    CONNECTION_STATUS[register_Strophe.Status.REGIFAIL] = 'REGIFAIL';
    CONNECTION_STATUS[register_Strophe.Status.REGISTERED] = 'REGISTERED';
    CONNECTION_STATUS[register_Strophe.Status.CONFLICT] = 'CONFLICT';
    CONNECTION_STATUS[register_Strophe.Status.NOTACCEPTABLE] = 'NOTACCEPTABLE';
    shared_api.settings.extend({
      'allow_registration': true,
      'domain_placeholder': __(' e.g. conversejs.org'),
      // Placeholder text shown in the domain input on the registration form
      'providers_link': 'https://compliance.conversations.im/',
      // Link to XMPP providers shown on registration page
      'registration_domain': ''
    });
    router.route('converse/login', function () {
      return setActiveForm('login');
    });
    router.route('converse/register', function () {
      return setActiveForm('register');
    });
  }
});
;// CONCATENATED MODULE: ./src/plugins/roomslist/model.js


var roomslist_model_Strophe = public_converse.env.Strophe;
var RoomsListModel = Model.extend({
  defaults: function defaults() {
    return {
      'muc_domain': shared_api.settings.get('muc_domain'),
      'nick': shared_converse.getDefaultMUCNickname(),
      'toggle_state': shared_converse.OPENED
    };
  },
  initialize: function initialize() {
    var _this = this;
    shared_api.settings.listen.on('change:muc_domain', function (muc_domain) {
      return _this.setDomain(muc_domain);
    });
  },
  setDomain: function setDomain(jid) {
    if (!shared_api.settings.get('locked_muc_domain')) {
      this.save('muc_domain', roomslist_model_Strophe.getDomainFromJid(jid));
    }
  }
});
/* harmony default export */ const roomslist_model = (RoomsListModel);
;// CONCATENATED MODULE: ./src/plugins/muc-views/search.js
function search_typeof(obj) {
  "@babel/helpers - typeof";

  return search_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;
  }, search_typeof(obj);
}
function search_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  search_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" == search_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 search_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 search_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        search_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        search_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}


var search_converse$env = public_converse.env,
  search_Strophe = search_converse$env.Strophe,
  search_$iq = search_converse$env.$iq,
  search_sizzle = search_converse$env.sizzle;
search_Strophe.addNamespace('MUCSEARCH', 'https://xmlns.zombofant.net/muclumbus/search/1.0');
var rooms_cache = {};
function searchRooms(_x) {
  return _searchRooms.apply(this, arguments);
}
function _searchRooms() {
  _searchRooms = search_asyncToGenerator( /*#__PURE__*/search_regeneratorRuntime().mark(function _callee(query) {
    var iq, iq_result, s;
    return search_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          iq = search_$iq({
            'type': 'get',
            'from': shared_converse.bare_jid,
            'to': 'api@search.jabber.network'
          }).c('search', {
            'xmlns': search_Strophe.NS.MUCSEARCH
          }).c('set', {
            'xmlns': search_Strophe.NS.RSM
          }).c('max').t(10).up().up().c('x', {
            'xmlns': search_Strophe.NS.XFORM,
            'type': 'submit'
          }).c('field', {
            'var': 'FORM_TYPE',
            'type': 'hidden'
          }).c('value').t('https://xmlns.zombofant.net/muclumbus/search/1.0#params').up().up().c('field', {
            'var': 'q',
            'type': 'text-single'
          }).c('value').t(query).up().up().c('field', {
            'var': 'sinname',
            'type': 'boolean'
          }).c('value').t('true').up().up().c('field', {
            'var': 'sindescription',
            'type': 'boolean'
          }).c('value').t('false').up().up().c('field', {
            'var': 'sinaddr',
            'type': 'boolean'
          }).c('value').t('true').up().up().c('field', {
            'var': 'min_users',
            'type': 'text-single'
          }).c('value').t('1').up().up().c('field', {
            'var': 'key',
            'type': 'list-single'
          }).c('value').t('address').up().c('option').c('value').t('nusers').up().up().c('option').c('value').t('address');
          _context.prev = 1;
          _context.next = 4;
          return shared_api.sendIQ(iq);
        case 4:
          iq_result = _context.sent;
          _context.next = 11;
          break;
        case 7:
          _context.prev = 7;
          _context.t0 = _context["catch"](1);
          log.error(_context.t0);
          return _context.abrupt("return", []);
        case 11:
          s = "result[xmlns=\"".concat(search_Strophe.NS.MUCSEARCH, "\"] item");
          return _context.abrupt("return", search_sizzle(s, iq_result).map(function (i) {
            var _i$querySelector;
            var jid = i.getAttribute('address');
            return {
              'label': "".concat((_i$querySelector = i.querySelector('name')) === null || _i$querySelector === void 0 ? void 0 : _i$querySelector.textContent, " (").concat(jid, ")"),
              'value': jid
            };
          }));
        case 13:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 7]]);
  }));
  return _searchRooms.apply(this, arguments);
}
function search_getAutoCompleteList(query) {
  if (!rooms_cache[query]) {
    rooms_cache[query] = searchRooms(query);
  }
  return rooms_cache[query];
}
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/templates/add-muc.js
var add_muc_templateObject, add_muc_templateObject2, add_muc_templateObject3, add_muc_templateObject4;
function add_muc_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}






var nickname_input = function nickname_input(el) {
  var i18n_nickname = __('Nickname');
  var i18n_required_field = __('This field is required');
  return (0,external_lit_namespaceObject.html)(add_muc_templateObject || (add_muc_templateObject = add_muc_taggedTemplateLiteral(["\n            <div class=\"form-group\" >\n                <label for=\"nickname\">", ":</label>\n                <input type=\"text\"\n                    title=\"", "\"\n                    required=\"required\"\n                    name=\"nickname\"\n                    value=\"", "\"\n                    class=\"form-control\"/>\n            </div>\n    "])), i18n_nickname, i18n_required_field, el.model.get('nick') || '');
};
/* harmony default export */ const add_muc = (function (el) {
  var i18n_join = __('Join');
  var muc_domain = el.model.get('muc_domain') || shared_api.settings.get('muc_domain');
  var placeholder = '';
  if (!shared_api.settings.get('locked_muc_domain')) {
    placeholder = muc_domain ? "name@".concat(muc_domain) : __('name@conference.example.org');
  }
  var label_room_address = muc_domain ? __('Groupchat name') : __('Groupchat address');
  var muc_roomid_policy_error_msg = el.muc_roomid_policy_error_msg;
  var muc_roomid_policy_hint = shared_api.settings.get('muc_roomid_policy_hint');
  return (0,external_lit_namespaceObject.html)(add_muc_templateObject2 || (add_muc_templateObject2 = add_muc_taggedTemplateLiteral(["\n        <form class=\"converse-form add-chatroom\" @submit=", ">\n            <div class=\"form-group\">\n                <label for=\"chatroom\">", ":</label>\n                ", "\n                <converse-autocomplete\n                    .getAutoCompleteList=", "\n                    ?autofocus=", "\n                    min_chars=\"3\"\n                    position=\"below\"\n                    placeholder=\"", "\"\n                    class=\"add-muc-autocomplete\"\n                    name=\"chatroom\">\n                </converse-autocomplete>\n            </div>\n            ", "\n            ", "\n            <input type=\"submit\" class=\"btn btn-primary\" name=\"join\" value=\"", "\" ?disabled=\"", "\" />\n        </form>\n    "])), function (ev) {
    return el.openChatRoom(ev);
  }, label_room_address, muc_roomid_policy_error_msg ? (0,external_lit_namespaceObject.html)(add_muc_templateObject3 || (add_muc_templateObject3 = add_muc_taggedTemplateLiteral(["<label class=\"roomid-policy-error\">", "</label>"])), muc_roomid_policy_error_msg) : '', search_getAutoCompleteList, true, placeholder, muc_roomid_policy_hint ? (0,external_lit_namespaceObject.html)(add_muc_templateObject4 || (add_muc_templateObject4 = add_muc_taggedTemplateLiteral(["<div class=\"form-group\">", "</div>"])), unsafe_html_o(purify_default().sanitize(muc_roomid_policy_hint, {
    'ALLOWED_TAGS': ['b', 'br', 'em']
  }))) : '', !shared_api.settings.get('locked_muc_nickname') ? nickname_input(el) : '', i18n_join || '', muc_roomid_policy_error_msg);
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/muc-views/styles/add-muc-modal.scss
var add_muc_modal = __webpack_require__(1188);
;// CONCATENATED MODULE: ./src/plugins/muc-views/styles/add-muc-modal.scss

      
      
      
      
      
      
      
      
      

var add_muc_modal_options = {};

add_muc_modal_options.styleTagTransform = (styleTagTransform_default());
add_muc_modal_options.setAttributes = (setAttributesWithoutAttributes_default());

      add_muc_modal_options.insert = insertBySelector_default().bind(null, "head");
    
add_muc_modal_options.domAPI = (styleDomAPI_default());
add_muc_modal_options.insertStyleElement = (insertStyleElement_default());

var add_muc_modal_update = injectStylesIntoStyleTag_default()(add_muc_modal/* default */.Z, add_muc_modal_options);




       /* harmony default export */ const styles_add_muc_modal = (add_muc_modal/* default */.Z && add_muc_modal/* default */.Z.locals ? add_muc_modal/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/add-muc.js
function add_muc_typeof(obj) {
  "@babel/helpers - typeof";

  return add_muc_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;
  }, add_muc_typeof(obj);
}
function add_muc_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function add_muc_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, add_muc_toPropertyKey(descriptor.key), descriptor);
  }
}
function add_muc_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) add_muc_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) add_muc_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function add_muc_toPropertyKey(arg) {
  var key = add_muc_toPrimitive(arg, "string");
  return add_muc_typeof(key) === "symbol" ? key : String(key);
}
function add_muc_toPrimitive(input, hint) {
  if (add_muc_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (add_muc_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function add_muc_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    add_muc_get = Reflect.get.bind();
  } else {
    add_muc_get = function _get(target, property, receiver) {
      var base = add_muc_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return add_muc_get.apply(this, arguments);
}
function add_muc_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = add_muc_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function add_muc_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) add_muc_setPrototypeOf(subClass, superClass);
}
function add_muc_setPrototypeOf(o, p) {
  add_muc_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return add_muc_setPrototypeOf(o, p);
}
function add_muc_createSuper(Derived) {
  var hasNativeReflectConstruct = add_muc_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = add_muc_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = add_muc_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return add_muc_possibleConstructorReturn(this, result);
  };
}
function add_muc_possibleConstructorReturn(self, call) {
  if (call && (add_muc_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 add_muc_assertThisInitialized(self);
}
function add_muc_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function add_muc_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 add_muc_getPrototypeOf(o) {
  add_muc_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return add_muc_getPrototypeOf(o);
}





var add_muc_u = public_converse.env.utils;
var add_muc_Strophe = public_converse.env.Strophe;
var AddMUCModal = /*#__PURE__*/function (_BaseModal) {
  add_muc_inherits(AddMUCModal, _BaseModal);
  var _super = add_muc_createSuper(AddMUCModal);
  function AddMUCModal() {
    add_muc_classCallCheck(this, AddMUCModal);
    return _super.apply(this, arguments);
  }
  add_muc_createClass(AddMUCModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      add_muc_get(add_muc_getPrototypeOf(AddMUCModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change:muc_domain', function () {
        return _this.render();
      });
      this.muc_roomid_policy_error_msg = null;
      this.render();
      this.addEventListener('shown.bs.modal', function () {
        _this.querySelector('input[name="chatroom"]').focus();
      }, false);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return add_muc(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Enter a new Groupchat');
    }
  }, {
    key: "parseRoomDataFromEvent",
    value: function parseRoomDataFromEvent(form) {
      var _data$get;
      // eslint-disable-line class-methods-use-this
      var data = new FormData(form);
      var jid = (_data$get = data.get('chatroom')) === null || _data$get === void 0 ? void 0 : _data$get.trim();
      var nick;
      if (shared_api.settings.get('locked_muc_nickname')) {
        nick = shared_converse.getDefaultMUCNickname();
        if (!nick) {
          throw new Error("Using locked_muc_nickname but no nickname found!");
        }
      } else {
        nick = data.get('nickname').trim();
      }
      return {
        'jid': jid,
        'nick': nick
      };
    }
  }, {
    key: "openChatRoom",
    value: function openChatRoom(ev) {
      ev.preventDefault();
      if (this.checkRoomidPolicy()) return;
      var data = this.parseRoomDataFromEvent(ev.target);
      if (data.nick === "") {
        // Make sure defaults apply if no nick is provided.
        data.nick = undefined;
      }
      var jid;
      if (shared_api.settings.get('locked_muc_domain') || shared_api.settings.get('muc_domain') && !add_muc_u.isValidJID(data.jid)) {
        jid = "".concat(add_muc_Strophe.escapeNode(data.jid), "@").concat(shared_api.settings.get('muc_domain'));
      } else {
        jid = data.jid;
        this.model.setDomain(jid);
      }
      shared_api.rooms.open(jid, Object.assign(data, {
        jid: jid
      }), true);
      ev.target.reset();
      this.modal.hide();
    }
  }, {
    key: "checkRoomidPolicy",
    value: function checkRoomidPolicy() {
      if (shared_api.settings.get('muc_roomid_policy') && shared_api.settings.get('muc_domain')) {
        var jid = this.querySelector('converse-autocomplete input').value;
        if (shared_api.settings.get('locked_muc_domain') || !add_muc_u.isValidJID(jid)) {
          jid = "".concat(add_muc_Strophe.escapeNode(jid), "@").concat(shared_api.settings.get('muc_domain'));
        }
        var roomid = add_muc_Strophe.getNodeFromJid(jid);
        var roomdomain = add_muc_Strophe.getDomainFromJid(jid);
        if (shared_api.settings.get('muc_domain') !== roomdomain || shared_api.settings.get('muc_roomid_policy').test(roomid)) {
          this.muc_roomid_policy_error_msg = null;
        } else {
          this.muc_roomid_policy_error_msg = __('Groupchat id is invalid.');
          return true;
        }
        this.render();
      }
    }
  }]);
  return AddMUCModal;
}(modal_modal);

shared_api.elements.define('converse-add-muc-modal', AddMUCModal);
;// CONCATENATED MODULE: ./node_modules/lodash-es/head.js
/**
 * Gets the first element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @alias first
 * @category Array
 * @param {Array} array The array to query.
 * @returns {*} Returns the first element of `array`.
 * @example
 *
 * _.head([1, 2, 3]);
 * // => 1
 *
 * _.head([]);
 * // => undefined
 */
function head(array) {
  return array && array.length ? array[0] : undefined;
}
/* harmony default export */ const lodash_es_head = (head);
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-description.js
var muc_description_templateObject, muc_description_templateObject2, muc_description_templateObject3, muc_description_templateObject4, muc_description_templateObject5, muc_description_templateObject6, muc_description_templateObject7, muc_description_templateObject8, muc_description_templateObject9, muc_description_templateObject10, muc_description_templateObject11, muc_description_templateObject12;
function muc_description_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const muc_description = (function (o) {
  var i18n_desc = __('Description:');
  var i18n_jid = __('Groupchat XMPP Address:');
  var i18n_occ = __('Participants:');
  var i18n_features = __('Features:');
  var i18n_requires_auth = __('Requires authentication');
  var i18n_hidden = __('Hidden');
  var i18n_requires_invite = __('Requires an invitation');
  var i18n_moderated = __('Moderated');
  var i18n_non_anon = __('Non-anonymous');
  var i18n_open_room = __('Open');
  var i18n_permanent_room = __('Permanent');
  var i18n_public = __('Public');
  var i18n_semi_anon = __('Semi-anonymous');
  var i18n_temp_room = __('Temporary');
  var i18n_unmoderated = __('Unmoderated');
  return (0,external_lit_namespaceObject.html)(muc_description_templateObject || (muc_description_templateObject = muc_description_taggedTemplateLiteral(["\n    <div class=\"room-info\">\n        <p class=\"room-info\"><strong>", "</strong> ", "</p>\n        <p class=\"room-info\"><strong>", "</strong> ", "</p>\n        <p class=\"room-info\"><strong>", "</strong> ", "</p>\n        <p class=\"room-info\"><strong>", "</strong>\n            <ul>\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n                ", "\n            </ul>\n        </p>\n    </div>\n"])), i18n_jid, o.jid, i18n_desc, o.desc, i18n_occ, o.occ, i18n_features, o.passwordprotected ? (0,external_lit_namespaceObject.html)(muc_description_templateObject2 || (muc_description_templateObject2 = muc_description_taggedTemplateLiteral(["<li class=\"room-info locked\">", "</li>"])), i18n_requires_auth) : '', o.hidden ? (0,external_lit_namespaceObject.html)(muc_description_templateObject3 || (muc_description_templateObject3 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_hidden) : '', o.membersonly ? (0,external_lit_namespaceObject.html)(muc_description_templateObject4 || (muc_description_templateObject4 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_requires_invite) : '', o.moderated ? (0,external_lit_namespaceObject.html)(muc_description_templateObject5 || (muc_description_templateObject5 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_moderated) : '', o.nonanonymous ? (0,external_lit_namespaceObject.html)(muc_description_templateObject6 || (muc_description_templateObject6 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_non_anon) : '', o.open ? (0,external_lit_namespaceObject.html)(muc_description_templateObject7 || (muc_description_templateObject7 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_open_room) : '', o.persistent ? (0,external_lit_namespaceObject.html)(muc_description_templateObject8 || (muc_description_templateObject8 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_permanent_room) : '', o.publicroom ? (0,external_lit_namespaceObject.html)(muc_description_templateObject9 || (muc_description_templateObject9 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_public) : '', o.semianonymous ? (0,external_lit_namespaceObject.html)(muc_description_templateObject10 || (muc_description_templateObject10 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_semi_anon) : '', o.temporary ? (0,external_lit_namespaceObject.html)(muc_description_templateObject11 || (muc_description_templateObject11 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_temp_room) : '', o.unmoderated ? (0,external_lit_namespaceObject.html)(muc_description_templateObject12 || (muc_description_templateObject12 = muc_description_taggedTemplateLiteral(["<li class=\"room-info\">", "</li>"])), i18n_unmoderated) : '');
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/templates/muc-list.js
var muc_list_templateObject, muc_list_templateObject2, muc_list_templateObject3, muc_list_templateObject4, muc_list_templateObject5;
function muc_list_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var muc_list_form = function form(o) {
  var i18n_query = __('Show groupchats');
  var i18n_server_address = __('Server address');
  return (0,external_lit_namespaceObject.html)(muc_list_templateObject || (muc_list_templateObject = muc_list_taggedTemplateLiteral(["\n        <form class=\"converse-form list-chatrooms\"\n            @submit=", ">\n            <div class=\"form-group\">\n                <label for=\"chatroom\">", ":</label>\n                <input type=\"text\"\n                    autofocus\n                    @change=", "\n                    value=\"", "\"\n                    required=\"required\"\n                    name=\"server\"\n                    class=\"form-control\"\n                    placeholder=\"", "\"/>\n            </div>\n            <input type=\"submit\" class=\"btn btn-primary\" name=\"list\" value=\"", "\"/>\n        </form>\n    "])), o.submitForm, i18n_server_address, o.setDomainFromEvent, o.muc_domain || '', o.server_placeholder, i18n_query);
};
var tplItem = function tplItem(o, item) {
  var i18n_info_title = __('Show more information on this groupchat');
  var i18n_open_title = __('Click to open this groupchat');
  return (0,external_lit_namespaceObject.html)(muc_list_templateObject2 || (muc_list_templateObject2 = muc_list_taggedTemplateLiteral(["\n        <li class=\"room-item list-group-item\">\n            <div class=\"available-chatroom d-flex flex-row\">\n                <a class=\"open-room available-room w-100\"\n                    @click=", "\n                    data-room-jid=\"", "\"\n                    data-room-name=\"", "\"\n                    title=\"", "\"\n                    href=\"#\">", "</a>\n                    <a class=\"right room-info icon-room-info\"\n                    @click=", "\n                    data-room-jid=\"", "\"\n                    title=\"", "\"\n                    href=\"#\"></a>\n            </div>\n        </li>\n    "])), o.openRoom, item.jid, item.name, i18n_open_title, item.name || item.jid, o.toggleRoomInfo, item.jid, i18n_info_title);
};
/* harmony default export */ const muc_list = (function (o) {
  return (0,external_lit_namespaceObject.html)(muc_list_templateObject3 || (muc_list_templateObject3 = muc_list_taggedTemplateLiteral(["\n        ", "\n        <ul class=\"available-chatrooms list-group\">\n            ", "\n            ", "\n            ", "\n        </ul>\n    "])), o.show_form ? muc_list_form(o) : '', o.loading_items ? (0,external_lit_namespaceObject.html)(muc_list_templateObject4 || (muc_list_templateObject4 = muc_list_taggedTemplateLiteral(["<li class=\"list-group-item\"> ", " </li>"])), spinner()) : '', o.feedback_text ? (0,external_lit_namespaceObject.html)(muc_list_templateObject5 || (muc_list_templateObject5 = muc_list_taggedTemplateLiteral(["<li class=\"list-group-item active\">", "</li>"])), o.feedback_text) : '', repeat_c(o.items, function (item) {
    return item.jid;
  }, function (item) {
    return tplItem(o, item);
  }));
});
;// CONCATENATED MODULE: ./src/plugins/muc-views/modals/muc-list.js
function muc_list_typeof(obj) {
  "@babel/helpers - typeof";

  return muc_list_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;
  }, muc_list_typeof(obj);
}
function muc_list_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function muc_list_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, muc_list_toPropertyKey(descriptor.key), descriptor);
  }
}
function muc_list_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) muc_list_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) muc_list_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function muc_list_toPropertyKey(arg) {
  var key = muc_list_toPrimitive(arg, "string");
  return muc_list_typeof(key) === "symbol" ? key : String(key);
}
function muc_list_toPrimitive(input, hint) {
  if (muc_list_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (muc_list_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function muc_list_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    muc_list_get = Reflect.get.bind();
  } else {
    muc_list_get = function _get(target, property, receiver) {
      var base = muc_list_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return muc_list_get.apply(this, arguments);
}
function muc_list_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = muc_list_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function muc_list_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) muc_list_setPrototypeOf(subClass, superClass);
}
function muc_list_setPrototypeOf(o, p) {
  muc_list_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return muc_list_setPrototypeOf(o, p);
}
function muc_list_createSuper(Derived) {
  var hasNativeReflectConstruct = muc_list_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = muc_list_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = muc_list_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return muc_list_possibleConstructorReturn(this, result);
  };
}
function muc_list_possibleConstructorReturn(self, call) {
  if (call && (muc_list_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 muc_list_assertThisInitialized(self);
}
function muc_list_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function muc_list_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 muc_list_getPrototypeOf(o) {
  muc_list_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return muc_list_getPrototypeOf(o);
}









var muc_list_converse$env = public_converse.env,
  muc_list_Strophe = muc_list_converse$env.Strophe,
  muc_list_$iq = muc_list_converse$env.$iq,
  muc_list_sizzle = muc_list_converse$env.sizzle;
var muc_list_u = public_converse.env.utils;

/* Insert groupchat info (based on returned #disco IQ stanza)
 * @function insertRoomInfo
 * @param { HTMLElement } el - The HTML DOM element that contains the info.
 * @param { Element } stanza - The IQ stanza containing the groupchat info.
 */
function insertRoomInfo(el, stanza) {
  var _head, _head2;
  // All MUC features found here: https://xmpp.org/registrar/disco-features.html
  el.querySelector('span.spinner').remove();
  el.querySelector('a.room-info').classList.add('selected');
  el.insertAdjacentHTML('beforeEnd', muc_list_u.getElementFromTemplateResult(muc_description({
    'jid': stanza.getAttribute('from'),
    'desc': (_head = lodash_es_head(muc_list_sizzle('field[var="muc#roominfo_description"] value', stanza))) === null || _head === void 0 ? void 0 : _head.textContent,
    'occ': (_head2 = lodash_es_head(muc_list_sizzle('field[var="muc#roominfo_occupants"] value', stanza))) === null || _head2 === void 0 ? void 0 : _head2.textContent,
    'hidden': muc_list_sizzle('feature[var="muc_hidden"]', stanza).length,
    'membersonly': muc_list_sizzle('feature[var="muc_membersonly"]', stanza).length,
    'moderated': muc_list_sizzle('feature[var="muc_moderated"]', stanza).length,
    'nonanonymous': muc_list_sizzle('feature[var="muc_nonanonymous"]', stanza).length,
    'open': muc_list_sizzle('feature[var="muc_open"]', stanza).length,
    'passwordprotected': muc_list_sizzle('feature[var="muc_passwordprotected"]', stanza).length,
    'persistent': muc_list_sizzle('feature[var="muc_persistent"]', stanza).length,
    'publicroom': muc_list_sizzle('feature[var="muc_publicroom"]', stanza).length,
    'semianonymous': muc_list_sizzle('feature[var="muc_semianonymous"]', stanza).length,
    'temporary': muc_list_sizzle('feature[var="muc_temporary"]', stanza).length,
    'unmoderated': muc_list_sizzle('feature[var="muc_unmoderated"]', stanza).length
  })));
}

/**
 * Show/hide extra information about a groupchat in a listing.
 * @function toggleRoomInfo
 * @param { Event }
 */
function _toggleRoomInfo(ev) {
  var parent_el = muc_list_u.ancestor(ev.target, '.room-item');
  var div_el = parent_el.querySelector('div.room-info');
  if (div_el) {
    muc_list_u.slideIn(div_el).then(muc_list_u.removeElement);
    parent_el.querySelector('a.room-info').classList.remove('selected');
  } else {
    parent_el.insertAdjacentElement('beforeend', muc_list_u.getElementFromTemplateResult(spinner()));
    shared_api.disco.info(ev.target.getAttribute('data-room-jid'), null).then(function (stanza) {
      return insertRoomInfo(parent_el, stanza);
    }).catch(function (e) {
      return log.error(e);
    });
  }
}
var MUCListModal = /*#__PURE__*/function (_BaseModal) {
  muc_list_inherits(MUCListModal, _BaseModal);
  var _super = muc_list_createSuper(MUCListModal);
  function MUCListModal(options) {
    var _this;
    muc_list_classCallCheck(this, MUCListModal);
    _this = _super.call(this, options);
    _this.items = [];
    _this.loading_items = false;
    return _this;
  }
  muc_list_createClass(MUCListModal, [{
    key: "initialize",
    value: function initialize() {
      var _this2 = this;
      muc_list_get(muc_list_getPrototypeOf(MUCListModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change:muc_domain', this.onDomainChange);
      this.listenTo(this.model, 'change:feedback_text', function () {
        return _this2.render();
      });
      this.addEventListener('shown.bs.modal', function () {
        return shared_api.settings.get('locked_muc_domain') && _this2.updateRoomsList();
      });
      this.model.save('feedback_text', '');
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      var _this3 = this;
      return muc_list(Object.assign(this.model.toJSON(), {
        'show_form': !shared_api.settings.get('locked_muc_domain'),
        'server_placeholder': this.model.get('muc_domain') || __('conference.example.org'),
        'items': this.items,
        'loading_items': this.loading_items,
        'openRoom': function openRoom(ev) {
          return _this3.openRoom(ev);
        },
        'setDomainFromEvent': function setDomainFromEvent(ev) {
          return _this3.setDomainFromEvent(ev);
        },
        'submitForm': function submitForm(ev) {
          return _this3.showRooms(ev);
        },
        'toggleRoomInfo': function toggleRoomInfo(ev) {
          return _this3.toggleRoomInfo(ev);
        }
      }));
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Query for Groupchats');
    }
  }, {
    key: "openRoom",
    value: function openRoom(ev) {
      ev.preventDefault();
      var jid = ev.target.getAttribute('data-room-jid');
      var name = ev.target.getAttribute('data-room-name');
      this.modal.hide();
      shared_api.rooms.open(jid, {
        'name': name
      }, true);
    }
  }, {
    key: "toggleRoomInfo",
    value: function toggleRoomInfo(ev) {
      // eslint-disable-line
      ev.preventDefault();
      _toggleRoomInfo(ev);
    }
  }, {
    key: "onDomainChange",
    value: function onDomainChange() {
      shared_api.settings.get('auto_list_rooms') && this.updateRoomsList();
    }

    /**
     * Handle the IQ stanza returned from the server, containing
     * all its public groupchats.
     * @private
     * @method _converse.ChatRoomView#onRoomsFound
     * @param { HTMLElement } iq
     */
  }, {
    key: "onRoomsFound",
    value: function onRoomsFound(iq) {
      this.loading_items = false;
      var rooms = iq ? muc_list_sizzle('query item', iq) : [];
      if (rooms.length) {
        this.model.set({
          'feedback_text': __('Groupchats found')
        }, {
          'silent': true
        });
        this.items = rooms.map(getAttributes);
      } else {
        this.items = [];
        this.model.set({
          'feedback_text': __('No groupchats found')
        }, {
          'silent': true
        });
      }
      this.render();
      return true;
    }

    /**
     * Send an IQ stanza to the server asking for all groupchats
     * @private
     * @method _converse.ChatRoomView#updateRoomsList
     */
  }, {
    key: "updateRoomsList",
    value: function updateRoomsList() {
      var _this4 = this;
      var iq = muc_list_$iq({
        'to': this.model.get('muc_domain'),
        'from': shared_converse.connection.jid,
        'type': "get"
      }).c("query", {
        xmlns: muc_list_Strophe.NS.DISCO_ITEMS
      });
      shared_api.sendIQ(iq).then(function (iq) {
        return _this4.onRoomsFound(iq);
      }).catch(function () {
        return _this4.onRoomsFound();
      });
    }
  }, {
    key: "showRooms",
    value: function showRooms(ev) {
      ev.preventDefault();
      this.loading_items = true;
      this.render();
      var data = new FormData(ev.target);
      this.model.setDomain(data.get('server'));
      this.updateRoomsList();
    }
  }, {
    key: "setDomainFromEvent",
    value: function setDomainFromEvent(ev) {
      this.model.setDomain(ev.target.value);
    }
  }, {
    key: "setNick",
    value: function setNick(ev) {
      this.model.save({
        nick: ev.target.value
      });
    }
  }]);
  return MUCListModal;
}(modal_modal);

shared_api.elements.define('converse-muc-list-modal', MUCListModal);
;// CONCATENATED MODULE: ./src/plugins/roomslist/templates/roomslist.js
var roomslist_templateObject, roomslist_templateObject2, roomslist_templateObject3, roomslist_templateObject4, roomslist_templateObject5;
function roomslist_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}







function isCurrentlyOpen(room) {
  return isUniView() && !room.get('hidden');
}
function tplBookmark(room) {
  var _room$get;
  var bm = (_room$get = room.get('bookmarked')) !== null && _room$get !== void 0 ? _room$get : false;
  var i18n_bookmark = __('Bookmark');
  return (0,external_lit_namespaceObject.html)(roomslist_templateObject || (roomslist_templateObject = roomslist_taggedTemplateLiteral(["\n        <a class=\"list-item-action add-bookmark\"\n            data-room-jid=\"", "\"\n            data-bookmark-name=\"", "\"\n            @click=", "\n            title=\"", "\">\n\n            <converse-icon class=\"fa ", "\"\n                           size=\"1.2em\"\n                           color=\"", "\"></converse-icon>\n        </a>"])), room.get('jid'), room.getDisplayName(), function (ev) {
    return addBookmarkViaEvent(ev);
  }, i18n_bookmark, bm ? 'fa-bookmark' : 'fa-bookmark-empty', isCurrentlyOpen(room) ? 'var(--inverse-link-color)' : '');
}
var tplUnreadIndicator = function tplUnreadIndicator(room) {
  return (0,external_lit_namespaceObject.html)(roomslist_templateObject2 || (roomslist_templateObject2 = roomslist_taggedTemplateLiteral(["<span class=\"list-item-badge badge badge--muc msgs-indicator\">", "</span>"])), room.get('num_unread'));
};
var tplActivityIndicator = function tplActivityIndicator() {
  return (0,external_lit_namespaceObject.html)(roomslist_templateObject3 || (roomslist_templateObject3 = roomslist_taggedTemplateLiteral(["<span class=\"list-item-badge badge badge--muc msgs-indicator\"></span>"])));
};
function tplRoomItem(el, room) {
  var i18n_leave_room = __('Leave this groupchat');
  var has_unread_msgs = room.get('num_unread_general') || room.get('has_activity');
  return (0,external_lit_namespaceObject.html)(roomslist_templateObject4 || (roomslist_templateObject4 = roomslist_taggedTemplateLiteral(["\n        <div class=\"list-item controlbox-padded available-chatroom d-flex flex-row ", " ", "\"\n            data-room-jid=\"", "\">\n\n            ", "\n\n            <a class=\"list-item-link open-room available-room w-100\"\n                data-room-jid=\"", "\"\n                title=\"", "\"\n                @click=", ">", "</a>\n\n            ", "\n\n            <a class=\"list-item-action room-info\"\n                data-room-jid=\"", "\"\n                title=\"", "\"\n                @click=", ">\n\n                <converse-icon class=\"fa fa-info-circle\" size=\"1.2em\" color=\"", "\"></converse-icon>\n            </a>\n\n            <a class=\"list-item-action close-room\"\n                data-room-jid=\"", "\"\n                data-room-name=\"", "\"\n                title=\"", "\"\n                @click=", ">\n                <converse-icon class=\"fa fa-sign-out-alt\" size=\"1.2em\" color=\"", "\"></converse-icon>\n            </a>\n        </div>"])), isCurrentlyOpen(room) ? 'open' : '', has_unread_msgs ? 'unread-msgs' : '', room.get('jid'), room.get('num_unread') ? tplUnreadIndicator(room) : room.get('has_activity') ? tplActivityIndicator() : '', room.get('jid'), __('Click to open this groupchat'), function (ev) {
    return el.openRoom(ev);
  }, room.getDisplayName(), shared_api.settings.get('allow_bookmarks') ? tplBookmark(room) : '', room.get('jid'), __('Show more information on this groupchat'), function (ev) {
    return el.showRoomDetailsModal(ev);
  }, isCurrentlyOpen(room) ? 'var(--inverse-link-color)' : '', room.get('jid'), room.getDisplayName(), i18n_leave_room, function (ev) {
    return el.closeRoom(ev);
  }, isCurrentlyOpen(room) ? 'var(--inverse-link-color)' : '');
}
/* harmony default export */ const roomslist = (function (el) {
  var chatboxes = shared_converse.chatboxes,
    CHATROOMS_TYPE = shared_converse.CHATROOMS_TYPE,
    CLOSED = shared_converse.CLOSED;
  var rooms = chatboxes.filter(function (m) {
    return m.get('type') === CHATROOMS_TYPE;
  });
  rooms.sort(function (a, b) {
    return a.getDisplayName().toLowerCase() <= b.getDisplayName().toLowerCase() ? -1 : 1;
  });
  var i18n_desc_rooms = __('Click to toggle the list of open groupchats');
  var i18n_heading_chatrooms = __('Groupchats');
  var i18n_title_list_rooms = __('Query for groupchats');
  var i18n_title_new_room = __('Add a new groupchat');
  var i18n_show_bookmarks = __('Show bookmarked groupchats');
  var is_closed = el.model.get('toggle_state') === CLOSED;
  return (0,external_lit_namespaceObject.html)(roomslist_templateObject5 || (roomslist_templateObject5 = roomslist_taggedTemplateLiteral(["\n        <div class=\"d-flex controlbox-padded\">\n            <span class=\"w-100 controlbox-heading controlbox-heading--groupchats\">\n                <a class=\"list-toggle open-rooms-toggle\" title=\"", "\" @click=", ">\n                    <converse-icon\n                        class=\"fa ", "\"\n                        size=\"1em\"\n                        color=\"var(--muc-color)\"></converse-icon>\n                    ", "\n                </a>\n            </span>\n\n            <a class=\"controlbox-heading__btn show-bookmark-list-modal\"\n                @click=", "\n                title=\"", "\"\n                data-toggle=\"modal\">\n                    <converse-icon class=\"fa fa-bookmark right\" size=\"1em\"></converse-icon>\n            </a>\n\n            <a class=\"controlbox-heading__btn show-list-muc-modal\"\n                @click=", "\n                title=\"", "\" data-toggle=\"modal\" data-target=\"#muc-list-modal\">\n                    <converse-icon class=\"fa fa-list-ul right\" size=\"1em\"></converse-icon>\n            </a>\n            <a class=\"controlbox-heading__btn show-add-muc-modal\"\n                @click=", "\n                title=\"", "\" data-toggle=\"modal\" data-target=\"#add-chatrooms-modal\">\n                    <converse-icon class=\"fa fa-plus right\" size=\"1em\"></converse-icon>\n            </a>\n        </div>\n\n        <div class=\"list-container list-container--openrooms ", "\">\n            <div class=\"items-list rooms-list open-rooms-list ", "\">\n                ", "\n            </div>\n        </div>"])), i18n_desc_rooms, function (ev) {
    return el.toggleRoomsList(ev);
  }, is_closed ? 'fa-caret-right' : 'fa-caret-down', i18n_heading_chatrooms, function (ev) {
    return shared_api.modal.show('converse-bookmark-list-modal', {
      'model': el.model
    }, ev);
  }, i18n_show_bookmarks, function (ev) {
    return shared_api.modal.show('converse-muc-list-modal', {
      'model': el.model
    }, ev);
  }, i18n_title_list_rooms, function (ev) {
    return shared_api.modal.show('converse-add-muc-modal', {
      'model': el.model
    }, ev);
  }, i18n_title_new_room, rooms.length ? '' : 'hidden', is_closed ? 'collapsed' : '', rooms.map(function (room) {
    return tplRoomItem(el, room);
  }));
});
;// CONCATENATED MODULE: ./src/plugins/roomslist/view.js
function roomslist_view_typeof(obj) {
  "@babel/helpers - typeof";

  return roomslist_view_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;
  }, roomslist_view_typeof(obj);
}
function roomslist_view_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  roomslist_view_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" == roomslist_view_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 roomslist_view_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 roomslist_view_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        roomslist_view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        roomslist_view_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function roomslist_view_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function roomslist_view_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, roomslist_view_toPropertyKey(descriptor.key), descriptor);
  }
}
function roomslist_view_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) roomslist_view_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) roomslist_view_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function roomslist_view_toPropertyKey(arg) {
  var key = roomslist_view_toPrimitive(arg, "string");
  return roomslist_view_typeof(key) === "symbol" ? key : String(key);
}
function roomslist_view_toPrimitive(input, hint) {
  if (roomslist_view_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (roomslist_view_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function roomslist_view_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) roomslist_view_setPrototypeOf(subClass, superClass);
}
function roomslist_view_setPrototypeOf(o, p) {
  roomslist_view_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return roomslist_view_setPrototypeOf(o, p);
}
function roomslist_view_createSuper(Derived) {
  var hasNativeReflectConstruct = roomslist_view_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = roomslist_view_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = roomslist_view_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return roomslist_view_possibleConstructorReturn(this, result);
  };
}
function roomslist_view_possibleConstructorReturn(self, call) {
  if (call && (roomslist_view_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 roomslist_view_assertThisInitialized(self);
}
function roomslist_view_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function roomslist_view_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 roomslist_view_getPrototypeOf(o) {
  roomslist_view_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return roomslist_view_getPrototypeOf(o);
}







var view_converse$env = public_converse.env,
  view_Strophe = view_converse$env.Strophe,
  view_u = view_converse$env.u;
var RoomsList = /*#__PURE__*/function (_CustomElement) {
  roomslist_view_inherits(RoomsList, _CustomElement);
  var _super = roomslist_view_createSuper(RoomsList);
  function RoomsList() {
    roomslist_view_classCallCheck(this, RoomsList);
    return _super.apply(this, arguments);
  }
  roomslist_view_createClass(RoomsList, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      var id = "converse.roomspanel".concat(shared_converse.bare_jid);
      this.model = new roomslist_model({
        id: id
      });
      initStorage(this.model, id);
      this.model.fetch();
      this.listenTo(shared_converse.chatboxes, 'add', this.renderIfChatRoom);
      this.listenTo(shared_converse.chatboxes, 'remove', this.renderIfChatRoom);
      this.listenTo(shared_converse.chatboxes, 'destroy', this.renderIfChatRoom);
      this.listenTo(shared_converse.chatboxes, 'change', this.renderIfRelevantChange);
      this.listenTo(this.model, 'change', function () {
        return _this.requestUpdate();
      });
      this.requestUpdate();
    }
  }, {
    key: "render",
    value: function render() {
      return roomslist(this);
    }
  }, {
    key: "renderIfChatRoom",
    value: function renderIfChatRoom(model) {
      view_u.isChatRoom(model) && this.requestUpdate();
    }
  }, {
    key: "renderIfRelevantChange",
    value: function renderIfRelevantChange(model) {
      var attrs = ['bookmarked', 'hidden', 'name', 'num_unread', 'num_unread_general', 'has_activity'];
      var changed = model.changed || {};
      if (view_u.isChatRoom(model) && Object.keys(changed).filter(function (m) {
        return attrs.includes(m);
      }).length) {
        this.requestUpdate();
      }
    }
  }, {
    key: "showRoomDetailsModal",
    value: function showRoomDetailsModal(ev) {
      // eslint-disable-line class-methods-use-this
      var jid = ev.currentTarget.getAttribute('data-room-jid');
      var room = shared_converse.chatboxes.get(jid);
      ev.preventDefault();
      shared_api.modal.show('converse-muc-details-modal', {
        'model': room
      }, ev);
    }
  }, {
    key: "openRoom",
    value: function () {
      var _openRoom = roomslist_view_asyncToGenerator( /*#__PURE__*/roomslist_view_regeneratorRuntime().mark(function _callee(ev) {
        var name, jid, data;
        return roomslist_view_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              // eslint-disable-line class-methods-use-this
              ev.preventDefault();
              name = ev.target.textContent;
              jid = ev.target.getAttribute('data-room-jid');
              data = {
                'name': name || view_Strophe.unescapeNode(view_Strophe.getNodeFromJid(jid)) || jid
              };
              _context.next = 6;
              return shared_api.rooms.open(jid, data, true);
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      function openRoom(_x) {
        return _openRoom.apply(this, arguments);
      }
      return openRoom;
    }()
  }, {
    key: "closeRoom",
    value: function () {
      var _closeRoom = roomslist_view_asyncToGenerator( /*#__PURE__*/roomslist_view_regeneratorRuntime().mark(function _callee2(ev) {
        var name, jid, result, room;
        return roomslist_view_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              // eslint-disable-line class-methods-use-this
              ev.preventDefault();
              name = ev.currentTarget.getAttribute('data-room-name');
              jid = ev.currentTarget.getAttribute('data-room-jid');
              _context2.next = 5;
              return shared_api.confirm(__("Are you sure you want to leave the groupchat %1$s?", name));
            case 5:
              result = _context2.sent;
              if (!result) {
                _context2.next = 11;
                break;
              }
              _context2.next = 9;
              return shared_api.rooms.get(jid);
            case 9:
              room = _context2.sent;
              room.close();
            case 11:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      function closeRoom(_x2) {
        return _closeRoom.apply(this, arguments);
      }
      return closeRoom;
    }()
  }, {
    key: "toggleRoomsList",
    value: function toggleRoomsList(ev) {
      var _ev$preventDefault,
        _this2 = this;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      var list_el = this.querySelector('.open-rooms-list');
      if (this.model.get('toggle_state') === shared_converse.CLOSED) {
        view_u.slideOut(list_el).then(function () {
          return _this2.model.save({
            'toggle_state': shared_converse.OPENED
          });
        });
      } else {
        view_u.slideIn(list_el).then(function () {
          return _this2.model.save({
            'toggle_state': shared_converse.CLOSED
          });
        });
      }
    }
  }]);
  return RoomsList;
}(CustomElement);
shared_api.elements.define('converse-rooms-list', RoomsList);
;// CONCATENATED MODULE: ./src/plugins/roomslist/index.js
/**
 * @description
 *  Converse.js plugin which shows a list of currently open
 *  rooms in the "Rooms Panel" of the ControlBox.
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



public_converse.plugins.add('converse-roomslist', {
  dependencies: ["converse-singleton", "converse-controlbox", "converse-muc", "converse-bookmarks"],
  initialize: function initialize() {}
});
;// CONCATENATED MODULE: ./src/shared/templates/icons.js
var templates_icons_templateObject;
function templates_icons_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const icons = (function () {
  return (0,external_lit_namespaceObject.html)(templates_icons_templateObject || (templates_icons_templateObject = templates_icons_taggedTemplateLiteral(["\n    <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <!--\n    Font Awesome Free 5.13.0 by @fontawesome - https://fontawesome.com\n    License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)\n    -->\n    <svg xmlns=\"http://www.w3.org/2000/svg\" style=\"display: none;\">\n    <symbol id=\"icon-address-book\" viewBox=\"0 0 448 512\">\n        <path d=\"M436 160c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20V48c0-26.5-21.5-48-48-48H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h320c26.5 0 48-21.5 48-48v-48h20c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20v-64h20c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20v-64h20zm-228-32c35.3 0 64 28.7 64 64s-28.7 64-64 64-64-28.7-64-64 28.7-64 64-64zm112 236.8c0 10.6-10 19.2-22.4 19.2H118.4C106 384 96 375.4 96 364.8v-19.2c0-31.8 30.1-57.6 67.2-57.6h5c12.3 5.1 25.7 8 39.8 8s27.6-2.9 39.8-8h5c37.1 0 67.2 25.8 67.2 57.6v19.2z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-double-down\" viewBox=\"0 0 320 512\">\n        <path d=\"M143 256.3L7 120.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0L313 86.3c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.4 9.5-24.6 9.5-34 .1zm34 192l136-136c9.4-9.4 9.4-24.6 0-33.9l-22.6-22.6c-9.4-9.4-24.6-9.4-33.9 0L160 352.1l-96.4-96.4c-9.4-9.4-24.6-9.4-33.9 0L7 278.3c-9.4 9.4-9.4 24.6 0 33.9l136 136c9.4 9.5 24.6 9.5 34 .1z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-double-left\" viewBox=\"0 0 448 512\">\n        <path d=\"M223.7 239l136-136c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9L319.9 256l96.4 96.4c9.4 9.4 9.4 24.6 0 33.9L393.7 409c-9.4 9.4-24.6 9.4-33.9 0l-136-136c-9.5-9.4-9.5-24.6-.1-34zm-192 34l136 136c9.4 9.4 24.6 9.4 33.9 0l22.6-22.6c9.4-9.4 9.4-24.6 0-33.9L127.9 256l96.4-96.4c9.4-9.4 9.4-24.6 0-33.9L201.7 103c-9.4-9.4-24.6-9.4-33.9 0l-136 136c-9.5 9.4-9.5 24.6-.1 34z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-double-right\" viewBox=\"0 0 448 512\">\n        <path d=\"M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34zm192-34l-136-136c-9.4-9.4-24.6-9.4-33.9 0l-22.6 22.6c-9.4 9.4-9.4 24.6 0 33.9l96.4 96.4-96.4 96.4c-9.4 9.4-9.4 24.6 0 33.9l22.6 22.6c9.4 9.4 24.6 9.4 33.9 0l136-136c9.4-9.2 9.4-24.4 0-33.8z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-double-up\" viewBox=\"0 0 320 512\">\n        <path d=\"M177 255.7l136 136c9.4 9.4 9.4 24.6 0 33.9l-22.6 22.6c-9.4 9.4-24.6 9.4-33.9 0L160 351.9l-96.4 96.4c-9.4 9.4-24.6 9.4-33.9 0L7 425.7c-9.4-9.4-9.4-24.6 0-33.9l136-136c9.4-9.5 24.6-9.5 34-.1zm-34-192L7 199.7c-9.4 9.4-9.4 24.6 0 33.9l22.6 22.6c9.4 9.4 24.6 9.4 33.9 0l96.4-96.4 96.4 96.4c9.4 9.4 24.6 9.4 33.9 0l22.6-22.6c9.4-9.4 9.4-24.6 0-33.9l-136-136c-9.2-9.4-24.4-9.4-33.8 0z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-down\" viewBox=\"0 0 320 512\">\n        <path d=\"M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-left\" viewBox=\"0 0 256 512\">\n        <path d=\"M31.7 239l136-136c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9L127.9 256l96.4 96.4c9.4 9.4 9.4 24.6 0 33.9L201.7 409c-9.4 9.4-24.6 9.4-33.9 0l-136-136c-9.5-9.4-9.5-24.6-.1-34z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-right\" viewBox=\"0 0 256 512\">\n        <path d=\"M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z\"></path>\n    </symbol>\n    <symbol id=\"icon-angle-up\" viewBox=\"0 0 320 512\">\n        <path d=\"M177 159.7l136 136c9.4 9.4 9.4 24.6 0 33.9l-22.6 22.6c-9.4 9.4-24.6 9.4-33.9 0L160 255.9l-96.4 96.4c-9.4 9.4-24.6 9.4-33.9 0L7 329.7c-9.4-9.4-9.4-24.6 0-33.9l136-136c9.4-9.5 24.6-9.5 34-.1z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-alt-circle-down\" viewBox=\"0 0 512 512\">\n        <path d=\"M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-alt-circle-left\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 504C119 504 8 393 8 256S119 8 256 8s248 111 248 248-111 248-248 248zm116-292H256v-70.9c0-10.7-13-16.1-20.5-8.5L121.2 247.5c-4.7 4.7-4.7 12.2 0 16.9l114.3 114.9c7.6 7.6 20.5 2.2 20.5-8.5V300h116c6.6 0 12-5.4 12-12v-64c0-6.6-5.4-12-12-12z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-alt-circle-right\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8c137 0 248 111 248 248S393 504 256 504 8 393 8 256 119 8 256 8zM140 300h116v70.9c0 10.7 13 16.1 20.5 8.5l114.3-114.9c4.7-4.7 4.7-12.2 0-16.9l-114.3-115c-7.6-7.6-20.5-2.2-20.5 8.5V212H140c-6.6 0-12 5.4-12 12v64c0 6.6 5.4 12 12 12z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-alt-circle-up\" viewBox=\"0 0 512 512\">\n        <path d=\"M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm292 116V256h70.9c10.7 0 16.1-13 8.5-20.5L264.5 121.2c-4.7-4.7-12.2-4.7-16.9 0l-115 114.3c-7.6 7.6-2.2 20.5 8.5 20.5H212v116c0 6.6 5.4 12 12 12h64c6.6 0 12-5.4 12-12z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-circle-down\" viewBox=\"0 0 512 512\">\n        <path d=\"M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zm-143.6-28.9L288 302.6V120c0-13.3-10.7-24-24-24h-16c-13.3 0-24 10.7-24 24v182.6l-72.4-75.5c-9.3-9.7-24.8-9.9-34.3-.4l-10.9 11c-9.4 9.4-9.4 24.6 0 33.9L239 404.3c9.4 9.4 24.6 9.4 33.9 0l132.7-132.7c9.4-9.4 9.4-24.6 0-33.9l-10.9-11c-9.5-9.5-25-9.3-34.3.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-circle-left\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 504C119 504 8 393 8 256S119 8 256 8s248 111 248 248-111 248-248 248zm28.9-143.6L209.4 288H392c13.3 0 24-10.7 24-24v-16c0-13.3-10.7-24-24-24H209.4l75.5-72.4c9.7-9.3 9.9-24.8.4-34.3l-11-10.9c-9.4-9.4-24.6-9.4-33.9 0L107.7 239c-9.4 9.4-9.4 24.6 0 33.9l132.7 132.7c9.4 9.4 24.6 9.4 33.9 0l11-10.9c9.5-9.5 9.3-25-.4-34.3z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-circle-right\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8c137 0 248 111 248 248S393 504 256 504 8 393 8 256 119 8 256 8zm-28.9 143.6l75.5 72.4H120c-13.3 0-24 10.7-24 24v16c0 13.3 10.7 24 24 24h182.6l-75.5 72.4c-9.7 9.3-9.9 24.8-.4 34.3l11 10.9c9.4 9.4 24.6 9.4 33.9 0L404.3 273c9.4-9.4 9.4-24.6 0-33.9L271.6 106.3c-9.4-9.4-24.6-9.4-33.9 0l-11 10.9c-9.5 9.6-9.3 25.1.4 34.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-circle-up\" viewBox=\"0 0 512 512\">\n        <path d=\"M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm143.6 28.9l72.4-75.5V392c0 13.3 10.7 24 24 24h16c13.3 0 24-10.7 24-24V209.4l72.4 75.5c9.3 9.7 24.8 9.9 34.3.4l10.9-11c9.4-9.4 9.4-24.6 0-33.9L273 107.7c-9.4-9.4-24.6-9.4-33.9 0L106.3 240.4c-9.4 9.4-9.4 24.6 0 33.9l10.9 11c9.6 9.5 25.1 9.3 34.4-.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-down\" viewBox=\"0 0 448 512\">\n        <path d=\"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-left\" viewBox=\"0 0 448 512\">\n        <path d=\"M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-right\" viewBox=\"0 0 448 512\">\n        <path d=\"M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrow-up\" viewBox=\"0 0 448 512\">\n        <path d=\"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrows-alt\" viewBox=\"0 0 512 512\">\n        <path d=\"M352.201 425.775l-79.196 79.196c-9.373 9.373-24.568 9.373-33.941 0l-79.196-79.196c-15.119-15.119-4.411-40.971 16.971-40.97h51.162L228 284H127.196v51.162c0 21.382-25.851 32.09-40.971 16.971L7.029 272.937c-9.373-9.373-9.373-24.569 0-33.941L86.225 159.8c15.119-15.119 40.971-4.411 40.971 16.971V228H228V127.196h-51.23c-21.382 0-32.09-25.851-16.971-40.971l79.196-79.196c9.373-9.373 24.568-9.373 33.941 0l79.196 79.196c15.119 15.119 4.411 40.971-16.971 40.971h-51.162V228h100.804v-51.162c0-21.382 25.851-32.09 40.97-16.971l79.196 79.196c9.373 9.373 9.373 24.569 0 33.941L425.773 352.2c-15.119 15.119-40.971 4.411-40.97-16.971V284H284v100.804h51.23c21.382 0 32.09 25.851 16.971 40.971z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrows-alt-h\" viewBox=\"0 0 512 512\">\n        <path d=\"M377.941 169.941V216H134.059v-46.059c0-21.382-25.851-32.09-40.971-16.971L7.029 239.029c-9.373 9.373-9.373 24.568 0 33.941l86.059 86.059c15.119 15.119 40.971 4.411 40.971-16.971V296h243.882v46.059c0 21.382 25.851 32.09 40.971 16.971l86.059-86.059c9.373-9.373 9.373-24.568 0-33.941l-86.059-86.059c-15.119-15.12-40.971-4.412-40.971 16.97z\"></path>\n    </symbol>\n    <symbol id=\"icon-arrows-alt-v\" viewBox=\"0 0 256 512\">\n        <path d=\"M214.059 377.941H168V134.059h46.059c21.382 0 32.09-25.851 16.971-40.971L144.971 7.029c-9.373-9.373-24.568-9.373-33.941 0L24.971 93.088c-15.119 15.119-4.411 40.971 16.971 40.971H88v243.882H41.941c-21.382 0-32.09 25.851-16.971 40.971l86.059 86.059c9.373 9.373 24.568 9.373 33.941 0l86.059-86.059c15.12-15.119 4.412-40.971-16.97-40.971z\"></path>\n    </symbol>\n    <symbol id=\"icon-bars\" viewBox=\"0 0 448 512\">\n        <path d=\"M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z\"></path>\n    </symbol>\n    <symbol id=\"icon-bookmark\" viewBox=\"0 0 384 512\">\n        <path d=\"M0 512V48C0 21.49 21.49 0 48 0h288c26.51 0 48 21.49 48 48v464L192 400 0 512z\"></path>\n    </symbol>\n    <symbol id=\"icon-bookmark-empty\" viewBox=\"0 0 384 512\">\n        <path d=\"M0 48C0 21.5 21.5 0 48 0l0 48V441.4l130.1-92.9c8.3-6 19.6-6 27.9 0L336 441.4V48H48V0H336c26.5 0 48 21.5 48 48V488c0 9-5 17.2-13 21.3s-17.6 3.4-24.9-1.8L192 397.5 37.9 507.5c-7.3 5.2-16.9 5.9-24.9 1.8S0 497 0 488V48z\"/>\n    </symbol>\n    <symbol id=\"icon-caret-down\" viewBox=\"0 0 320 512\">\n        <path d=\"M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z\"></path>\n    </symbol>\n    <symbol id=\"icon-caret-right\" viewBox=\"0 0 192 512\">\n        <path d=\"M0 384.662V127.338c0-17.818 21.543-26.741 34.142-14.142l128.662 128.662c7.81 7.81 7.81 20.474 0 28.284L34.142 398.804C21.543 411.404 0 402.48 0 384.662z\"></path>\n    </symbol>\n    <symbol id=\"icon-check\" viewBox=\"0 0 512 512\">\n        <path d=\"M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z\"></path>\n    </symbol>\n    <symbol id=\"icon-circle\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z\"></path>\n    </symbol>\n    <symbol id=\"icon-cog\" viewBox=\"0 0 512 512\">\n        <path d=\"M487.4 315.7l-42.6-24.6c4.3-23.2 4.3-47 0-70.2l42.6-24.6c4.9-2.8 7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8 110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4 6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7 85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7 94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47 0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6 30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9 15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7 8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9 42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7 43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z\"></path>\n    </symbol>\n    <symbol id=\"icon-database\" viewBox=\"0 0 448 512\">\n        <path d=\"M448 73.143v45.714C448 159.143 347.667 192 224 192S0 159.143 0 118.857V73.143C0 32.857 100.333 0 224 0s224 32.857 224 73.143zM448 176v102.857C448 319.143 347.667 352 224 352S0 319.143 0 278.857V176c48.125 33.143 136.208 48.572 224 48.572S399.874 209.143 448 176zm0 160v102.857C448 479.143 347.667 512 224 512S0 479.143 0 438.857V336c48.125 33.143 136.208 48.572 224 48.572S399.874 369.143 448 336z\"></path>\n    </symbol>\n    <symbol id=\"icon-edit\" viewBox=\"0 0 576 512\">\n        <path d=\"M402.6 83.2l90.2 90.2c3.8 3.8 3.8 10 0 13.8L274.4 405.6l-92.8 10.3c-12.4 1.4-22.9-9.1-21.5-21.5l10.3-92.8L388.8 83.2c3.8-3.8 10-3.8 13.8 0zm162-22.9l-48.8-48.8c-15.2-15.2-39.9-15.2-55.2 0l-35.4 35.4c-3.8 3.8-3.8 10 0 13.8l90.2 90.2c3.8 3.8 10 3.8 13.8 0l35.4-35.4c15.2-15.3 15.2-40 0-55.2zM384 346.2V448H64V128h229.8c3.2 0 6.2-1.3 8.5-3.5l40-40c7.6-7.6 2.2-20.5-8.5-20.5H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V306.2c0-10.7-12.9-16-20.5-8.5l-40 40c-2.2 2.3-3.5 5.3-3.5 8.5z\"></path>\n    </symbol>\n    <symbol id=\"icon-eye\" viewBox=\"0 0 576 512\">\n        <path d=\"M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z\"></path>\n    </symbol>\n    <symbol id=\"icon-eye-slash\" viewBox=\"0 0 640 512\">\n        <path d=\"M320 400c-75.85 0-137.25-58.71-142.9-133.11L72.2 185.82c-13.79 17.3-26.48 35.59-36.72 55.59a32.35 32.35 0 0 0 0 29.19C89.71 376.41 197.07 448 320 448c26.91 0 52.87-4 77.89-10.46L346 397.39a144.13 144.13 0 0 1-26 2.61zm313.82 58.1l-110.55-85.44a331.25 331.25 0 0 0 81.25-102.07 32.35 32.35 0 0 0 0-29.19C550.29 135.59 442.93 64 320 64a308.15 308.15 0 0 0-147.32 37.7L45.46 3.37A16 16 0 0 0 23 6.18L3.37 31.45A16 16 0 0 0 6.18 53.9l588.36 454.73a16 16 0 0 0 22.46-2.81l19.64-25.27a16 16 0 0 0-2.82-22.45zm-183.72-142l-39.3-30.38A94.75 94.75 0 0 0 416 256a94.76 94.76 0 0 0-121.31-92.21A47.65 47.65 0 0 1 304 192a46.64 46.64 0 0 1-1.54 10l-73.61-56.89A142.31 142.31 0 0 1 320 112a143.92 143.92 0 0 1 144 144c0 21.63-5.29 41.79-13.9 60.11z\"></path>\n    </symbol>\n    <symbol id=\"icon-gavel\" viewBox=\"0 0 512 512\">\n        <path d=\"M504.971 199.362l-22.627-22.627c-9.373-9.373-24.569-9.373-33.941 0l-5.657 5.657L329.608 69.255l5.657-5.657c9.373-9.373 9.373-24.569 0-33.941L312.638 7.029c-9.373-9.373-24.569-9.373-33.941 0L154.246 131.48c-9.373 9.373-9.373 24.569 0 33.941l22.627 22.627c9.373 9.373 24.569 9.373 33.941 0l5.657-5.657 39.598 39.598-81.04 81.04-5.657-5.657c-12.497-12.497-32.758-12.497-45.255 0L9.373 412.118c-12.497 12.497-12.497 32.758 0 45.255l45.255 45.255c12.497 12.497 32.758 12.497 45.255 0l114.745-114.745c12.497-12.497 12.497-32.758 0-45.255l-5.657-5.657 81.04-81.04 39.598 39.598-5.657 5.657c-9.373 9.373-9.373 24.569 0 33.941l22.627 22.627c9.373 9.373 24.569 9.373 33.941 0l124.451-124.451c9.372-9.372 9.372-24.568 0-33.941z\"></path>\n    </symbol>\n    <symbol id=\"icon-globe\" viewBox=\"0 0 496 512\">\n        <path d=\"M336.5 160C322 70.7 287.8 8 248 8s-74 62.7-88.5 152h177zM152 256c0 22.2 1.2 43.5 3.3 64h185.3c2.1-20.5 3.3-41.8 3.3-64s-1.2-43.5-3.3-64H155.3c-2.1 20.5-3.3 41.8-3.3 64zm324.7-96c-28.6-67.9-86.5-120.4-158-141.6 24.4 33.8 41.2 84.7 50 141.6h108zM177.2 18.4C105.8 39.6 47.8 92.1 19.3 160h108c8.7-56.9 25.5-107.8 49.9-141.6zM487.4 192H372.7c2.1 21 3.3 42.5 3.3 64s-1.2 43-3.3 64h114.6c5.5-20.5 8.6-41.8 8.6-64s-3.1-43.5-8.5-64zM120 256c0-21.5 1.2-43 3.3-64H8.6C3.2 212.5 0 233.8 0 256s3.2 43.5 8.6 64h114.6c-2-21-3.2-42.5-3.2-64zm39.5 96c14.5 89.3 48.7 152 88.5 152s74-62.7 88.5-152h-177zm159.3 141.6c71.4-21.2 129.4-73.7 158-141.6h-108c-8.8 56.9-25.6 107.8-50 141.6zM19.3 352c28.6 67.9 86.5 120.4 158 141.6-24.4-33.8-41.2-84.7-50-141.6h-108z\"></path>\n    </symbol>\n    <symbol id=\"icon-id-card\" viewBox=\"0 0 576 512\">\n        <path d=\"M528 32H48C21.5 32 0 53.5 0 80v16h576V80c0-26.5-21.5-48-48-48zM0 432c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V128H0v304zm352-232c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16c0 4.4-3.6 8-8 8H360c-4.4 0-8-3.6-8-8v-16zm0 64c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16c0 4.4-3.6 8-8 8H360c-4.4 0-8-3.6-8-8v-16zm0 64c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16c0 4.4-3.6 8-8 8H360c-4.4 0-8-3.6-8-8v-16zM176 192c35.3 0 64 28.7 64 64s-28.7 64-64 64-64-28.7-64-64 28.7-64 64-64zM67.1 396.2C75.5 370.5 99.6 352 128 352h8.2c12.3 5.1 25.7 8 39.8 8s27.6-2.9 39.8-8h8.2c28.4 0 52.5 18.5 60.9 44.2 3.2 9.9-5.2 19.8-15.6 19.8H82.7c-10.4 0-18.8-10-15.6-19.8z\"></path>\n    </symbol>\n    <symbol id=\"icon-id-card-alt\" viewBox=\"0 0 576 512\">\n        <path d=\"M528 64H384v96H192V64H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V112c0-26.5-21.5-48-48-48zM288 224c35.3 0 64 28.7 64 64s-28.7 64-64 64-64-28.7-64-64 28.7-64 64-64zm93.3 224H194.7c-10.4 0-18.8-10-15.6-19.8 8.3-25.6 32.4-44.2 60.9-44.2h8.2c12.3 5.1 25.7 8 39.8 8s27.6-2.9 39.8-8h8.2c28.4 0 52.5 18.5 60.9 44.2 3.2 9.8-5.2 19.8-15.6 19.8zM352 32c0-17.7-14.3-32-32-32h-64c-17.7 0-32 14.3-32 32v96h128V32z\"></path>\n    </symbol>\n    <symbol id=\"icon-info\" viewBox=\"0 0 192 512\">\n        <path d=\"M20 424.229h20V279.771H20c-11.046 0-20-8.954-20-20V212c0-11.046 8.954-20 20-20h112c11.046 0 20 8.954 20 20v212.229h20c11.046 0 20 8.954 20 20V492c0 11.046-8.954 20-20 20H20c-11.046 0-20-8.954-20-20v-47.771c0-11.046 8.954-20 20-20zM96 0C56.235 0 24 32.235 24 72s32.235 72 72 72 72-32.235 72-72S135.764 0 96 0z\"></path>\n    </symbol>\n    <symbol id=\"icon-info-circle\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z\"></path>\n    </symbol>\n    <symbol id=\"icon-list-ul\" viewBox=\"0 0 512 512\">\n        <path d=\"M48 48a48 48 0 1 0 48 48 48 48 0 0 0-48-48zm0 160a48 48 0 1 0 48 48 48 48 0 0 0-48-48zm0 160a48 48 0 1 0 48 48 48 48 0 0 0-48-48zm448 16H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm0-320H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16zm0 160H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16z\"></path>\n    </symbol>\n    <symbol id=\"icon-lock\" viewBox=\"0 0 448 512\">\n        <path d=\"M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z\"></path>\n    </symbol>\n    <symbol id=\"icon-lock-open\" viewBox=\"0 0 576 512\">\n        <path d=\"M423.5 0C339.5.3 272 69.5 272 153.5V224H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48h-48v-71.1c0-39.6 31.7-72.5 71.3-72.9 40-.4 72.7 32.1 72.7 72v80c0 13.3 10.7 24 24 24h32c13.3 0 24-10.7 24-24v-80C576 68 507.5-.3 423.5 0z\"></path>\n    </symbol>\n    <symbol id=\"icon-minus\" viewBox=\"0 0 448 512\">\n        <path d=\"M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z\"></path>\n    </symbol>\n    <symbol id=\"icon-minus-circle\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zM124 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H124z\"></path>\n    </symbol>\n    <symbol id=\"icon-minus-square\" viewBox=\"0 0 448 512\">\n        <path d=\"M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z\"></path>\n    </symbol>\n    <symbol id=\"icon-paper-plane\" viewBox=\"0 0 512 512\">\n        <path d=\"M476 3.2L12.5 270.6c-18.1 10.4-15.8 35.6 2.2 43.2L121 358.4l287.3-253.2c5.5-4.9 13.3 2.6 8.6 8.3L176 407v80.5c0 23.6 28.5 32.9 42.5 15.8L282 426l124.6 52.2c14.2 6 30.4-2.9 33-18.2l72-432C515 7.8 493.3-6.8 476 3.2z\"></path>\n    </symbol>\n    <symbol id=\"icon-paperclip\" viewBox=\"0 0 448 512\">\n        <path d=\"M43.246 466.142c-58.43-60.289-57.341-157.511 1.386-217.581L254.392 34c44.316-45.332 116.351-45.336 160.671 0 43.89 44.894 43.943 117.329 0 162.276L232.214 383.128c-29.855 30.537-78.633 30.111-107.982-.998-28.275-29.97-27.368-77.473 1.452-106.953l143.743-146.835c6.182-6.314 16.312-6.422 22.626-.241l22.861 22.379c6.315 6.182 6.422 16.312.241 22.626L171.427 319.927c-4.932 5.045-5.236 13.428-.648 18.292 4.372 4.634 11.245 4.711 15.688.165l182.849-186.851c19.613-20.062 19.613-52.725-.011-72.798-19.189-19.627-49.957-19.637-69.154 0L90.39 293.295c-34.763 35.56-35.299 93.12-1.191 128.313 34.01 35.093 88.985 35.137 123.058.286l172.06-175.999c6.177-6.319 16.307-6.433 22.626-.256l22.877 22.364c6.319 6.177 6.434 16.307.256 22.626l-172.06 175.998c-59.576 60.938-155.943 60.216-214.77-.485z\"></path>\n    </symbol>\n    <symbol id=\"icon-pencil-alt\" viewBox=\"0 0 512 512\">\n        <path d=\"M497.9 142.1l-46.1 46.1c-4.7 4.7-12.3 4.7-17 0l-111-111c-4.7-4.7-4.7-12.3 0-17l46.1-46.1c18.7-18.7 49.1-18.7 67.9 0l60.1 60.1c18.8 18.7 18.8 49.1 0 67.9zM284.2 99.8L21.6 362.4.4 483.9c-2.9 16.4 11.4 30.6 27.8 27.8l121.5-21.3 262.6-262.6c4.7-4.7 4.7-12.3 0-17l-111-111c-4.8-4.7-12.4-4.7-17.1 0zM124.1 339.9c-5.5-5.5-5.5-14.3 0-19.8l154-154c5.5-5.5 14.3-5.5 19.8 0s5.5 14.3 0 19.8l-154 154c-5.5 5.5-14.3 5.5-19.8 0zM88 424h48v36.3l-64.5 11.3-31.1-31.1L51.7 376H88v48z\"></path>\n    </symbol>\n    <symbol id=\"icon-phone\" viewBox=\"0 0 512 512\">\n        <path d=\"M493.4 24.6l-104-24c-11.3-2.6-22.9 3.3-27.5 13.9l-48 112c-4.2 9.8-1.4 21.3 6.9 28l60.6 49.6c-36 76.7-98.9 140.5-177.2 177.2l-49.6-60.6c-6.8-8.3-18.2-11.1-28-6.9l-112 48C3.9 366.5-2 378.1.6 389.4l24 104C27.1 504.2 36.7 512 48 512c256.1 0 464-207.5 464-464 0-11.2-7.7-20.9-18.6-23.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-plus\" viewBox=\"0 0 448 512\">\n        <path d=\"M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z\"></path>\n    </symbol>\n    <symbol id=\"icon-plus-circle\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z\"></path>\n    </symbol>\n    <symbol id=\"icon-plus-square\" viewBox=\"0 0 448 512\">\n        <path d=\"M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-32 252c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92H92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z\"></path>\n    </symbol>\n    <symbol id=\"icon-save\" viewBox=\"0 0 448 512\">\n        <path d=\"M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z\"></path>\n    </symbol>\n    <symbol id=\"icon-sign-out-alt\" viewBox=\"0 0 512 512\">\n        <path d=\"M497 273L329 441c-15 15-41 4.5-41-17v-96H152c-13.3 0-24-10.7-24-24v-96c0-13.3 10.7-24 24-24h136V88c0-21.4 25.9-32 41-17l168 168c9.3 9.4 9.3 24.6 0 34zM192 436v-40c0-6.6-5.4-12-12-12H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h84c6.6 0 12-5.4 12-12V76c0-6.6-5.4-12-12-12H96c-53 0-96 43-96 96v192c0 53 43 96 96 96h84c6.6 0 12-5.4 12-12z\"></path>\n    </symbol>\n    <symbol id=\"icon-smile\" viewBox=\"0 0 496 512\">\n        <path d=\"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm80 168c17.7 0 32 14.3 32 32s-14.3 32-32 32-32-14.3-32-32 14.3-32 32-32zm-160 0c17.7 0 32 14.3 32 32s-14.3 32-32 32-32-14.3-32-32 14.3-32 32-32zm194.8 170.2C334.3 380.4 292.5 400 248 400s-86.3-19.6-114.8-53.8c-13.6-16.3 11-36.7 24.6-20.5 22.4 26.9 55.2 42.2 90.2 42.2s67.8-15.4 90.2-42.2c13.4-16.2 38.1 4.2 24.6 20.5z\"></path>\n    </symbol>\n    <symbol id=\"icon-snowflake\" viewBox=\"0 0 448 512\">\n        <path d=\"M440.3 345.2l-33.8-19.5 26-7c8.2-2.2 13.1-10.7 10.9-18.9l-4-14.9c-2.2-8.2-10.7-13.1-18.9-10.9l-70.8 19-63.9-37 63.8-36.9 70.8 19c8.2 2.2 16.7-2.7 18.9-10.9l4-14.9c2.2-8.2-2.7-16.7-10.9-18.9l-26-7 33.8-19.5c7.4-4.3 9.9-13.7 5.7-21.1L430.4 119c-4.3-7.4-13.7-9.9-21.1-5.7l-33.8 19.5 7-26c2.2-8.2-2.7-16.7-10.9-18.9l-14.9-4c-8.2-2.2-16.7 2.7-18.9 10.9l-19 70.8-62.8 36.2v-77.5l53.7-53.7c6.2-6.2 6.2-16.4 0-22.6l-11.3-11.3c-6.2-6.2-16.4-6.2-22.6 0L256 56.4V16c0-8.8-7.2-16-16-16h-32c-8.8 0-16 7.2-16 16v40.4l-19.7-19.7c-6.2-6.2-16.4-6.2-22.6 0L138.3 48c-6.3 6.2-6.3 16.4 0 22.6l53.7 53.7v77.5l-62.8-36.2-19-70.8c-2.2-8.2-10.7-13.1-18.9-10.9l-14.9 4c-8.2 2.2-13.1 10.7-10.9 18.9l7 26-33.8-19.5c-7.4-4.3-16.8-1.7-21.1 5.7L2.1 145.7c-4.3 7.4-1.7 16.8 5.7 21.1l33.8 19.5-26 7c-8.3 2.2-13.2 10.7-11 19l4 14.9c2.2 8.2 10.7 13.1 18.9 10.9l70.8-19 63.8 36.9-63.8 36.9-70.8-19c-8.2-2.2-16.7 2.7-18.9 10.9l-4 14.9c-2.2 8.2 2.7 16.7 10.9 18.9l26 7-33.8 19.6c-7.4 4.3-9.9 13.7-5.7 21.1l15.5 26.8c4.3 7.4 13.7 9.9 21.1 5.7l33.8-19.5-7 26c-2.2 8.2 2.7 16.7 10.9 18.9l14.9 4c8.2 2.2 16.7-2.7 18.9-10.9l19-70.8 62.8-36.2v77.5l-53.7 53.7c-6.3 6.2-6.3 16.4 0 22.6l11.3 11.3c6.2 6.2 16.4 6.2 22.6 0l19.7-19.7V496c0 8.8 7.2 16 16 16h32c8.8 0 16-7.2 16-16v-40.4l19.7 19.7c6.2 6.2 16.4 6.2 22.6 0l11.3-11.3c6.2-6.2 6.2-16.4 0-22.6L256 387.7v-77.5l62.8 36.2 19 70.8c2.2 8.2 10.7 13.1 18.9 10.9l14.9-4c8.2-2.2 13.1-10.7 10.9-18.9l-7-26 33.8 19.5c7.4 4.3 16.8 1.7 21.1-5.7l15.5-26.8c4.3-7.3 1.8-16.8-5.6-21z\"></path>\n    </symbol>\n    <symbol id=\"icon-spinner\" viewBox=\"0 0 512 512\">\n        <path d=\"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z\"></path>\n    </symbol>\n    <symbol id=\"icon-sync\" viewBox=\"0 0 512 512\">\n        <path d=\"M440.65 12.57l4 82.77A247.16 247.16 0 0 0 255.83 8C134.73 8 33.91 94.92 12.29 209.82A12 12 0 0 0 24.09 224h49.05a12 12 0 0 0 11.67-9.26 175.91 175.91 0 0 1 317-56.94l-101.46-4.86a12 12 0 0 0-12.57 12v47.41a12 12 0 0 0 12 12H500a12 12 0 0 0 12-12V12a12 12 0 0 0-12-12h-47.37a12 12 0 0 0-11.98 12.57zM255.83 432a175.61 175.61 0 0 1-146-77.8l101.8 4.87a12 12 0 0 0 12.57-12v-47.4a12 12 0 0 0-12-12H12a12 12 0 0 0-12 12V500a12 12 0 0 0 12 12h47.35a12 12 0 0 0 12-12.6l-4.15-82.57A247.17 247.17 0 0 0 255.83 504c121.11 0 221.93-86.92 243.55-201.82a12 12 0 0 0-11.8-14.18h-49.05a12 12 0 0 0-11.67 9.26A175.86 175.86 0 0 1 255.83 432z\"></path>\n    </symbol>\n    <symbol id=\"icon-times\" viewBox=\"0 0 352 512\">\n        <path d=\"M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z\"></path>\n    </symbol>\n    <symbol id=\"icon-times-circle\" viewBox=\"0 0 512 512\">\n        <path d=\"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z\"></path>\n    </symbol>\n    <symbol id=\"icon-trash\" viewBox=\"0 0 448 512\">\n        <path d=\"M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z\"></path>\n    </symbol>\n    <symbol id=\"icon-trash-alt\" viewBox=\"0 0 448 512\">\n        <path d=\"M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z\"></path>\n    </symbol>\n    <symbol id=\"icon-unlock\" viewBox=\"0 0 448 512\">\n        <path d=\"M400 256H152V152.9c0-39.6 31.7-72.5 71.3-72.9 40-.4 72.7 32.1 72.7 72v16c0 13.3 10.7 24 24 24h32c13.3 0 24-10.7 24-24v-16C376 68 307.5-.3 223.5 0 139.5.3 72 69.5 72 153.5V256H48c-26.5 0-48 21.5-48 48v160c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V304c0-26.5-21.5-48-48-48z\"></path>\n    </symbol>\n    <symbol id=\"icon-user\" viewBox=\"0 0 448 512\">\n        <path d=\"M224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm89.6 32h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-user-cog\" viewBox=\"0 0 640 512\">\n        <path d=\"M610.5 373.3c2.6-14.1 2.6-28.5 0-42.6l25.8-14.9c3-1.7 4.3-5.2 3.3-8.5-6.7-21.6-18.2-41.2-33.2-57.4-2.3-2.5-6-3.1-9-1.4l-25.8 14.9c-10.9-9.3-23.4-16.5-36.9-21.3v-29.8c0-3.4-2.4-6.4-5.7-7.1-22.3-5-45-4.8-66.2 0-3.3.7-5.7 3.7-5.7 7.1v29.8c-13.5 4.8-26 12-36.9 21.3l-25.8-14.9c-2.9-1.7-6.7-1.1-9 1.4-15 16.2-26.5 35.8-33.2 57.4-1 3.3.4 6.8 3.3 8.5l25.8 14.9c-2.6 14.1-2.6 28.5 0 42.6l-25.8 14.9c-3 1.7-4.3 5.2-3.3 8.5 6.7 21.6 18.2 41.1 33.2 57.4 2.3 2.5 6 3.1 9 1.4l25.8-14.9c10.9 9.3 23.4 16.5 36.9 21.3v29.8c0 3.4 2.4 6.4 5.7 7.1 22.3 5 45 4.8 66.2 0 3.3-.7 5.7-3.7 5.7-7.1v-29.8c13.5-4.8 26-12 36.9-21.3l25.8 14.9c2.9 1.7 6.7 1.1 9-1.4 15-16.2 26.5-35.8 33.2-57.4 1-3.3-.4-6.8-3.3-8.5l-25.8-14.9zM496 400.5c-26.8 0-48.5-21.8-48.5-48.5s21.8-48.5 48.5-48.5 48.5 21.8 48.5 48.5-21.7 48.5-48.5 48.5zM224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm201.2 226.5c-2.3-1.2-4.6-2.6-6.8-3.9l-7.9 4.6c-6 3.4-12.8 5.3-19.6 5.3-10.9 0-21.4-4.6-28.9-12.6-18.3-19.8-32.3-43.9-40.2-69.6-5.5-17.7 1.9-36.4 17.9-45.7l7.9-4.6c-.1-2.6-.1-5.2 0-7.8l-7.9-4.6c-16-9.2-23.4-28-17.9-45.7.9-2.9 2.2-5.8 3.2-8.7-3.8-.3-7.5-1.2-11.4-1.2h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c10.1 0 19.5-3.2 27.2-8.5-1.2-3.8-2-7.7-2-11.8v-9.2z\"></path>\n    </symbol>\n    <symbol id=\"icon-user-plus\" viewBox=\"0 0 640 512\">\n        <path d=\"M624 208h-64v-64c0-8.8-7.2-16-16-16h-32c-8.8 0-16 7.2-16 16v64h-64c-8.8 0-16 7.2-16 16v32c0 8.8 7.2 16 16 16h64v64c0 8.8 7.2 16 16 16h32c8.8 0 16-7.2 16-16v-64h64c8.8 0 16-7.2 16-16v-32c0-8.8-7.2-16-16-16zm-400 48c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm89.6 32h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-user-secret\" viewBox=\"0 0 448 512\">\n        <path d=\"M383.9 308.3l23.9-62.6c4-10.5-3.7-21.7-15-21.7h-58.5c11-18.9 17.8-40.6 17.8-64v-.3c39.2-7.8 64-19.1 64-31.7 0-13.3-27.3-25.1-70.1-33-9.2-32.8-27-65.8-40.6-82.8-9.5-11.9-25.9-15.6-39.5-8.8l-27.6 13.8c-9 4.5-19.6 4.5-28.6 0L182.1 3.4c-13.6-6.8-30-3.1-39.5 8.8-13.5 17-31.4 50-40.6 82.8-42.7 7.9-70 19.7-70 33 0 12.6 24.8 23.9 64 31.7v.3c0 23.4 6.8 45.1 17.8 64H56.3c-11.5 0-19.2 11.7-14.7 22.3l25.8 60.2C27.3 329.8 0 372.7 0 422.4v44.8C0 491.9 20.1 512 44.8 512h358.4c24.7 0 44.8-20.1 44.8-44.8v-44.8c0-48.4-25.8-90.4-64.1-114.1zM176 480l-41.6-192 49.6 32 24 40-32 120zm96 0l-32-120 24-40 49.6-32L272 480zm41.7-298.5c-3.9 11.9-7 24.6-16.5 33.4-10.1 9.3-48 22.4-64-25-2.8-8.4-15.4-8.4-18.3 0-17 50.2-56 32.4-64 25-9.5-8.8-12.7-21.5-16.5-33.4-.8-2.5-6.3-5.7-6.3-5.8v-10.8c28.3 3.6 61 5.8 96 5.8s67.7-2.1 96-5.8v10.8c-.1.1-5.6 3.2-6.4 5.8z\"></path>\n    </symbol>\n    <symbol id=\"icon-users\" viewBox=\"0 0 640 512\">\n        <path d=\"M96 224c35.3 0 64-28.7 64-64s-28.7-64-64-64-64 28.7-64 64 28.7 64 64 64zm448 0c35.3 0 64-28.7 64-64s-28.7-64-64-64-64 28.7-64 64 28.7 64 64 64zm32 32h-64c-17.6 0-33.5 7.1-45.1 18.6 40.3 22.1 68.9 62 75.1 109.4h66c17.7 0 32-14.3 32-32v-32c0-35.3-28.7-64-64-64zm-256 0c61.9 0 112-50.1 112-112S381.9 32 320 32 208 82.1 208 144s50.1 112 112 112zm76.8 32h-8.3c-20.8 10-43.9 16-68.5 16s-47.6-6-68.5-16h-8.3C179.6 288 128 339.6 128 403.2V432c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48v-28.8c0-63.6-51.6-115.2-115.2-115.2zm-223.7-13.4C161.5 263.1 145.6 256 128 256H64c-35.3 0-64 28.7-64 64v32c0 17.7 14.3 32 32 32h65.9c6.3-47.4 34.9-87.3 75.2-109.4z\"></path>\n    </symbol>\n    <symbol id=\"icon-wrench\" viewBox=\"0 0 512 512\">\n        <path d=\"M507.73 109.1c-2.24-9.03-13.54-12.09-20.12-5.51l-74.36 74.36-67.88-11.31-11.31-67.88 74.36-74.36c6.62-6.62 3.43-17.9-5.66-20.16-47.38-11.74-99.55.91-136.58 37.93-39.64 39.64-50.55 97.1-34.05 147.2L18.74 402.76c-24.99 24.99-24.99 65.51 0 90.5 24.99 24.99 65.51 24.99 90.5 0l213.21-213.21c50.12 16.71 107.47 5.68 147.37-34.22 37.07-37.07 49.7-89.32 37.91-136.73zM64 472c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24z\"></path>\n    </symbol>\n    <symbol id=\"icon-refresh\" viewBox=\"0 0 512 512\">\n        <path d=\"M464 16c-17.67 0-32 14.31-32 32v74.09C392.1 66.52 327.4 32 256 32C161.5 32 78.59 92.34 49.58 182.2c-5.438 16.81 3.797 34.88 20.61 40.28c16.89 5.5 34.88-3.812 40.3-20.59C130.9 138.5 189.4 96 256 96c50.5 0 96.26 24.55 124.4 64H336c-17.67 0-32 14.31-32 32s14.33 32 32 32h128c17.67 0 32-14.31 32-32V48C496 30.31 481.7 16 464 16zM441.8 289.6c-16.92-5.438-34.88 3.812-40.3 20.59C381.1 373.5 322.6 416 256 416c-50.5 0-96.25-24.55-124.4-64H176c17.67 0 32-14.31 32-32s-14.33-32-32-32h-128c-17.67 0-32 14.31-32 32v144c0 17.69 14.33 32 32 32s32-14.31 32-32v-74.09C119.9 445.5 184.6 480 255.1 480c94.45 0 177.4-60.34 206.4-150.2C467.9 313 458.6 294.1 441.8 289.6z\"></path>\n    </symbol>\n    </svg>\n"])));
});
;// CONCATENATED MODULE: ./src/shared/components/font-awesome.js
function font_awesome_typeof(obj) {
  "@babel/helpers - typeof";

  return font_awesome_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;
  }, font_awesome_typeof(obj);
}
function font_awesome_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function font_awesome_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, font_awesome_toPropertyKey(descriptor.key), descriptor);
  }
}
function font_awesome_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) font_awesome_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) font_awesome_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function font_awesome_toPropertyKey(arg) {
  var key = font_awesome_toPrimitive(arg, "string");
  return font_awesome_typeof(key) === "symbol" ? key : String(key);
}
function font_awesome_toPrimitive(input, hint) {
  if (font_awesome_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (font_awesome_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function font_awesome_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) font_awesome_setPrototypeOf(subClass, superClass);
}
function font_awesome_setPrototypeOf(o, p) {
  font_awesome_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return font_awesome_setPrototypeOf(o, p);
}
function font_awesome_createSuper(Derived) {
  var hasNativeReflectConstruct = font_awesome_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = font_awesome_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = font_awesome_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return font_awesome_possibleConstructorReturn(this, result);
  };
}
function font_awesome_possibleConstructorReturn(self, call) {
  if (call && (font_awesome_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 font_awesome_assertThisInitialized(self);
}
function font_awesome_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function font_awesome_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 font_awesome_getPrototypeOf(o) {
  font_awesome_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return font_awesome_getPrototypeOf(o);
}



var FontAwesome = /*#__PURE__*/function (_CustomElement) {
  font_awesome_inherits(FontAwesome, _CustomElement);
  var _super = font_awesome_createSuper(FontAwesome);
  function FontAwesome() {
    font_awesome_classCallCheck(this, FontAwesome);
    return _super.apply(this, arguments);
  }
  font_awesome_createClass(FontAwesome, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      return icons();
    }
  }]);
  return FontAwesome;
}(CustomElement);
shared_api.elements.define('converse-fontawesome', FontAwesome);
;// CONCATENATED MODULE: ./src/plugins/rootview/templates/root.js
var root_templateObject;
function root_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}



/* harmony default export */ const templates_root = (function () {
  var extra_classes = shared_api.settings.get('singleton') ? ['converse-singleton'] : [];
  extra_classes.push("converse-".concat(shared_api.settings.get('view_mode')));
  return (0,external_lit_namespaceObject.html)(root_templateObject || (root_templateObject = root_taggedTemplateLiteral(["\n        <converse-chats class=\"converse-chatboxes row no-gutters ", "\"></converse-chats>\n        <div id=\"converse-modals\" class=\"modals\"></div>\n        <converse-fontawesome></converse-fontawesome>\n    "])), extra_classes.join(' '));
});
;// CONCATENATED MODULE: ./src/plugins/rootview/utils.js

function getTheme() {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return shared_api.settings.get('dark_theme');
  } else {
    return shared_api.settings.get('theme');
  }
}
function ensureElement() {
  if (!shared_api.settings.get('auto_insert')) {
    return;
  }
  var root = shared_api.settings.get('root');
  if (!root.querySelector('converse-root')) {
    var el = document.createElement('converse-root');
    var body = root.querySelector('body');
    if (body) {
      body.appendChild(el);
    } else {
      root.appendChild(el); // Perhaps inside a web component?
    }
  }
}
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/rootview/styles/root.scss
var styles_root = __webpack_require__(5048);
;// CONCATENATED MODULE: ./src/plugins/rootview/styles/root.scss

      
      
      
      
      
      
      
      
      

var root_options = {};

root_options.styleTagTransform = (styleTagTransform_default());
root_options.setAttributes = (setAttributesWithoutAttributes_default());

      root_options.insert = insertBySelector_default().bind(null, "head");
    
root_options.domAPI = (styleDomAPI_default());
root_options.insertStyleElement = (insertStyleElement_default());

var root_update = injectStylesIntoStyleTag_default()(styles_root/* default */.Z, root_options);




       /* harmony default export */ const rootview_styles_root = (styles_root/* default */.Z && styles_root/* default */.Z.locals ? styles_root/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/rootview/root.js
function root_typeof(obj) {
  "@babel/helpers - typeof";

  return root_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;
  }, root_typeof(obj);
}
function root_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function root_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, root_toPropertyKey(descriptor.key), descriptor);
  }
}
function root_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) root_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) root_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function root_toPropertyKey(arg) {
  var key = root_toPrimitive(arg, "string");
  return root_typeof(key) === "symbol" ? key : String(key);
}
function root_toPrimitive(input, hint) {
  if (root_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (root_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function root_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) root_setPrototypeOf(subClass, superClass);
}
function root_setPrototypeOf(o, p) {
  root_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return root_setPrototypeOf(o, p);
}
function root_createSuper(Derived) {
  var hasNativeReflectConstruct = root_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = root_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = root_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return root_possibleConstructorReturn(this, result);
  };
}
function root_possibleConstructorReturn(self, call) {
  if (call && (root_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 root_assertThisInitialized(self);
}
function root_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function root_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 root_getPrototypeOf(o) {
  root_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return root_getPrototypeOf(o);
}







/**
 * `converse-root` is an optional custom element which can be used to
 * declaratively insert the Converse UI into the DOM.
 *
 * It can be inserted into the DOM before or after Converse has loaded or been
 * initialized.
 */
var ConverseRoot = /*#__PURE__*/function (_CustomElement) {
  root_inherits(ConverseRoot, _CustomElement);
  var _super = root_createSuper(ConverseRoot);
  function ConverseRoot() {
    root_classCallCheck(this, ConverseRoot);
    return _super.apply(this, arguments);
  }
  root_createClass(ConverseRoot, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      return templates_root();
    }
  }, {
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.setAttribute('id', 'conversejs');
      this.setClasses();
      var settings = getAppSettings();
      this.listenTo(settings, 'change:view_mode', function () {
        return _this.setClasses();
      });
      this.listenTo(settings, 'change:singleton', function () {
        return _this.setClasses();
      });
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function () {
        return _this.setClasses();
      });
      window.matchMedia('(prefers-color-scheme: light)').addListener(function () {
        return _this.setClasses();
      });
    }
  }, {
    key: "setClasses",
    value: function setClasses() {
      this.className = "";
      this.classList.add('conversejs');
      this.classList.add("converse-".concat(shared_api.settings.get('view_mode')));
      this.classList.add("theme-".concat(getTheme()));
      this.requestUpdate();
    }
  }]);
  return ConverseRoot;
}(CustomElement);

;// CONCATENATED MODULE: ./src/plugins/rootview/index.js



public_converse.plugins.add('converse-rootview', {
  initialize: function initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    shared_api.settings.extend({
      'auto_insert': true,
      'theme': 'classic',
      'dark_theme': 'dracula'
    });
    shared_api.listen.on('chatBoxesInitialized', ensureElement);

    // Only define the element now, otherwise it it's already in the DOM
    // before `converse.initialized` has been called it will render too
    // early.
    shared_api.elements.define('converse-root', ConverseRoot);
  }
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/modals/templates/add-contact.js
var add_contact_templateObject;
function add_contact_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




/* harmony default export */ const add_contact = (function (el) {
  var i18n_add = __('Add');
  var i18n_contact_placeholder = __('name@example.org');
  var i18n_error_message = __('Please enter a valid XMPP address');
  var i18n_group = __('Group');
  var i18n_nickname = __('Name');
  var i18n_xmpp_address = __('XMPP Address');
  return (0,external_lit_namespaceObject.html)(add_contact_templateObject || (add_contact_templateObject = add_contact_taggedTemplateLiteral(["\n        <form class=\"converse-form add-xmpp-contact\" @submit=", ">\n            <div class=\"modal-body\">\n                <span class=\"modal-alert\"></span>\n                <div class=\"form-group add-xmpp-contact__jid\">\n                    <label class=\"clearfix\" for=\"jid\">", ":</label>\n                    <div class=\"suggestion-box suggestion-box__jid\">\n                        <ul class=\"suggestion-box__results suggestion-box__results--below\" hidden=\"\"></ul>\n                        <input type=\"text\" name=\"jid\" ?required=", "\n                            value=\"", "\"\n                            class=\"form-control suggestion-box__input\"\n                            placeholder=\"", "\"/>\n                        <span class=\"suggestion-box__additions visually-hidden\" role=\"status\" aria-live=\"assertive\" aria-relevant=\"additions\"></span>\n                    </div>\n                </div>\n\n                <div class=\"form-group add-xmpp-contact__name\">\n                    <label class=\"clearfix\" for=\"name\">", ":</label>\n                    <div class=\"suggestion-box suggestion-box__name\">\n                        <ul class=\"suggestion-box__results suggestion-box__results--above\" hidden=\"\"></ul>\n                        <input type=\"text\" name=\"name\" value=\"", "\"\n                            class=\"form-control suggestion-box__input\"/>\n                        <span class=\"suggestion-box__additions visually-hidden\" role=\"status\" aria-live=\"assertive\" aria-relevant=\"additions\"></span>\n                    </div>\n                </div>\n                <div class=\"form-group add-xmpp-contact__group\">\n                    <label class=\"clearfix\" for=\"name\">", ":</label>\n                    <converse-autocomplete .list=", " name=\"group\"></converse-autocomplete>\n                </div>\n                <div class=\"form-group\"><div class=\"invalid-feedback\">", "</div></div>\n                <button type=\"submit\" class=\"btn btn-primary\">", "</button>\n            </div>\n        </form>"])), function (ev) {
    return el.addContactFromForm(ev);
  }, i18n_xmpp_address, !shared_api.settings.get('xhr_user_search_url'), el.model.get('jid') || '', i18n_contact_placeholder, i18n_nickname, el.model.get('nickname') || '', i18n_group, getGroupsAutoCompleteList(), i18n_error_message, i18n_add);
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/modals/add-contact.js
function add_contact_typeof(obj) {
  "@babel/helpers - typeof";

  return add_contact_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;
  }, add_contact_typeof(obj);
}
function add_contact_toConsumableArray(arr) {
  return add_contact_arrayWithoutHoles(arr) || add_contact_iterableToArray(arr) || add_contact_unsupportedIterableToArray(arr) || add_contact_nonIterableSpread();
}
function add_contact_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function add_contact_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return add_contact_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 add_contact_arrayLikeToArray(o, minLen);
}
function add_contact_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function add_contact_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return add_contact_arrayLikeToArray(arr);
}
function add_contact_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 add_contact_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function add_contact_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, add_contact_toPropertyKey(descriptor.key), descriptor);
  }
}
function add_contact_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) add_contact_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) add_contact_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function add_contact_toPropertyKey(arg) {
  var key = add_contact_toPrimitive(arg, "string");
  return add_contact_typeof(key) === "symbol" ? key : String(key);
}
function add_contact_toPrimitive(input, hint) {
  if (add_contact_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (add_contact_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function add_contact_get() {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    add_contact_get = Reflect.get.bind();
  } else {
    add_contact_get = function _get(target, property, receiver) {
      var base = add_contact_superPropBase(target, property);
      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);
      if (desc.get) {
        return desc.get.call(arguments.length < 3 ? target : receiver);
      }
      return desc.value;
    };
  }
  return add_contact_get.apply(this, arguments);
}
function add_contact_superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = add_contact_getPrototypeOf(object);
    if (object === null) break;
  }
  return object;
}
function add_contact_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) add_contact_setPrototypeOf(subClass, superClass);
}
function add_contact_setPrototypeOf(o, p) {
  add_contact_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return add_contact_setPrototypeOf(o, p);
}
function add_contact_createSuper(Derived) {
  var hasNativeReflectConstruct = add_contact_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = add_contact_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = add_contact_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return add_contact_possibleConstructorReturn(this, result);
  };
}
function add_contact_possibleConstructorReturn(self, call) {
  if (call && (add_contact_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 add_contact_assertThisInitialized(self);
}
function add_contact_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function add_contact_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 add_contact_getPrototypeOf(o) {
  add_contact_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return add_contact_getPrototypeOf(o);
}










var AddContactModal = /*#__PURE__*/function (_BaseModal) {
  add_contact_inherits(AddContactModal, _BaseModal);
  var _super = add_contact_createSuper(AddContactModal);
  function AddContactModal() {
    add_contact_classCallCheck(this, AddContactModal);
    return _super.apply(this, arguments);
  }
  add_contact_createClass(AddContactModal, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      add_contact_get(add_contact_getPrototypeOf(AddContactModal.prototype), "initialize", this).call(this);
      this.listenTo(this.model, 'change', function () {
        return _this.render();
      });
      this.render();
      this.addEventListener('shown.bs.modal', function () {
        var _this$querySelector;
        return (_this$querySelector = _this.querySelector('input[name="jid"]')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.focus();
      }, false);
    }
  }, {
    key: "renderModal",
    value: function renderModal() {
      return add_contact(this);
    }
  }, {
    key: "getModalTitle",
    value: function getModalTitle() {
      // eslint-disable-line class-methods-use-this
      return __('Add a Contact');
    }
  }, {
    key: "afterRender",
    value: function afterRender() {
      if (typeof shared_api.settings.get('xhr_user_search_url') === 'string') {
        this.initXHRAutoComplete();
      } else {
        this.initJIDAutoComplete();
      }
    }
  }, {
    key: "initJIDAutoComplete",
    value: function initJIDAutoComplete() {
      if (!shared_api.settings.get('autocomplete_add_contact')) {
        return;
      }
      var el = this.querySelector('.suggestion-box__jid').parentElement;
      this.jid_auto_complete = new shared_converse.AutoComplete(el, {
        'data': function data(text, input) {
          return "".concat(input.slice(0, input.indexOf("@")), "@").concat(text);
        },
        'filter': shared_converse.FILTER_STARTSWITH,
        'list': add_contact_toConsumableArray(new Set(shared_converse.roster.map(function (item) {
          return external_strophe_namespaceObject.Strophe.getDomainFromJid(item.get('jid'));
        })))
      });
    }
  }, {
    key: "initGroupAutoComplete",
    value: function initGroupAutoComplete() {
      if (!shared_api.settings.get('autocomplete_add_contact')) {
        return;
      }
      var el = this.querySelector('.suggestion-box__jid').parentElement;
      this.jid_auto_complete = new shared_converse.AutoComplete(el, {
        'data': function data(text, input) {
          return "".concat(input.slice(0, input.indexOf("@")), "@").concat(text);
        },
        'filter': shared_converse.FILTER_STARTSWITH,
        'list': add_contact_toConsumableArray(new Set(shared_converse.roster.map(function (item) {
          return external_strophe_namespaceObject.Strophe.getDomainFromJid(item.get('jid'));
        })))
      });
    }
  }, {
    key: "initXHRAutoComplete",
    value: function initXHRAutoComplete() {
      var _this2 = this;
      if (!shared_api.settings.get('autocomplete_add_contact')) {
        return this.initXHRFetch();
      }
      var el = this.querySelector('.suggestion-box__name').parentElement;
      this.name_auto_complete = new shared_converse.AutoComplete(el, {
        'auto_evaluate': false,
        'filter': shared_converse.FILTER_STARTSWITH,
        'list': []
      });
      var xhr = new window.XMLHttpRequest();
      // `open` must be called after `onload` for mock/testing purposes.
      xhr.onload = function () {
        if (xhr.responseText) {
          var r = xhr.responseText;
          _this2.name_auto_complete.list = JSON.parse(r).map(function (i) {
            return {
              'label': i.fullname || i.jid,
              'value': i.jid
            };
          });
          _this2.name_auto_complete.auto_completing = true;
          _this2.name_auto_complete.evaluate();
        }
      };
      var input_el = this.querySelector('input[name="name"]');
      input_el.addEventListener('input', lodash_es_debounce(function () {
        xhr.open("GET", "".concat(shared_api.settings.get('xhr_user_search_url'), "q=").concat(encodeURIComponent(input_el.value)), true);
        xhr.send();
      }, 300));
      this.name_auto_complete.on('suggestion-box-selectcomplete', function (ev) {
        _this2.querySelector('input[name="name"]').value = ev.text.label;
        _this2.querySelector('input[name="jid"]').value = ev.text.value;
      });
    }
  }, {
    key: "initXHRFetch",
    value: function initXHRFetch() {
      var _this3 = this;
      this.xhr = new window.XMLHttpRequest();
      this.xhr.onload = function () {
        if (_this3.xhr.responseText) {
          var r = _this3.xhr.responseText;
          var list = JSON.parse(r).map(function (i) {
            return {
              'label': i.fullname || i.jid,
              'value': i.jid
            };
          });
          if (list.length !== 1) {
            var el = _this3.querySelector('.invalid-feedback');
            el.textContent = __('Sorry, could not find a contact with that name');
            addClass('d-block', el);
            return;
          }
          var jid = list[0].value;
          if (_this3.validateSubmission(jid)) {
            var form = _this3.querySelector('form');
            var name = list[0].label;
            _this3.afterSubmission(form, jid, name);
          }
        }
      };
    }
  }, {
    key: "validateSubmission",
    value: function validateSubmission(jid) {
      var el = this.querySelector('.invalid-feedback');
      if (!jid || lodash_es_compact(jid.split('@')).length < 2) {
        addClass('is-invalid', this.querySelector('input[name="jid"]'));
        addClass('d-block', el);
        return false;
      } else if (shared_converse.roster.get(external_strophe_namespaceObject.Strophe.getBareJidFromJid(jid))) {
        el.textContent = __('This contact has already been added');
        addClass('d-block', el);
        return false;
      }
      removeClass('d-block', el);
      return true;
    }
  }, {
    key: "afterSubmission",
    value: function afterSubmission(_form, jid, name, group) {
      if (group && !Array.isArray(group)) {
        group = [group];
      }
      shared_converse.roster.addAndSubscribe(jid, name, group);
      this.model.clear();
      this.modal.hide();
    }
  }, {
    key: "addContactFromForm",
    value: function addContactFromForm(ev) {
      ev.preventDefault();
      var data = new FormData(ev.target);
      var jid = (data.get('jid') || '').trim();
      if (!jid && typeof shared_api.settings.get('xhr_user_search_url') === 'string') {
        var input_el = this.querySelector('input[name="name"]');
        this.xhr.open("GET", "".concat(shared_api.settings.get('xhr_user_search_url'), "q=").concat(encodeURIComponent(input_el.value)), true);
        this.xhr.send();
        return;
      }
      if (this.validateSubmission(jid)) {
        this.afterSubmission(ev.target, jid, data.get('name'), data.get('group'));
      }
    }
  }]);
  return AddContactModal;
}(modal_modal);

shared_api.elements.define('converse-add-contact-modal', AddContactModal);
;// CONCATENATED MODULE: ./src/plugins/rosterview/templates/group.js
var group_templateObject, group_templateObject2;
function group_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}







var group_u = public_converse.env.u;
function renderContact(contact) {
  var jid = contact.get('jid');
  var extra_classes = [];
  if (isUniView()) {
    var chatbox = shared_converse.chatboxes.get(jid);
    if (chatbox && !chatbox.get('hidden')) {
      extra_classes.push('open');
    }
  }
  var ask = contact.get('ask');
  var requesting = contact.get('requesting');
  var subscription = contact.get('subscription');
  if (ask === 'subscribe' || subscription === 'from') {
    /* ask === 'subscribe'
     *      Means we have asked to subscribe to them.
     *
     * subscription === 'from'
     *      They are subscribed to us, but not vice versa.
     *      We assume that there is a pending subscription
     *      from us to them (otherwise we're in a state not
     *      supported by converse.js).
     *
     *  So in both cases the user is a "pending" contact.
     */
    extra_classes.push('pending-xmpp-contact');
  } else if (requesting === true) {
    extra_classes.push('requesting-xmpp-contact');
  } else if (subscription === 'both' || subscription === 'to' || group_u.isSameBareJID(jid, shared_converse.connection.jid)) {
    extra_classes.push('current-xmpp-contact');
    extra_classes.push(subscription);
    extra_classes.push(contact.presence.get('show'));
  }
  return (0,external_lit_namespaceObject.html)(group_templateObject || (group_templateObject = group_taggedTemplateLiteral(["\n        <li class=\"list-item d-flex controlbox-padded ", "\" data-status=\"", "\">\n            <converse-roster-contact .model=", "></converse-roster-contact>\n        </li>"])), extra_classes.join(' '), contact.presence.get('show'), contact);
}
/* harmony default export */ const group = (function (o) {
  var i18n_title = __('Click to hide these contacts');
  var collapsed = shared_converse.roster.state.get('collapsed_groups');
  return (0,external_lit_namespaceObject.html)(group_templateObject2 || (group_templateObject2 = group_taggedTemplateLiteral(["\n        <div class=\"roster-group\" data-group=\"", "\">\n            <a href=\"#\" class=\"list-toggle group-toggle controlbox-padded\" title=\"", "\" @click=", ">\n                <converse-icon color=\"var(--chat-head-color-dark)\" size=\"1em\" class=\"fa ", "\"></converse-icon> ", "\n            </a>\n            <ul class=\"items-list roster-group-contacts ", "\" data-group=\"", "\">\n                ", "\n            </ul>\n        </div>"])), o.name, i18n_title, function (ev) {
    return toggleGroup(ev, o.name);
  }, collapsed.includes(o.name) ? 'fa-caret-right' : 'fa-caret-down', o.name, collapsed.includes(o.name) ? 'collapsed' : '', o.name, repeat_c(o.contacts, function (c) {
    return c.get('jid');
  }, renderContact));
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/templates/roster.js
var roster_templateObject, roster_templateObject2;
function roster_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}







/* harmony default export */ const roster = (function (el) {
  var i18n_heading_contacts = __('Contacts');
  var i18n_toggle_contacts = __('Click to toggle contacts');
  var i18n_title_add_contact = __('Add a contact');
  var i18n_title_sync_contacts = __('Re-sync your contacts');
  var roster = shared_converse.roster || [];
  var contacts_map = roster.reduce(function (acc, contact) {
    return populateContactsMap(acc, contact);
  }, {});
  var groupnames = Object.keys(contacts_map).filter(shouldShowGroup);
  var is_closed = el.model.get('toggle_state') === shared_converse.CLOSED;
  groupnames.sort(groupsComparator);
  return (0,external_lit_namespaceObject.html)(roster_templateObject || (roster_templateObject = roster_taggedTemplateLiteral(["\n        <div class=\"d-flex controlbox-padded\">\n            <span class=\"w-100 controlbox-heading controlbox-heading--contacts\">\n                <a class=\"list-toggle open-contacts-toggle\" title=\"", "\" @click=", ">\n                    <converse-icon\n                        class=\"fa ", "\"\n                        size=\"1em\"\n                        color=\"var(--chat-color)\"></converse-icon>\n                    ", "\n                </a>\n            </span>\n            <a class=\"controlbox-heading__btn sync-contacts\"\n               @click=", "\n               title=\"", "\">\n\n                <converse-icon class=\"fa fa-sync right ", "\" size=\"1em\"></converse-icon>\n            </a>\n            ", "\n        </div>\n\n        <div class=\"list-container roster-contacts ", "\">\n            <converse-roster-filter @update=", "></converse-roster-filter>\n            ", "\n        </div>\n    "])), i18n_toggle_contacts, el.toggleRoster, is_closed ? 'fa-caret-right' : 'fa-caret-down', i18n_heading_contacts, function (ev) {
    return el.syncContacts(ev);
  }, i18n_title_sync_contacts, el.syncing_contacts ? 'fa-spin' : '', shared_api.settings.get('allow_contact_requests') ? (0,external_lit_namespaceObject.html)(roster_templateObject2 || (roster_templateObject2 = roster_taggedTemplateLiteral(["\n                <a class=\"controlbox-heading__btn add-contact\"\n                    @click=", "\n                    title=\"", "\"\n                    data-toggle=\"modal\"\n                    data-target=\"#add-contact-modal\">\n                    <converse-icon class=\"fa fa-user-plus right\" size=\"1.25em\"></converse-icon>\n                </a>"])), function (ev) {
    return el.showAddContactModal(ev);
  }, i18n_title_add_contact) : '', is_closed ? 'hidden' : '', function () {
    return el.requestUpdate();
  }, repeat_c(groupnames, function (n) {
    return n;
  }, function (name) {
    var contacts = contacts_map[name].filter(function (c) {
      return shouldShowContact(c, name);
    });
    contacts.sort(contactsComparator);
    return contacts.length ? group({
      contacts: contacts,
      name: name
    }) : '';
  }));
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/rosterview.js
function rosterview_typeof(obj) {
  "@babel/helpers - typeof";

  return rosterview_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;
  }, rosterview_typeof(obj);
}
function rosterview_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  rosterview_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" == rosterview_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 rosterview_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 rosterview_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        rosterview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        rosterview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function rosterview_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function rosterview_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, rosterview_toPropertyKey(descriptor.key), descriptor);
  }
}
function rosterview_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) rosterview_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) rosterview_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function rosterview_toPropertyKey(arg) {
  var key = rosterview_toPrimitive(arg, "string");
  return rosterview_typeof(key) === "symbol" ? key : String(key);
}
function rosterview_toPrimitive(input, hint) {
  if (rosterview_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (rosterview_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function rosterview_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) rosterview_setPrototypeOf(subClass, superClass);
}
function rosterview_setPrototypeOf(o, p) {
  rosterview_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return rosterview_setPrototypeOf(o, p);
}
function rosterview_createSuper(Derived) {
  var hasNativeReflectConstruct = rosterview_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = rosterview_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = rosterview_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return rosterview_possibleConstructorReturn(this, result);
  };
}
function rosterview_possibleConstructorReturn(self, call) {
  if (call && (rosterview_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 rosterview_assertThisInitialized(self);
}
function rosterview_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function rosterview_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 rosterview_getPrototypeOf(o) {
  rosterview_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return rosterview_getPrototypeOf(o);
}







/**
 * @class
 * @namespace _converse.RosterView
 * @memberOf _converse
 */
var RosterView = /*#__PURE__*/function (_CustomElement) {
  rosterview_inherits(RosterView, _CustomElement);
  var _super = rosterview_createSuper(RosterView);
  function RosterView() {
    rosterview_classCallCheck(this, RosterView);
    return _super.apply(this, arguments);
  }
  rosterview_createClass(RosterView, [{
    key: "initialize",
    value: function () {
      var _initialize = rosterview_asyncToGenerator( /*#__PURE__*/rosterview_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        var id, chatboxes, presences, roster;
        return rosterview_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              id = "converse.contacts-panel".concat(shared_converse.bare_jid);
              this.model = new Model({
                id: id
              });
              initStorage(this.model, id);
              this.model.fetch();
              _context.next = 6;
              return shared_api.waitUntil('rosterInitialized');
            case 6:
              chatboxes = shared_converse.chatboxes, presences = shared_converse.presences, roster = shared_converse.roster;
              this.listenTo(shared_converse, 'rosterContactsFetched', function () {
                return _this.requestUpdate();
              });
              this.listenTo(presences, 'change:show', function () {
                return _this.requestUpdate();
              });
              this.listenTo(chatboxes, 'change:hidden', function () {
                return _this.requestUpdate();
              });
              this.listenTo(roster, 'add', function () {
                return _this.requestUpdate();
              });
              this.listenTo(roster, 'destroy', function () {
                return _this.requestUpdate();
              });
              this.listenTo(roster, 'remove', function () {
                return _this.requestUpdate();
              });
              this.listenTo(roster, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(roster.state, 'change', function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change', function () {
                return _this.requestUpdate();
              });
              /**
               * Triggered once the _converse.RosterView instance has been created and initialized.
               * @event _converse#rosterViewInitialized
               * @example _converse.api.listen.on('rosterViewInitialized', () => { ... });
               */
              shared_api.trigger('rosterViewInitialized');
            case 17:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      return roster(this);
    }
  }, {
    key: "showAddContactModal",
    value: function showAddContactModal(ev) {
      // eslint-disable-line class-methods-use-this
      shared_api.modal.show('converse-add-contact-modal', {
        'model': new Model()
      }, ev);
    }
  }, {
    key: "syncContacts",
    value: function () {
      var _syncContacts = rosterview_asyncToGenerator( /*#__PURE__*/rosterview_regeneratorRuntime().mark(function _callee2(ev) {
        var roster;
        return rosterview_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              // eslint-disable-line class-methods-use-this
              ev.preventDefault();
              roster = shared_converse.roster;
              this.syncing_contacts = true;
              this.requestUpdate();
              roster.data.save('version', null);
              _context2.next = 7;
              return roster.fetchFromServer();
            case 7:
              shared_api.user.presence.send();
              this.syncing_contacts = false;
              this.requestUpdate();
            case 10:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function syncContacts(_x) {
        return _syncContacts.apply(this, arguments);
      }
      return syncContacts;
    }()
  }, {
    key: "toggleRoster",
    value: function toggleRoster(ev) {
      var _ev$preventDefault,
        _this2 = this;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      var list_el = this.querySelector('.list-container.roster-contacts');
      if (this.model.get('toggle_state') === shared_converse.CLOSED) {
        slideOut(list_el).then(function () {
          return _this2.model.save({
            'toggle_state': shared_converse.OPENED
          });
        });
      } else {
        slideIn(list_el).then(function () {
          return _this2.model.save({
            'toggle_state': shared_converse.CLOSED
          });
        });
      }
    }
  }]);
  return RosterView;
}(CustomElement);

shared_api.elements.define('converse-roster', RosterView);
;// CONCATENATED MODULE: ./src/plugins/rosterview/templates/requesting_contact.js
var requesting_contact_templateObject;
function requesting_contact_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}

/* harmony default export */ const requesting_contact = (function (o) {
  return (0,external_lit_namespaceObject.html)(requesting_contact_templateObject || (requesting_contact_templateObject = requesting_contact_taggedTemplateLiteral(["\n   <a class=\"open-chat w-100\" href=\"#\" @click=", ">\n      <span class=\"req-contact-name w-100\" title=\"JID: ", "\">", "</span>\n   </a>\n   <a class=\"accept-xmpp-request list-item-action list-item-action--visible\"\n      @click=", "\n      aria-label=\"", "\" title=\"", "\" href=\"#\">\n\n      <converse-icon class=\"fa fa-check\" size=\"1em\"></converse-icon>\n   </a>\n\n   <a class=\"decline-xmpp-request list-item-action list-item-action--visible\"\n      @click=", "\n      aria-label=\"", "\" title=\"", "\" href=\"#\">\n\n      <converse-icon class=\"fa fa-times\" size=\"1em\"></converse-icon>\n   </a>"])), o.openChat, o.jid, o.display_name, o.acceptRequest, o.desc_accept, o.desc_accept, o.declineRequest, o.desc_decline, o.desc_decline);
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/constants.js

var STATUSES = {
  'dnd': __('This contact is busy'),
  'online': __('This contact is online'),
  'offline': __('This contact is offline'),
  'unavailable': __('This contact is unavailable'),
  'xa': __('This contact is away for an extended period'),
  'away': __('This contact is away')
};
;// CONCATENATED MODULE: ./src/plugins/rosterview/templates/roster_item.js
var roster_item_templateObject, roster_item_templateObject2, roster_item_templateObject3;
function roster_item_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}




var tplRemoveLink = function tplRemoveLink(el, item) {
  var display_name = item.getDisplayName();
  var i18n_remove = __('Click to remove %1$s as a contact', display_name);
  return (0,external_lit_namespaceObject.html)(roster_item_templateObject || (roster_item_templateObject = roster_item_taggedTemplateLiteral(["\n      <a class=\"list-item-action remove-xmpp-contact\" @click=", " title=\"", "\" href=\"#\">\n         <converse-icon class=\"fa fa-trash-alt\" size=\"1.5em\"></converse-icon>\n      </a>\n   "])), el.removeContact, i18n_remove);
};
/* harmony default export */ const roster_item = (function (el, item) {
  var _el$model$vcard, _el$model$vcard2;
  var show = item.presence.get('show') || 'offline';
  var classes, color;
  if (show === 'online') {
    classes = 'fa fa-circle';
    color = 'chat-status-online';
  } else if (show === 'dnd') {
    classes = 'fa fa-minus-circle';
    color = 'chat-status-busy';
  } else if (show === 'away') {
    classes = 'fa fa-circle';
    color = 'chat-status-away';
  } else {
    classes = 'fa fa-circle';
    color = 'subdued-color';
  }
  var desc_status = STATUSES[show];
  var num_unread = item.get('num_unread') || 0;
  var display_name = item.getDisplayName();
  var i18n_chat = __('Click to chat with %1$s (XMPP address: %2$s)', display_name, el.model.get('jid'));
  return (0,external_lit_namespaceObject.html)(roster_item_templateObject2 || (roster_item_templateObject2 = roster_item_taggedTemplateLiteral(["\n   <a class=\"list-item-link cbox-list-item open-chat ", "\" title=\"", "\" href=\"#\" @click=", ">\n      <span>\n         <converse-avatar\n            class=\"avatar\"\n            .data=", "\n            nonce=", "\n            height=\"30\" width=\"30\"></converse-avatar>\n         <converse-icon\n            title=\"", "\"\n            color=\"var(--", ")\"\n            size=\"1em\"\n            class=\"", " chat-status chat-status--avatar\"></converse-icon>\n      </span>\n      ", "\n      <span class=\"contact-name contact-name--", " ", "\">", "</span>\n   </a>\n   ", ""])), num_unread ? 'unread-msgs' : '', i18n_chat, el.openChat, (_el$model$vcard = el.model.vcard) === null || _el$model$vcard === void 0 ? void 0 : _el$model$vcard.attributes, (_el$model$vcard2 = el.model.vcard) === null || _el$model$vcard2 === void 0 ? void 0 : _el$model$vcard2.get('vcard_updated'), desc_status, color, classes, num_unread ? (0,external_lit_namespaceObject.html)(roster_item_templateObject3 || (roster_item_templateObject3 = roster_item_taggedTemplateLiteral(["<span class=\"msgs-indicator\">", "</span>"])), num_unread) : '', el.show, num_unread ? 'unread-msgs' : '', display_name, shared_api.settings.get('allow_contact_removal') ? tplRemoveLink(el, item) : '');
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/contactview.js
function contactview_typeof(obj) {
  "@babel/helpers - typeof";

  return contactview_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;
  }, contactview_typeof(obj);
}
function contactview_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  contactview_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" == contactview_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 contactview_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 contactview_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        contactview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        contactview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function contactview_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function contactview_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, contactview_toPropertyKey(descriptor.key), descriptor);
  }
}
function contactview_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) contactview_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) contactview_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function contactview_toPropertyKey(arg) {
  var key = contactview_toPrimitive(arg, "string");
  return contactview_typeof(key) === "symbol" ? key : String(key);
}
function contactview_toPrimitive(input, hint) {
  if (contactview_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (contactview_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function contactview_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) contactview_setPrototypeOf(subClass, superClass);
}
function contactview_setPrototypeOf(o, p) {
  contactview_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return contactview_setPrototypeOf(o, p);
}
function contactview_createSuper(Derived) {
  var hasNativeReflectConstruct = contactview_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = contactview_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = contactview_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return contactview_possibleConstructorReturn(this, result);
  };
}
function contactview_possibleConstructorReturn(self, call) {
  if (call && (contactview_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 contactview_assertThisInitialized(self);
}
function contactview_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function contactview_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 contactview_getPrototypeOf(o) {
  contactview_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return contactview_getPrototypeOf(o);
}






var contactview_RosterContact = /*#__PURE__*/function (_CustomElement) {
  contactview_inherits(RosterContact, _CustomElement);
  var _super = contactview_createSuper(RosterContact);
  function RosterContact() {
    contactview_classCallCheck(this, RosterContact);
    return _super.apply(this, arguments);
  }
  contactview_createClass(RosterContact, [{
    key: "initialize",
    value: function initialize() {
      var _this = this;
      this.listenTo(this.model, 'change', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'highlight', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'vcard:add', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'vcard:change', function () {
        return _this.requestUpdate();
      });
      this.listenTo(this.model, 'presenceChanged', function () {
        return _this.requestUpdate();
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      if (this.model.get('requesting') === true) {
        var display_name = this.model.getDisplayName();
        return requesting_contact(Object.assign(this.model.toJSON(), {
          display_name: display_name,
          'openChat': function openChat(ev) {
            return _this2.openChat(ev);
          },
          'acceptRequest': function acceptRequest(ev) {
            return _this2.acceptRequest(ev);
          },
          'declineRequest': function declineRequest(ev) {
            return _this2.declineRequest(ev);
          },
          'desc_accept': __("Click to accept the contact request from %1$s", display_name),
          'desc_decline': __("Click to decline the contact request from %1$s", display_name)
        }));
      } else {
        return roster_item(this, this.model);
      }
    }
  }, {
    key: "openChat",
    value: function openChat(ev) {
      var _ev$preventDefault;
      ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
      this.model.openChat();
    }
  }, {
    key: "removeContact",
    value: function () {
      var _removeContact = contactview_asyncToGenerator( /*#__PURE__*/contactview_regeneratorRuntime().mark(function _callee(ev) {
        var _ev$preventDefault2;
        var result;
        return contactview_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
              if (shared_api.settings.get('allow_contact_removal')) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return");
            case 3:
              _context.next = 5;
              return shared_api.confirm(__("Are you sure you want to remove this contact?"));
            case 5:
              result = _context.sent;
              if (result) {
                _context.next = 8;
                break;
              }
              return _context.abrupt("return");
            case 8:
              try {
                this.model.removeFromRoster();
                if (this.model.collection) {
                  // The model might have already been removed as
                  // result of a roster push.
                  this.model.destroy();
                }
              } catch (e) {
                log.error(e);
                shared_api.alert('error', __('Error'), [__('Sorry, there was an error while trying to remove %1$s as a contact.', this.model.getDisplayName())]);
              }
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function removeContact(_x) {
        return _removeContact.apply(this, arguments);
      }
      return removeContact;
    }()
  }, {
    key: "acceptRequest",
    value: function () {
      var _acceptRequest = contactview_asyncToGenerator( /*#__PURE__*/contactview_regeneratorRuntime().mark(function _callee2(ev) {
        var _ev$preventDefault3;
        return contactview_regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              ev === null || ev === void 0 ? void 0 : (_ev$preventDefault3 = ev.preventDefault) === null || _ev$preventDefault3 === void 0 ? void 0 : _ev$preventDefault3.call(ev);
              _context2.next = 3;
              return shared_converse.roster.sendContactAddIQ(this.model.get('jid'), this.model.getFullname(), []);
            case 3:
              this.model.authorize().subscribe();
            case 4:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function acceptRequest(_x2) {
        return _acceptRequest.apply(this, arguments);
      }
      return acceptRequest;
    }()
  }, {
    key: "declineRequest",
    value: function () {
      var _declineRequest = contactview_asyncToGenerator( /*#__PURE__*/contactview_regeneratorRuntime().mark(function _callee3(ev) {
        var result;
        return contactview_regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (ev && ev.preventDefault) {
                ev.preventDefault();
              }
              _context3.next = 3;
              return shared_api.confirm(__("Are you sure you want to decline this contact request?"));
            case 3:
              result = _context3.sent;
              if (result) {
                this.model.unauthorize().destroy();
              }
              return _context3.abrupt("return", this);
            case 6:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function declineRequest(_x3) {
        return _declineRequest.apply(this, arguments);
      }
      return declineRequest;
    }()
  }], [{
    key: "properties",
    get: function get() {
      return {
        model: {
          type: Object
        }
      };
    }
  }]);
  return RosterContact;
}(CustomElement);

shared_api.elements.define('converse-roster-contact', contactview_RosterContact);
;// CONCATENATED MODULE: ./src/plugins/rosterview/templates/roster_filter.js
var roster_filter_templateObject;
function roster_filter_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const roster_filter = (function (o) {
  var i18n_placeholder = __('Filter');
  var title_contact_filter = __('Filter by contact name');
  var title_group_filter = __('Filter by group name');
  var title_status_filter = __('Filter by status');
  var label_any = __('Any');
  var label_unread_messages = __('Unread');
  var label_online = __('Online');
  var label_chatty = __('Chatty');
  var label_busy = __('Busy');
  var label_away = __('Away');
  var label_xa = __('Extended Away');
  var label_offline = __('Offline');
  return (0,external_lit_namespaceObject.html)(roster_filter_templateObject || (roster_filter_templateObject = roster_filter_taggedTemplateLiteral(["\n        <form class=\"controlbox-padded roster-filter-form input-button-group ", "\"\n            @submit=", ">\n            <div class=\"form-inline flex-nowrap\">\n                <div class=\"filter-by d-flex flex-nowrap\">\n                    <converse-icon size=\"1em\" @click=", " class=\"fa fa-user clickable ", "\" data-type=\"contacts\" title=\"", "\"></converse-icon>\n                    <converse-icon size=\"1em\" @click=", " class=\"fa fa-users clickable ", "\" data-type=\"groups\" title=\"", "\"></converse-icon>\n                    <converse-icon size=\"1em\" @click=", " class=\"fa fa-circle clickable ", "\" data-type=\"state\" title=\"", "\"></converse-icon>\n                </div>\n                <div class=\"btn-group\">\n                    <input .value=\"", "\"\n                        @keydown=", "\n                        class=\"roster-filter form-control ", "\"\n                        placeholder=\"", "\"/>\n                    <converse-icon size=\"1em\" class=\"fa fa-times clear-input ", "\"\n                        @click=", ">\n                    </converse-icon>\n                </div>\n                <select class=\"form-control state-type ", "\"\n                        @change=", ">\n                    <option value=\"\">", "</option>\n                    <option ?selected=", " value=\"unread_messages\">", "</option>\n                    <option ?selected=", " value=\"online\">", "</option>\n                    <option ?selected=", " value=\"chat\">", "</option>\n                    <option ?selected=", " value=\"dnd\">", "</option>\n                    <option ?selected=", " value=\"away\">", "</option>\n                    <option ?selected=", " value=\"xa\">", "</option>\n                    <option ?selected=", " value=\"offline\">", "</option>\n                </select>\n            </div>\n        </form>"])), !o.visible ? 'hidden' : 'fade-in', o.submitFilter, o.changeTypeFilter, o.filter_type === 'contacts' ? 'selected' : '', title_contact_filter, o.changeTypeFilter, o.filter_type === 'groups' ? 'selected' : '', title_group_filter, o.changeTypeFilter, o.filter_type === 'state' ? 'selected' : '', title_status_filter, o.filter_text || '', o.liveFilter, o.filter_type === 'state' ? 'hidden' : '', i18n_placeholder, !o.filter_text || o.filter_type === 'state' ? 'hidden' : '', o.clearFilter, o.filter_type !== 'state' ? 'hidden' : '', o.changeChatStateFilter, label_any, o.chat_state === 'unread_messages', label_unread_messages, o.chat_state === 'online', label_online, o.chat_state === 'chat', label_chatty, o.chat_state === 'dnd', label_busy, o.chat_state === 'away', label_away, o.chat_state === 'xa', label_xa, o.chat_state === 'offline', label_offline);
});
;// CONCATENATED MODULE: ./src/plugins/rosterview/filterview.js
function filterview_typeof(obj) {
  "@babel/helpers - typeof";

  return filterview_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;
  }, filterview_typeof(obj);
}
function filterview_regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  filterview_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" == filterview_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 filterview_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 filterview_asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        filterview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        filterview_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function filterview_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function filterview_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, filterview_toPropertyKey(descriptor.key), descriptor);
  }
}
function filterview_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) filterview_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) filterview_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function filterview_toPropertyKey(arg) {
  var key = filterview_toPrimitive(arg, "string");
  return filterview_typeof(key) === "symbol" ? key : String(key);
}
function filterview_toPrimitive(input, hint) {
  if (filterview_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (filterview_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function filterview_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) filterview_setPrototypeOf(subClass, superClass);
}
function filterview_setPrototypeOf(o, p) {
  filterview_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return filterview_setPrototypeOf(o, p);
}
function filterview_createSuper(Derived) {
  var hasNativeReflectConstruct = filterview_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = filterview_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = filterview_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return filterview_possibleConstructorReturn(this, result);
  };
}
function filterview_possibleConstructorReturn(self, call) {
  if (call && (filterview_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 filterview_assertThisInitialized(self);
}
function filterview_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function filterview_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 filterview_getPrototypeOf(o) {
  filterview_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return filterview_getPrototypeOf(o);
}





var RosterFilterView = /*#__PURE__*/function (_CustomElement) {
  filterview_inherits(RosterFilterView, _CustomElement);
  var _super = filterview_createSuper(RosterFilterView);
  function RosterFilterView() {
    filterview_classCallCheck(this, RosterFilterView);
    return _super.apply(this, arguments);
  }
  filterview_createClass(RosterFilterView, [{
    key: "initialize",
    value: function () {
      var _initialize = filterview_asyncToGenerator( /*#__PURE__*/filterview_regeneratorRuntime().mark(function _callee() {
        var _this = this;
        return filterview_regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return shared_api.waitUntil('rosterInitialized');
            case 2:
              this.model = shared_converse.roster_filter;
              this.liveFilter = lodash_es_debounce(function () {
                _this.model.save({
                  'filter_text': _this.querySelector('.roster-filter').value
                });
              }, 250);
              this.listenTo(shared_converse, 'rosterContactsFetched', function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse.presences, 'change:show', function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse.roster, "add", function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse.roster, "destroy", function () {
                return _this.requestUpdate();
              });
              this.listenTo(shared_converse.roster, "remove", function () {
                return _this.requestUpdate();
              });
              this.listenTo(this.model, 'change', this.dispatchUpdateEvent);
              this.listenTo(this.model, 'change', function () {
                return _this.requestUpdate();
              });
              this.requestUpdate();
            case 12:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize() {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      return this.model ? roster_filter(Object.assign(this.model.toJSON(), {
        visible: this.shouldBeVisible(),
        changeChatStateFilter: function changeChatStateFilter(ev) {
          return _this2.changeChatStateFilter(ev);
        },
        changeTypeFilter: function changeTypeFilter(ev) {
          return _this2.changeTypeFilter(ev);
        },
        clearFilter: function clearFilter(ev) {
          return _this2.clearFilter(ev);
        },
        liveFilter: function liveFilter(ev) {
          return _this2.liveFilter(ev);
        },
        submitFilter: function submitFilter(ev) {
          return _this2.submitFilter(ev);
        }
      })) : '';
    }
  }, {
    key: "dispatchUpdateEvent",
    value: function dispatchUpdateEvent() {
      this.dispatchEvent(new CustomEvent('update', {
        'detail': this.model.changed
      }));
    }
  }, {
    key: "changeChatStateFilter",
    value: function changeChatStateFilter(ev) {
      ev && ev.preventDefault();
      this.model.save({
        'chat_state': this.querySelector('.state-type').value
      });
    }
  }, {
    key: "changeTypeFilter",
    value: function changeTypeFilter(ev) {
      var _ancestor;
      ev && ev.preventDefault();
      var type = ((_ancestor = ancestor(ev.target, 'converse-icon')) === null || _ancestor === void 0 ? void 0 : _ancestor.dataset.type) || 'contacts';
      if (type === 'state') {
        this.model.save({
          'filter_type': type,
          'chat_state': this.querySelector('.state-type').value
        });
      } else {
        this.model.save({
          'filter_type': type,
          'filter_text': this.querySelector('.roster-filter').value
        });
      }
    }
  }, {
    key: "submitFilter",
    value: function submitFilter(ev) {
      ev && ev.preventDefault();
      this.liveFilter();
    }

    /**
     * Returns true if the filter is enabled (i.e. if the user
     * has added values to the filter).
     * @private
     * @method _converse.RosterFilterView#isActive
     */
  }, {
    key: "isActive",
    value: function isActive() {
      return this.model.get('filter_type') === 'state' || this.model.get('filter_text');
    }
  }, {
    key: "shouldBeVisible",
    value: function shouldBeVisible() {
      var _converse$roster;
      return ((_converse$roster = shared_converse.roster) === null || _converse$roster === void 0 ? void 0 : _converse$roster.length) >= 5 || this.isActive();
    }
  }, {
    key: "clearFilter",
    value: function clearFilter(ev) {
      ev && ev.preventDefault();
      this.model.save({
        'filter_text': ''
      });
    }
  }]);
  return RosterFilterView;
}(CustomElement);
shared_api.elements.define('converse-roster-filter', RosterFilterView);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/rosterview/styles/roster.scss
var styles_roster = __webpack_require__(8189);
;// CONCATENATED MODULE: ./src/plugins/rosterview/styles/roster.scss

      
      
      
      
      
      
      
      
      

var roster_options = {};

roster_options.styleTagTransform = (styleTagTransform_default());
roster_options.setAttributes = (setAttributesWithoutAttributes_default());

      roster_options.insert = insertBySelector_default().bind(null, "head");
    
roster_options.domAPI = (styleDomAPI_default());
roster_options.insertStyleElement = (insertStyleElement_default());

var roster_update = injectStylesIntoStyleTag_default()(styles_roster/* default */.Z, roster_options);




       /* harmony default export */ const rosterview_styles_roster = (styles_roster/* default */.Z && styles_roster/* default */.Z.locals ? styles_roster/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/rosterview/index.js
/**
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */












public_converse.plugins.add('converse-rosterview', {
  dependencies: ["converse-roster", "converse-modal", "converse-chatboxviews"],
  initialize: function initialize() {
    shared_api.settings.extend({
      'autocomplete_add_contact': true,
      'allow_contact_removal': true,
      'hide_offline_users': false,
      'roster_groups': true,
      'xhr_user_search_url': null
    });
    shared_api.promises.add('rosterViewInitialized');
    shared_converse.RosterFilter = RosterFilter;
    shared_converse.RosterFilterView = RosterFilterView;
    shared_converse.RosterContactView = contactview_RosterContact;

    /* -------- Event Handlers ----------- */
    shared_api.listen.on('chatBoxesInitialized', function () {
      shared_converse.chatboxes.on('destroy', function (chatbox) {
        return highlightRosterItem(chatbox);
      });
      shared_converse.chatboxes.on('change:hidden', function (chatbox) {
        return highlightRosterItem(chatbox);
      });
    });
    shared_api.listen.on('afterTearDown', function () {
      var _converse$rotergroups;
      return (_converse$rotergroups = shared_converse.rotergroups) === null || _converse$rotergroups === void 0 ? void 0 : _converse$rotergroups.off().reset();
    });
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/singleton/singleton.scss
var singleton = __webpack_require__(8398);
;// CONCATENATED MODULE: ./src/plugins/singleton/singleton.scss

      
      
      
      
      
      
      
      
      

var singleton_options = {};

singleton_options.styleTagTransform = (styleTagTransform_default());
singleton_options.setAttributes = (setAttributesWithoutAttributes_default());

      singleton_options.insert = insertBySelector_default().bind(null, "head");
    
singleton_options.domAPI = (styleDomAPI_default());
singleton_options.insertStyleElement = (insertStyleElement_default());

var singleton_update = injectStylesIntoStyleTag_default()(singleton/* default */.Z, singleton_options);




       /* harmony default export */ const singleton_singleton = (singleton/* default */.Z && singleton/* default */.Z.locals ? singleton/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/singleton/index.js
/**
 * @copyright JC Brand
 * @license Mozilla Public License (MPLv2)
 * @description A plugin which restricts Converse to only one chat.
 */


public_converse.plugins.add('converse-singleton', {
  enabled: function enabled(_converse) {
    return _converse.api.settings.get("singleton");
  },
  initialize: function initialize() {
    shared_api.settings.extend({
      'allow_logout': false,
      // No point in logging out when we have auto_login as true.
      'allow_muc_invitations': false,
      // Doesn't make sense to allow because only
      // roster contacts can be invited
      'hide_muc_server': true
    });
    var auto_join_rooms = shared_api.settings.get('auto_join_rooms');
    var auto_join_private_chats = shared_api.settings.get('auto_join_private_chats');
    if (!Array.isArray(auto_join_rooms) && !Array.isArray(auto_join_private_chats)) {
      throw new Error("converse-singleton: auto_join_rooms must be an Array");
    }
    if (auto_join_rooms.length === 0 && auto_join_private_chats.length === 0) {
      throw new Error("If you set singleton set to true, you need " + "to specify auto_join_rooms or auto_join_private_chats");
    }
    if (auto_join_rooms.length > 0 && auto_join_private_chats.length > 0) {
      throw new Error("It doesn't make sense to have singleton set to true and " + "auto_join_rooms or auto_join_private_chats set to more then one, " + "since only one chat room may be open at any time.");
    }
  }
});
;// CONCATENATED MODULE: ./src/plugins/dragresize/utils.js

var dragresize_utils_u = public_converse.env.u;
function onStartVerticalResize(ev) {
  var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  if (!shared_api.settings.get('allow_dragresize')) {
    return true;
  }
  ev.preventDefault();
  // Record element attributes for mouseMove().
  var flyout = dragresize_utils_u.ancestor(ev.target, '.box-flyout');
  var style = window.getComputedStyle(flyout);
  var chatbox_el = flyout.parentElement;
  chatbox_el.height = parseInt(style.height.replace(/px$/, ''), 10);
  shared_converse.resizing = {
    'chatbox': chatbox_el,
    'direction': 'top'
  };
  chatbox_el.prev_pageY = ev.pageY;
  if (trigger) {
    /**
     * Triggered once the user starts to vertically resize a {@link _converse.ChatBoxView}
     * @event _converse#startVerticalResize
     * @example _converse.api.listen.on('startVerticalResize', (view) => { ... });
     */
    shared_api.trigger('startVerticalResize', chatbox_el);
  }
}
function onStartHorizontalResize(ev) {
  var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  if (!shared_api.settings.get('allow_dragresize')) {
    return true;
  }
  ev.preventDefault();
  var flyout = dragresize_utils_u.ancestor(ev.target, '.box-flyout');
  var style = window.getComputedStyle(flyout);
  var chatbox_el = flyout.parentElement;
  chatbox_el.width = parseInt(style.width.replace(/px$/, ''), 10);
  shared_converse.resizing = {
    'chatbox': chatbox_el,
    'direction': 'left'
  };
  chatbox_el.prev_pageX = ev.pageX;
  if (trigger) {
    /**
     * Triggered once the user starts to horizontally resize a {@link _converse.ChatBoxView}
     * @event _converse#startHorizontalResize
     * @example _converse.api.listen.on('startHorizontalResize', (view) => { ... });
     */
    shared_api.trigger('startHorizontalResize', chatbox_el);
  }
}
function onStartDiagonalResize(ev) {
  onStartHorizontalResize(ev, false);
  onStartVerticalResize(ev, false);
  shared_converse.resizing.direction = 'topleft';
  /**
   * Triggered once the user starts to diagonally resize a {@link _converse.ChatBoxView}
   * @event _converse#startDiagonalResize
   * @example _converse.api.listen.on('startDiagonalResize', (view) => { ... });
   */
  shared_api.trigger('startDiagonalResize', this);
}

/**
 * Applies some resistance to `value` around the `default_value`.
 * If value is close enough to `default_value`, then it is returned, otherwise
 * `value` is returned.
 * @param { number } value
 * @param { number } default_value
 * @returns { number }
 */
function applyDragResistance(value, default_value) {
  if (value === undefined) {
    return undefined;
  } else if (default_value === undefined) {
    return value;
  }
  var resistance = 10;
  if (value !== default_value && Math.abs(value - default_value) < resistance) {
    return default_value;
  }
  return value;
}
function onMouseMove(ev) {
  if (!shared_converse.resizing || !shared_api.settings.get('allow_dragresize')) {
    return true;
  }
  ev.preventDefault();
  shared_converse.resizing.chatbox.resizeChatBox(ev);
}
function onMouseUp(ev) {
  if (!shared_converse.resizing || !shared_api.settings.get('allow_dragresize')) {
    return true;
  }
  ev.preventDefault();
  var height = applyDragResistance(shared_converse.resizing.chatbox.height, shared_converse.resizing.chatbox.model.get('default_height'));
  var width = applyDragResistance(shared_converse.resizing.chatbox.width, shared_converse.resizing.chatbox.model.get('default_width'));
  if (shared_api.connection.connected()) {
    shared_converse.resizing.chatbox.model.save({
      'height': height
    });
    shared_converse.resizing.chatbox.model.save({
      'width': width
    });
  } else {
    shared_converse.resizing.chatbox.model.set({
      'height': height
    });
    shared_converse.resizing.chatbox.model.set({
      'width': width
    });
  }
  shared_converse.resizing = null;
}
;// CONCATENATED MODULE: ./src/plugins/dragresize/templates/dragresize.js
var dragresize_templateObject;
function dragresize_taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}


/* harmony default export */ const dragresize = (function () {
  return (0,external_lit_namespaceObject.html)(dragresize_templateObject || (dragresize_templateObject = dragresize_taggedTemplateLiteral(["\n    <div class=\"dragresize dragresize-top\" @mousedown=\"", "\"></div>\n    <div class=\"dragresize dragresize-topleft\" @mousedown=\"", "\"></div>\n    <div class=\"dragresize dragresize-left\" @mousedown=\"", "\"></div>\n"])), onStartVerticalResize, onStartDiagonalResize, onStartHorizontalResize);
});
;// CONCATENATED MODULE: ./src/plugins/dragresize/components/dragresize.js
function dragresize_typeof(obj) {
  "@babel/helpers - typeof";

  return dragresize_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;
  }, dragresize_typeof(obj);
}
function dragresize_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function dragresize_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, dragresize_toPropertyKey(descriptor.key), descriptor);
  }
}
function dragresize_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) dragresize_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) dragresize_defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function dragresize_toPropertyKey(arg) {
  var key = dragresize_toPrimitive(arg, "string");
  return dragresize_typeof(key) === "symbol" ? key : String(key);
}
function dragresize_toPrimitive(input, hint) {
  if (dragresize_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (dragresize_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function dragresize_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) dragresize_setPrototypeOf(subClass, superClass);
}
function dragresize_setPrototypeOf(o, p) {
  dragresize_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return dragresize_setPrototypeOf(o, p);
}
function dragresize_createSuper(Derived) {
  var hasNativeReflectConstruct = dragresize_isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = dragresize_getPrototypeOf(Derived),
      result;
    if (hasNativeReflectConstruct) {
      var NewTarget = dragresize_getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return dragresize_possibleConstructorReturn(this, result);
  };
}
function dragresize_possibleConstructorReturn(self, call) {
  if (call && (dragresize_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 dragresize_assertThisInitialized(self);
}
function dragresize_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function dragresize_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 dragresize_getPrototypeOf(o) {
  dragresize_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return dragresize_getPrototypeOf(o);
}



var ConverseDragResize = /*#__PURE__*/function (_CustomElement) {
  dragresize_inherits(ConverseDragResize, _CustomElement);
  var _super = dragresize_createSuper(ConverseDragResize);
  function ConverseDragResize() {
    dragresize_classCallCheck(this, ConverseDragResize);
    return _super.apply(this, arguments);
  }
  dragresize_createClass(ConverseDragResize, [{
    key: "render",
    value: function render() {
      // eslint-disable-line class-methods-use-this
      return dragresize();
    }
  }]);
  return ConverseDragResize;
}(CustomElement);
shared_api.elements.define('converse-dragresize', ConverseDragResize);
;// CONCATENATED MODULE: ./src/plugins/dragresize/mixin.js



var DragResizableMixin = {
  initDragResize: function initDragResize() {
    var _converse$connection;
    var view = this;
    var debouncedSetDimensions = lodash_es_debounce(function () {
      return view.setDimensions();
    });
    window.addEventListener('resize', view.debouncedSetDimensions);
    this.listenTo(this.model, 'destroy', function () {
      return window.removeEventListener('resize', debouncedSetDimensions);
    });

    // Determine and store the default box size.
    // We need this information for the drag-resizing feature.
    var flyout = this.querySelector('.box-flyout');
    var style = window.getComputedStyle(flyout);
    if (this.model.get('height') === undefined) {
      var height = parseInt(style.height.replace(/px$/, ''), 10);
      var width = parseInt(style.width.replace(/px$/, ''), 10);
      this.model.set('height', height);
      this.model.set('default_height', height);
      this.model.set('width', width);
      this.model.set('default_width', width);
    }
    var min_width = style['min-width'];
    var min_height = style['min-height'];
    this.model.set('min_width', min_width.endsWith('px') ? Number(min_width.replace(/px$/, '')) : 0);
    this.model.set('min_height', min_height.endsWith('px') ? Number(min_height.replace(/px$/, '')) : 0);
    // Initialize last known mouse position
    this.prev_pageY = 0;
    this.prev_pageX = 0;
    if ((_converse$connection = shared_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.connected) {
      this.height = this.model.get('height');
      this.width = this.model.get('width');
    }
    return this;
  },
  resizeChatBox: function resizeChatBox(ev) {
    var diff;
    if (shared_converse.resizing.direction.indexOf('top') === 0) {
      diff = ev.pageY - this.prev_pageY;
      if (diff) {
        this.height = this.height - diff > (this.model.get('min_height') || 0) ? this.height - diff : this.model.get('min_height');
        this.prev_pageY = ev.pageY;
        this.setChatBoxHeight(this.height);
      }
    }
    if (shared_converse.resizing.direction.includes('left')) {
      diff = this.prev_pageX - ev.pageX;
      if (diff) {
        this.width = this.width + diff > (this.model.get('min_width') || 0) ? this.width + diff : this.model.get('min_width');
        this.prev_pageX = ev.pageX;
        this.setChatBoxWidth(this.width);
      }
    }
  },
  setDimensions: function setDimensions() {
    // Make sure the chat box has the right height and width.
    this.adjustToViewport();
    this.setChatBoxHeight(this.model.get('height'));
    this.setChatBoxWidth(this.model.get('width'));
  },
  setChatBoxHeight: function setChatBoxHeight(height) {
    if (height) {
      height = applyDragResistance(height, this.model.get('default_height')) + 'px';
    } else {
      height = '';
    }
    var flyout_el = this.querySelector('.box-flyout');
    if (flyout_el !== null) {
      flyout_el.style.height = height;
    }
  },
  setChatBoxWidth: function setChatBoxWidth(width) {
    if (width) {
      width = applyDragResistance(width, this.model.get('default_width')) + 'px';
    } else {
      width = '';
    }
    this.style.width = width;
    var flyout_el = this.querySelector('.box-flyout');
    if (flyout_el !== null) {
      flyout_el.style.width = width;
    }
  },
  adjustToViewport: function adjustToViewport() {
    /* Event handler called when viewport gets resized. We remove
     * custom width/height from chat boxes.
     */
    var viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var viewport_height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    if (viewport_width <= 480) {
      this.model.set('height', undefined);
      this.model.set('width', undefined);
    } else if (viewport_width <= this.model.get('width')) {
      this.model.set('width', undefined);
    } else if (viewport_height <= this.model.get('height')) {
      this.model.set('height', undefined);
    }
  }
};
/* harmony default export */ const mixin = (DragResizableMixin);
;// CONCATENATED MODULE: ./src/plugins/dragresize/index.js
function dragresize_createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = dragresize_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 dragresize_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return dragresize_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 dragresize_arrayLikeToArray(o, minLen);
}
function dragresize_arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
/**
 * @module converse-dragresize
 * @copyright 2022, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




public_converse.plugins.add('converse-dragresize', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   */
  dependencies: ['converse-chatview', 'converse-headlines-view', 'converse-muc-views'],
  enabled: function enabled(_converse) {
    return _converse.api.settings.get('view_mode') == 'overlayed';
  },
  // Overrides mentioned here will be picked up by converse.js's
  // plugin architecture they will replace existing methods on the
  // relevant objects or classes.
  overrides: {
    ChatBox: {
      initialize: function initialize() {
        var _this = this;
        var result = this.__super__.initialize.apply(this, arguments);
        var height = this.get('height');
        var width = this.get('width');
        var save = this.get('id') === 'controlbox' ? function (a) {
          return _this.set(a);
        } : function (a) {
          return _this.save(a);
        };
        save({
          'height': applyDragResistance(height, this.get('default_height')),
          'width': applyDragResistance(width, this.get('default_width'))
        });
        return result;
      }
    }
  },
  initialize: function initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    shared_api.settings.extend({
      'allow_dragresize': true
    });
    Object.assign(shared_converse.ChatBoxView.prototype, mixin);
    Object.assign(shared_converse.ChatRoomView.prototype, mixin);
    if (shared_converse.ControlBoxView) {
      Object.assign(shared_converse.ControlBoxView.prototype, mixin);
    }

    /************************ BEGIN Event Handlers ************************/
    function registerGlobalEventHandlers() {
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    }
    function unregisterGlobalEventHandlers() {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    }

    /**
     * This function registers mousedown and mouseup events hadlers to 
     * all iframes in the DOM when converse UI resizing events are called
     * to prevent mouse drag stutter effect which is bad user experience.
     * @function dragresizeOverIframeHandler
     * @param {Object} e - dragging node element.
     */
    function dragresizeOverIframeHandler(e) {
      var iframes = document.getElementsByTagName('iframe');
      var _iterator = dragresize_createForOfIteratorHelper(iframes),
        _step;
      try {
        var _loop = function _loop() {
          var iframe = _step.value;
          e.addEventListener('mousedown', function () {
            iframe.style.pointerEvents = 'none';
          }, {
            once: true
          });
          e.addEventListener('mouseup', function () {
            iframe.style.pointerEvents = 'initial';
          }, {
            once: true
          });
        };
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          _loop();
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
    shared_api.listen.on('registeredGlobalEventHandlers', registerGlobalEventHandlers);
    shared_api.listen.on('unregisteredGlobalEventHandlers', unregisterGlobalEventHandlers);
    shared_api.listen.on('beforeShowingChatView', function (view) {
      return view.initDragResize().setDimensions();
    });
    shared_api.listen.on('startDiagonalResize', dragresizeOverIframeHandler);
    shared_api.listen.on('startHorizontalResize', dragresizeOverIframeHandler);
    shared_api.listen.on('startVerticalResize', dragresizeOverIframeHandler);
  }
});
// EXTERNAL MODULE: ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[2].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[2].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[2].use[3]!./node_modules/mini-css-extract-plugin/dist/loader.js!./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./src/plugins/fullscreen/styles/fullscreen.scss
var fullscreen = __webpack_require__(3928);
;// CONCATENATED MODULE: ./src/plugins/fullscreen/styles/fullscreen.scss

      
      
      
      
      
      
      
      
      

var fullscreen_options = {};

fullscreen_options.styleTagTransform = (styleTagTransform_default());
fullscreen_options.setAttributes = (setAttributesWithoutAttributes_default());

      fullscreen_options.insert = insertBySelector_default().bind(null, "head");
    
fullscreen_options.domAPI = (styleDomAPI_default());
fullscreen_options.insertStyleElement = (insertStyleElement_default());

var fullscreen_update = injectStylesIntoStyleTag_default()(fullscreen/* default */.Z, fullscreen_options);




       /* harmony default export */ const styles_fullscreen = (fullscreen/* default */.Z && fullscreen/* default */.Z.locals ? fullscreen/* default */.Z.locals : undefined);

;// CONCATENATED MODULE: ./src/plugins/fullscreen/index.js
/**
 * @module converse-fullscreen
 * @license Mozilla Public License (MPLv2)
 * @copyright 2022, the Converse.js contributors
 */



public_converse.plugins.add('converse-fullscreen', {
  enabled: function enabled() {
    return isUniView();
  },
  initialize: function initialize() {
    shared_api.settings.extend({
      chatview_avatar_height: 50,
      chatview_avatar_width: 50,
      hide_open_bookmarks: true,
      show_controlbox_by_default: true,
      sticky_controlbox: true
    });
  }
});
;// CONCATENATED MODULE: ./src/index.js
/**
 * @description Converse.js (A browser based XMPP chat client)
 * @copyright 2021, The Converse developers
 * @license Mozilla Public License (MPLv2)
 */









/* START: Removable plugins
 * ------------------------
 * Any of the following plugin imports may be removed if the plugin is not needed
 */

 // Views for XEP-0050 Ad-Hoc commands
 // Views for XEP-0048 Bookmarks
 // Renders standalone chat boxes for single user chat
 // The control box


 // Views related to MUC
 // Allows chat boxes to be minimized



 // XEP-0357 Push Notifications
 // XEP-0077 In-band registration
 // Show currently open chat rooms



 // Allows chat boxes to be resized by dragging them

/* END: Removable components */

shared_converse.CustomElement = CustomElement;
var initialize = public_converse.initialize;
public_converse.initialize = function (settings, callback) {
  if (Array.isArray(settings.whitelisted_plugins)) {
    settings.whitelisted_plugins = settings.whitelisted_plugins.concat(VIEW_PLUGINS);
  } else {
    settings.whitelisted_plugins = VIEW_PLUGINS;
  }
  return initialize(settings, callback);
};
/* harmony default export */ const src = (public_converse);

/***/ }),

/***/ 783:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Native Javascript for Bootstrap 4 v2.0.27 | © dnp_theme | MIT-License
(function (root, factory) {
  if (true) {
    // AMD support:
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else { var bsn; }
})(this, function () {
  /* Native Javascript for Bootstrap 4 | Internal Utility Functions
  ----------------------------------------------------------------*/
  "use strict";

  // globals
  var globalObject = typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : this || window,
    DOC = document,
    HTML = DOC.documentElement,
    body = 'body',
    // allow the library to be used in <head>

    // Native Javascript for Bootstrap Global Object
    BSN = globalObject.BSN = {},
    supports = BSN.supports = [],
    // function toggle attributes
    dataToggle = 'data-toggle',
    dataDismiss = 'data-dismiss',
    dataSpy = 'data-spy',
    dataRide = 'data-ride',
    // components
    stringAlert = 'Alert',
    stringButton = 'Button',
    stringCarousel = 'Carousel',
    stringCollapse = 'Collapse',
    stringDropdown = 'Dropdown',
    stringModal = 'Modal',
    stringPopover = 'Popover',
    stringScrollSpy = 'ScrollSpy',
    stringTab = 'Tab',
    stringTooltip = 'Tooltip',
    stringToast = 'Toast',
    // options DATA API
    dataAutohide = 'data-autohide',
    databackdrop = 'data-backdrop',
    dataKeyboard = 'data-keyboard',
    dataTarget = 'data-target',
    dataInterval = 'data-interval',
    dataHeight = 'data-height',
    dataPause = 'data-pause',
    dataTitle = 'data-title',
    dataOriginalTitle = 'data-original-title',
    dataDismissible = 'data-dismissible',
    dataTrigger = 'data-trigger',
    dataAnimation = 'data-animation',
    dataContainer = 'data-container',
    dataPlacement = 'data-placement',
    dataDelay = 'data-delay',
    // option keys
    backdrop = 'backdrop',
    keyboard = 'keyboard',
    delay = 'delay',
    content = 'content',
    target = 'target',
    currentTarget = 'currentTarget',
    interval = 'interval',
    pause = 'pause',
    animation = 'animation',
    placement = 'placement',
    container = 'container',
    // box model
    offsetTop = 'offsetTop',
    offsetBottom = 'offsetBottom',
    offsetLeft = 'offsetLeft',
    scrollTop = 'scrollTop',
    scrollLeft = 'scrollLeft',
    clientWidth = 'clientWidth',
    clientHeight = 'clientHeight',
    offsetWidth = 'offsetWidth',
    offsetHeight = 'offsetHeight',
    innerWidth = 'innerWidth',
    innerHeight = 'innerHeight',
    scrollHeight = 'scrollHeight',
    scrollWidth = 'scrollWidth',
    height = 'height',
    // aria
    ariaExpanded = 'aria-expanded',
    ariaHidden = 'aria-hidden',
    ariaSelected = 'aria-selected',
    // event names
    clickEvent = 'click',
    focusEvent = 'focus',
    hoverEvent = 'hover',
    keydownEvent = 'keydown',
    keyupEvent = 'keyup',
    resizeEvent = 'resize',
    // passive
    scrollEvent = 'scroll',
    // passive
    mouseHover = 'onmouseleave' in DOC ? ['mouseenter', 'mouseleave'] : ['mouseover', 'mouseout'],
    // touch since 2.0.26
    touchEvents = {
      start: 'touchstart',
      end: 'touchend',
      move: 'touchmove'
    },
    // passive
    // originalEvents
    showEvent = 'show',
    shownEvent = 'shown',
    hideEvent = 'hide',
    hiddenEvent = 'hidden',
    closeEvent = 'close',
    closedEvent = 'closed',
    slidEvent = 'slid',
    slideEvent = 'slide',
    changeEvent = 'change',
    // other
    getAttribute = 'getAttribute',
    setAttribute = 'setAttribute',
    hasAttribute = 'hasAttribute',
    createElement = 'createElement',
    appendChild = 'appendChild',
    innerHTML = 'innerHTML',
    getElementsByTagName = 'getElementsByTagName',
    preventDefault = 'preventDefault',
    getBoundingClientRect = 'getBoundingClientRect',
    querySelectorAll = 'querySelectorAll',
    getElementsByCLASSNAME = 'getElementsByClassName',
    getComputedStyle = 'getComputedStyle',
    indexOf = 'indexOf',
    parentNode = 'parentNode',
    length = 'length',
    toLowerCase = 'toLowerCase',
    Transition = 'Transition',
    Duration = 'Duration',
    Webkit = 'Webkit',
    style = 'style',
    push = 'push',
    tabindex = 'tabindex',
    contains = 'contains',
    active = 'active',
    showClass = 'show',
    collapsing = 'collapsing',
    disabled = 'disabled',
    loading = 'loading',
    left = 'left',
    right = 'right',
    top = 'top',
    bottom = 'bottom',
    // tooltip / popover
    tipPositions = /\b(top|bottom|left|right)+/,
    // modal
    modalOverlay = 0,
    fixedTop = 'fixed-top',
    fixedBottom = 'fixed-bottom',
    // transitionEnd since 2.0.4
    supportTransitions = Webkit + Transition in HTML[style] || Transition[toLowerCase]() in HTML[style],
    transitionEndEvent = Webkit + Transition in HTML[style] ? Webkit[toLowerCase]() + Transition + 'End' : Transition[toLowerCase]() + 'end',
    transitionDuration = Webkit + Duration in HTML[style] ? Webkit[toLowerCase]() + Transition + Duration : Transition[toLowerCase]() + Duration,
    // set new focus element since 2.0.3
    setFocus = function (element) {
      element.focus ? element.focus() : element.setActive();
    },
    // class manipulation, since 2.0.0 requires polyfill.js
    addClass = function (element, classNAME) {
      element.classList.add(classNAME);
    },
    removeClass = function (element, classNAME) {
      element.classList.remove(classNAME);
    },
    hasClass = function (element, classNAME) {
      // since 2.0.0
      return element.classList[contains](classNAME);
    },
    // selection methods
    getElementsByClassName = function (element, classNAME) {
      // returns Array
      return [].slice.call(element[getElementsByCLASSNAME](classNAME));
    },
    queryElement = function (selector, parent) {
      var lookUp = parent ? parent : DOC;
      return typeof selector === 'object' ? selector : lookUp.querySelector(selector);
    },
    getClosest = function (element, selector) {
      //element is the element and selector is for the closest parent element to find
      // source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/
      var firstChar = selector.charAt(0),
        selectorSubstring = selector.substr(1);
      if (firstChar === '.') {
        // If selector is a class
        for (; element && element !== DOC; element = element[parentNode]) {
          // Get closest match
          if (queryElement(selector, element[parentNode]) !== null && hasClass(element, selectorSubstring)) {
            return element;
          }
        }
      } else if (firstChar === '#') {
        // If selector is an ID
        for (; element && element !== DOC; element = element[parentNode]) {
          // Get closest match
          if (element.id === selectorSubstring) {
            return element;
          }
        }
      }
      return false;
    },
    // event attach jQuery style / trigger  since 1.2.0
    on = function (element, event, handler, options) {
      options = options || false;
      element.addEventListener(event, handler, options);
    },
    off = function (element, event, handler, options) {
      options = options || false;
      element.removeEventListener(event, handler, options);
    },
    one = function (element, event, handler, options) {
      // one since 2.0.4
      on(element, event, function handlerWrapper(e) {
        handler(e);
        off(element, event, handlerWrapper, options);
      }, options);
    },
    // determine support for passive events
    supportPassive = function () {
      // Test via a getter in the options object to see if the passive property is accessed
      var result = false;
      try {
        var opts = Object.defineProperty({}, 'passive', {
          get: function () {
            result = true;
          }
        });
        one(globalObject, 'testPassive', null, opts);
      } catch (e) {}
      return result;
    }(),
    // event options
    // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
    passiveHandler = supportPassive ? {
      passive: true
    } : false,
    // transitions
    getTransitionDurationFromElement = function (element) {
      var duration = supportTransitions ? globalObject[getComputedStyle](element)[transitionDuration] : 0;
      duration = parseFloat(duration);
      duration = typeof duration === 'number' && !isNaN(duration) ? duration * 1000 : 0;
      return duration; // we take a short offset to make sure we fire on the next frame after animation
    },
    emulateTransitionEnd = function (element, handler) {
      // emulateTransitionEnd since 2.0.4
      var called = 0,
        duration = getTransitionDurationFromElement(element);
      duration ? one(element, transitionEndEvent, function (e) {
        !called && handler(e), called = 1;
      }) : setTimeout(function () {
        !called && handler(), called = 1;
      }, 17);
    },
    bootstrapCustomEvent = function (eventName, componentName, related) {
      var OriginalCustomEvent = new CustomEvent(eventName + '.bs.' + componentName);
      OriginalCustomEvent.relatedTarget = related;
      this.dispatchEvent(OriginalCustomEvent);
    },
    // tooltip / popover stuff
    getScroll = function () {
      // also Affix and ScrollSpy uses it
      return {
        y: globalObject.pageYOffset || HTML[scrollTop],
        x: globalObject.pageXOffset || HTML[scrollLeft]
      };
    },
    styleTip = function (link, element, position, parent) {
      // both popovers and tooltips (target,tooltip,placement,elementToAppendTo)
      var elementDimensions = {
          w: element[offsetWidth],
          h: element[offsetHeight]
        },
        windowWidth = HTML[clientWidth] || DOC[body][clientWidth],
        windowHeight = HTML[clientHeight] || DOC[body][clientHeight],
        rect = link[getBoundingClientRect](),
        scroll = parent === DOC[body] ? getScroll() : {
          x: parent[offsetLeft] + parent[scrollLeft],
          y: parent[offsetTop] + parent[scrollTop]
        },
        linkDimensions = {
          w: rect[right] - rect[left],
          h: rect[bottom] - rect[top]
        },
        isPopover = hasClass(element, 'popover'),
        topPosition,
        leftPosition,
        arrow = queryElement('.arrow', element),
        arrowTop,
        arrowLeft,
        arrowWidth,
        arrowHeight,
        halfTopExceed = rect[top] + linkDimensions.h / 2 - elementDimensions.h / 2 < 0,
        halfLeftExceed = rect[left] + linkDimensions.w / 2 - elementDimensions.w / 2 < 0,
        halfRightExceed = rect[left] + elementDimensions.w / 2 + linkDimensions.w / 2 >= windowWidth,
        halfBottomExceed = rect[top] + elementDimensions.h / 2 + linkDimensions.h / 2 >= windowHeight,
        topExceed = rect[top] - elementDimensions.h < 0,
        leftExceed = rect[left] - elementDimensions.w < 0,
        bottomExceed = rect[top] + elementDimensions.h + linkDimensions.h >= windowHeight,
        rightExceed = rect[left] + elementDimensions.w + linkDimensions.w >= windowWidth;

      // recompute position
      position = (position === left || position === right) && leftExceed && rightExceed ? top : position; // first, when both left and right limits are exceeded, we fall back to top|bottom
      position = position === top && topExceed ? bottom : position;
      position = position === bottom && bottomExceed ? top : position;
      position = position === left && leftExceed ? right : position;
      position = position === right && rightExceed ? left : position;

      // update tooltip/popover class
      element.className[indexOf](position) === -1 && (element.className = element.className.replace(tipPositions, position));

      // we check the computed width & height and update here
      arrowWidth = arrow[offsetWidth];
      arrowHeight = arrow[offsetHeight];

      // apply styling to tooltip or popover
      if (position === left || position === right) {
        // secondary|side positions
        if (position === left) {
          // LEFT
          leftPosition = rect[left] + scroll.x - elementDimensions.w - (isPopover ? arrowWidth : 0);
        } else {
          // RIGHT
          leftPosition = rect[left] + scroll.x + linkDimensions.w;
        }

        // adjust top and arrow
        if (halfTopExceed) {
          topPosition = rect[top] + scroll.y;
          arrowTop = linkDimensions.h / 2 - arrowWidth;
        } else if (halfBottomExceed) {
          topPosition = rect[top] + scroll.y - elementDimensions.h + linkDimensions.h;
          arrowTop = elementDimensions.h - linkDimensions.h / 2 - arrowWidth;
        } else {
          topPosition = rect[top] + scroll.y - elementDimensions.h / 2 + linkDimensions.h / 2;
          arrowTop = elementDimensions.h / 2 - (isPopover ? arrowHeight * 0.9 : arrowHeight / 2);
        }
      } else if (position === top || position === bottom) {
        // primary|vertical positions
        if (position === top) {
          // TOP
          topPosition = rect[top] + scroll.y - elementDimensions.h - (isPopover ? arrowHeight : 0);
        } else {
          // BOTTOM
          topPosition = rect[top] + scroll.y + linkDimensions.h;
        }
        // adjust left | right and also the arrow
        if (halfLeftExceed) {
          leftPosition = 0;
          arrowLeft = rect[left] + linkDimensions.w / 2 - arrowWidth;
        } else if (halfRightExceed) {
          leftPosition = windowWidth - elementDimensions.w * 1.01;
          arrowLeft = elementDimensions.w - (windowWidth - rect[left]) + linkDimensions.w / 2 - arrowWidth / 2;
        } else {
          leftPosition = rect[left] + scroll.x - elementDimensions.w / 2 + linkDimensions.w / 2;
          arrowLeft = elementDimensions.w / 2 - (isPopover ? arrowWidth : arrowWidth / 2);
        }
      }

      // apply style to tooltip/popover and its arrow
      element[style][top] = topPosition + 'px';
      element[style][left] = leftPosition + 'px';
      arrowTop && (arrow[style][top] = arrowTop + 'px');
      arrowLeft && (arrow[style][left] = arrowLeft + 'px');
    };
  BSN.version = '2.0.27';

  /* Native Javascript for Bootstrap 4 | Alert
  -------------------------------------------*/

  // ALERT DEFINITION
  // ================
  var Alert = function (element) {
    // initialization element
    element = queryElement(element);

    // bind, target alert, duration and stuff
    var self = this,
      component = 'alert',
      alert = getClosest(element, '.' + component),
      triggerHandler = function () {
        hasClass(alert, 'fade') ? emulateTransitionEnd(alert, transitionEndHandler) : transitionEndHandler();
      },
      // handlers
      clickHandler = function (e) {
        alert = getClosest(e[target], '.' + component);
        element = queryElement('[' + dataDismiss + '="' + component + '"]', alert);
        element && alert && (element === e[target] || element[contains](e[target])) && self.close();
      },
      transitionEndHandler = function () {
        bootstrapCustomEvent.call(alert, closedEvent, component);
        off(element, clickEvent, clickHandler); // detach it's listener
        alert[parentNode].removeChild(alert);
      };

    // public method
    this.close = function () {
      if (alert && element && hasClass(alert, showClass)) {
        bootstrapCustomEvent.call(alert, closeEvent, component);
        removeClass(alert, showClass);
        alert && triggerHandler();
      }
    };

    // init
    if (!(stringAlert in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, clickHandler);
    }
    element[stringAlert] = self;
  };

  // ALERT DATA API
  // ==============
  supports[push]([stringAlert, Alert, '[' + dataDismiss + '="alert"]']);

  /* Native Javascript for Bootstrap 4 | Button
  ---------------------------------------------*/

  // BUTTON DEFINITION
  // ===================
  var Button = function (element) {
    // initialization element
    element = queryElement(element);

    // constant
    var toggled = false,
      // toggled makes sure to prevent triggering twice the change.bs.button events

      // strings
      component = 'button',
      checked = 'checked',
      LABEL = 'LABEL',
      INPUT = 'INPUT',
      // private methods
      keyHandler = function (e) {
        var key = e.which || e.keyCode;
        key === 32 && e[target] === DOC.activeElement && toggle(e);
      },
      preventScroll = function (e) {
        var key = e.which || e.keyCode;
        key === 32 && e[preventDefault]();
      },
      toggle = function (e) {
        var label = e[target].tagName === LABEL ? e[target] : e[target][parentNode].tagName === LABEL ? e[target][parentNode] : null; // the .btn label

        if (!label) return; //react if a label or its immediate child is clicked

        var labels = getElementsByClassName(label[parentNode], 'btn'),
          // all the button group buttons
          input = label[getElementsByTagName](INPUT)[0];
        if (!input) return; // return if no input found

        // manage the dom manipulation
        if (input.type === 'checkbox') {
          //checkboxes
          if (!input[checked]) {
            addClass(label, active);
            input[getAttribute](checked);
            input[setAttribute](checked, checked);
            input[checked] = true;
          } else {
            removeClass(label, active);
            input[getAttribute](checked);
            input.removeAttribute(checked);
            input[checked] = false;
          }
          if (!toggled) {
            // prevent triggering the event twice
            toggled = true;
            bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input
            bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group
          }
        }

        if (input.type === 'radio' && !toggled) {
          // radio buttons
          // don't trigger if already active (the OR condition is a hack to check if the buttons were selected with key press and NOT mouse click)
          if (!input[checked] || e.screenX === 0 && e.screenY == 0) {
            addClass(label, active);
            addClass(label, focusEvent);
            input[setAttribute](checked, checked);
            input[checked] = true;
            bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input
            bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group

            toggled = true;
            for (var i = 0, ll = labels[length]; i < ll; i++) {
              var otherLabel = labels[i],
                otherInput = otherLabel[getElementsByTagName](INPUT)[0];
              if (otherLabel !== label && hasClass(otherLabel, active)) {
                removeClass(otherLabel, active);
                otherInput.removeAttribute(checked);
                otherInput[checked] = false;
                bootstrapCustomEvent.call(otherInput, changeEvent, component); // trigger the change
              }
            }
          }
        }

        setTimeout(function () {
          toggled = false;
        }, 50);
      },
      focusHandler = function (e) {
        addClass(e[target][parentNode], focusEvent);
      },
      blurHandler = function (e) {
        removeClass(e[target][parentNode], focusEvent);
      };

    // init
    if (!(stringButton in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, toggle);
      on(element, keyupEvent, keyHandler), on(element, keydownEvent, preventScroll);
      var allBtns = getElementsByClassName(element, 'btn');
      for (var i = 0; i < allBtns.length; i++) {
        var input = allBtns[i][getElementsByTagName](INPUT)[0];
        on(input, focusEvent, focusHandler), on(input, 'blur', blurHandler);
      }
    }

    // activate items on load
    var labelsToACtivate = getElementsByClassName(element, 'btn'),
      lbll = labelsToACtivate[length];
    for (var i = 0; i < lbll; i++) {
      !hasClass(labelsToACtivate[i], active) && queryElement('input:checked', labelsToACtivate[i]) && addClass(labelsToACtivate[i], active);
    }
    element[stringButton] = this;
  };

  // BUTTON DATA API
  // =================
  supports[push]([stringButton, Button, '[' + dataToggle + '="buttons"]']);

  /* Native Javascript for Bootstrap 4 | Collapse
  -----------------------------------------------*/

  // COLLAPSE DEFINITION
  // ===================
  var Collapse = function (element, options) {
    // initialization element
    element = queryElement(element);

    // set options
    options = options || {};

    // event targets and constants
    var accordion = null,
      collapse = null,
      self = this,
      accordionData = element[getAttribute]('data-parent'),
      activeCollapse,
      activeElement,
      // component strings
      component = 'collapse',
      collapsed = 'collapsed',
      isAnimating = 'isAnimating',
      // private methods
      openAction = function (collapseElement, toggle) {
        bootstrapCustomEvent.call(collapseElement, showEvent, component);
        collapseElement[isAnimating] = true;
        addClass(collapseElement, collapsing);
        removeClass(collapseElement, component);
        collapseElement[style][height] = collapseElement[scrollHeight] + 'px';
        emulateTransitionEnd(collapseElement, function () {
          collapseElement[isAnimating] = false;
          collapseElement[setAttribute](ariaExpanded, 'true');
          toggle[setAttribute](ariaExpanded, 'true');
          removeClass(collapseElement, collapsing);
          addClass(collapseElement, component);
          addClass(collapseElement, showClass);
          collapseElement[style][height] = '';
          bootstrapCustomEvent.call(collapseElement, shownEvent, component);
        });
      },
      closeAction = function (collapseElement, toggle) {
        bootstrapCustomEvent.call(collapseElement, hideEvent, component);
        collapseElement[isAnimating] = true;
        collapseElement[style][height] = collapseElement[scrollHeight] + 'px'; // set height first
        removeClass(collapseElement, component);
        removeClass(collapseElement, showClass);
        addClass(collapseElement, collapsing);
        collapseElement[offsetWidth]; // force reflow to enable transition
        collapseElement[style][height] = '0px';
        emulateTransitionEnd(collapseElement, function () {
          collapseElement[isAnimating] = false;
          collapseElement[setAttribute](ariaExpanded, 'false');
          toggle[setAttribute](ariaExpanded, 'false');
          removeClass(collapseElement, collapsing);
          addClass(collapseElement, component);
          collapseElement[style][height] = '';
          bootstrapCustomEvent.call(collapseElement, hiddenEvent, component);
        });
      },
      getTarget = function () {
        var href = element.href && element[getAttribute]('href'),
          parent = element[getAttribute](dataTarget),
          id = href || parent && parent.charAt(0) === '#' && parent;
        return id && queryElement(id);
      };

    // public methods
    this.toggle = function (e) {
      e[preventDefault]();
      if (!hasClass(collapse, showClass)) {
        self.show();
      } else {
        self.hide();
      }
    };
    this.hide = function () {
      if (collapse[isAnimating]) return;
      closeAction(collapse, element);
      addClass(element, collapsed);
    };
    this.show = function () {
      if (accordion) {
        activeCollapse = queryElement('.' + component + '.' + showClass, accordion);
        activeElement = activeCollapse && (queryElement('[' + dataTarget + '="#' + activeCollapse.id + '"]', accordion) || queryElement('[href="#' + activeCollapse.id + '"]', accordion));
      }
      if (!collapse[isAnimating] || activeCollapse && !activeCollapse[isAnimating]) {
        if (activeElement && activeCollapse !== collapse) {
          closeAction(activeCollapse, activeElement);
          addClass(activeElement, collapsed);
        }
        openAction(collapse, element);
        removeClass(element, collapsed);
      }
    };

    // init
    if (!(stringCollapse in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, self.toggle);
    }
    collapse = getTarget();
    collapse[isAnimating] = false; // when true it will prevent click handlers  
    accordion = queryElement(options.parent) || accordionData && getClosest(element, accordionData);
    element[stringCollapse] = self;
  };

  // COLLAPSE DATA API
  // =================
  supports[push]([stringCollapse, Collapse, '[' + dataToggle + '="collapse"]']);

  /* Native Javascript for Bootstrap 4 | Dropdown
  ----------------------------------------------*/

  // DROPDOWN DEFINITION
  // ===================
  var Dropdown = function (element, option) {
    // initialization element
    element = queryElement(element);

    // set option
    this.persist = option === true || element[getAttribute]('data-persist') === 'true' || false;

    // constants, event targets, strings
    var self = this,
      children = 'children',
      parent = element[parentNode],
      component = 'dropdown',
      open = 'open',
      relatedTarget = null,
      menu = queryElement('.dropdown-menu', parent),
      menuItems = function () {
        var set = menu[children],
          newSet = [];
        for (var i = 0; i < set[length]; i++) {
          set[i][children][length] && set[i][children][0].tagName === 'A' && newSet[push](set[i][children][0]);
          set[i].tagName === 'A' && newSet[push](set[i]);
        }
        return newSet;
      }(),
      // preventDefault on empty anchor links
      preventEmptyAnchor = function (anchor) {
        (anchor.href && anchor.href.slice(-1) === '#' || anchor[parentNode] && anchor[parentNode].href && anchor[parentNode].href.slice(-1) === '#') && this[preventDefault]();
      },
      // toggle dismissible events
      toggleDismiss = function () {
        var type = element[open] ? on : off;
        type(DOC, clickEvent, dismissHandler);
        type(DOC, keydownEvent, preventScroll);
        type(DOC, keyupEvent, keyHandler);
        type(DOC, focusEvent, dismissHandler, true);
      },
      // handlers
      dismissHandler = function (e) {
        var eventTarget = e[target],
          hasData = eventTarget && (eventTarget[getAttribute](dataToggle) || eventTarget[parentNode] && getAttribute in eventTarget[parentNode] && eventTarget[parentNode][getAttribute](dataToggle));
        if (e.type === focusEvent && (eventTarget === element || eventTarget === menu || menu[contains](eventTarget))) {
          return;
        }
        if ((eventTarget === menu || menu[contains](eventTarget)) && (self.persist || hasData)) {
          return;
        } else {
          relatedTarget = eventTarget === element || element[contains](eventTarget) ? element : null;
          hide();
        }
        preventEmptyAnchor.call(e, eventTarget);
      },
      clickHandler = function (e) {
        relatedTarget = element;
        show();
        preventEmptyAnchor.call(e, e[target]);
      },
      preventScroll = function (e) {
        var key = e.which || e.keyCode;
        if (key === 38 || key === 40) {
          e[preventDefault]();
        }
      },
      keyHandler = function (e) {
        var key = e.which || e.keyCode,
          activeItem = DOC.activeElement,
          idx = menuItems[indexOf](activeItem),
          isSameElement = activeItem === element,
          isInsideMenu = menu[contains](activeItem),
          isMenuItem = activeItem[parentNode] === menu || activeItem[parentNode][parentNode] === menu;
        if (isMenuItem) {
          // navigate up | down
          idx = isSameElement ? 0 : key === 38 ? idx > 1 ? idx - 1 : 0 : key === 40 ? idx < menuItems[length] - 1 ? idx + 1 : idx : idx;
          menuItems[idx] && setFocus(menuItems[idx]);
        }
        if ((menuItems[length] && isMenuItem // menu has items
        || !menuItems[length] && (isInsideMenu || isSameElement) // menu might be a form
        || !isInsideMenu // or the focused element is not in the menu at all
        ) && element[open] && key === 27 // menu must be open
        ) {
          self.toggle();
          relatedTarget = null;
        }
      },
      // private methods
      show = function () {
        bootstrapCustomEvent.call(parent, showEvent, component, relatedTarget);
        addClass(menu, showClass);
        addClass(parent, showClass);
        element[setAttribute](ariaExpanded, true);
        bootstrapCustomEvent.call(parent, shownEvent, component, relatedTarget);
        element[open] = true;
        off(element, clickEvent, clickHandler);
        setTimeout(function () {
          setFocus(menu[getElementsByTagName]('INPUT')[0] || element); // focus the first input item | element
          toggleDismiss();
        }, 1);
      },
      hide = function () {
        bootstrapCustomEvent.call(parent, hideEvent, component, relatedTarget);
        removeClass(menu, showClass);
        removeClass(parent, showClass);
        element[setAttribute](ariaExpanded, false);
        bootstrapCustomEvent.call(parent, hiddenEvent, component, relatedTarget);
        element[open] = false;
        toggleDismiss();
        setFocus(element);
        setTimeout(function () {
          on(element, clickEvent, clickHandler);
        }, 1);
      };

    // set initial state to closed
    element[open] = false;

    // public methods
    this.toggle = function () {
      if (hasClass(parent, showClass) && element[open]) {
        hide();
      } else {
        show();
      }
    };

    // init
    if (!(stringDropdown in element)) {
      // prevent adding event handlers twice
      !tabindex in menu && menu[setAttribute](tabindex, '0'); // Fix onblur on Chrome | Safari
      on(element, clickEvent, clickHandler);
    }
    element[stringDropdown] = self;
  };

  // DROPDOWN DATA API
  // =================
  supports[push]([stringDropdown, Dropdown, '[' + dataToggle + '="dropdown"]']);

  /* Native Javascript for Bootstrap 4 | Modal
  -------------------------------------------*/

  // MODAL DEFINITION
  // ===============
  var Modal = function (element, options) {
    // element can be the modal/triggering button

    // the modal (both JavaScript / DATA API init) / triggering button element (DATA API)
    element = queryElement(element);

    // strings
    var component = 'modal',
      staticString = 'static',
      modalTrigger = 'modalTrigger',
      paddingRight = 'paddingRight',
      modalBackdropString = 'modal-backdrop',
      isAnimating = 'isAnimating',
      // determine modal, triggering element
      btnCheck = element[getAttribute](dataTarget) || element[getAttribute]('href'),
      checkModal = queryElement(btnCheck),
      modal = hasClass(element, component) ? element : checkModal;
    if (hasClass(element, component)) {
      element = null;
    } // modal is now independent of it's triggering element

    if (!modal) {
      return;
    } // invalidate

    // set options
    options = options || {};
    this[keyboard] = options[keyboard] === false || modal[getAttribute](dataKeyboard) === 'false' ? false : true;
    this[backdrop] = options[backdrop] === staticString || modal[getAttribute](databackdrop) === staticString ? staticString : true;
    this[backdrop] = options[backdrop] === false || modal[getAttribute](databackdrop) === 'false' ? false : this[backdrop];
    this[animation] = hasClass(modal, 'fade') ? true : false;
    this[content] = options[content]; // JavaScript only

    // set an initial state of the modal
    modal[isAnimating] = false;

    // bind, constants, event targets and other vars
    var self = this,
      relatedTarget = null,
      bodyIsOverflowing,
      scrollBarWidth,
      overlay,
      overlayDelay,
      modalTimer,
      // also find fixed-top / fixed-bottom items
      fixedItems = getElementsByClassName(HTML, fixedTop).concat(getElementsByClassName(HTML, fixedBottom)),
      // private methods
      getWindowWidth = function () {
        var htmlRect = HTML[getBoundingClientRect]();
        return globalObject[innerWidth] || htmlRect[right] - Math.abs(htmlRect[left]);
      },
      setScrollbar = function () {
        var bodyStyle = globalObject[getComputedStyle](DOC[body]),
          bodyPad = parseInt(bodyStyle[paddingRight], 10),
          itemPad;
        if (bodyIsOverflowing) {
          DOC[body][style][paddingRight] = bodyPad + scrollBarWidth + 'px';
          modal[style][paddingRight] = scrollBarWidth + 'px';
          if (fixedItems[length]) {
            for (var i = 0; i < fixedItems[length]; i++) {
              itemPad = globalObject[getComputedStyle](fixedItems[i])[paddingRight];
              fixedItems[i][style][paddingRight] = parseInt(itemPad) + scrollBarWidth + 'px';
            }
          }
        }
      },
      resetScrollbar = function () {
        DOC[body][style][paddingRight] = '';
        modal[style][paddingRight] = '';
        if (fixedItems[length]) {
          for (var i = 0; i < fixedItems[length]; i++) {
            fixedItems[i][style][paddingRight] = '';
          }
        }
      },
      measureScrollbar = function () {
        // thx walsh
        var scrollDiv = DOC[createElement]('div'),
          widthValue;
        scrollDiv.className = component + '-scrollbar-measure'; // this is here to stay
        DOC[body][appendChild](scrollDiv);
        widthValue = scrollDiv[offsetWidth] - scrollDiv[clientWidth];
        DOC[body].removeChild(scrollDiv);
        return widthValue;
      },
      checkScrollbar = function () {
        bodyIsOverflowing = DOC[body][clientWidth] < getWindowWidth();
        scrollBarWidth = measureScrollbar();
      },
      createOverlay = function () {
        var newOverlay = DOC[createElement]('div');
        overlay = queryElement('.' + modalBackdropString);
        if (overlay === null) {
          newOverlay[setAttribute]('class', modalBackdropString + (self[animation] ? ' fade' : ''));
          overlay = newOverlay;
          DOC[body][appendChild](overlay);
        }
        modalOverlay = 1;
      },
      removeOverlay = function () {
        overlay = queryElement('.' + modalBackdropString);
        if (overlay && overlay !== null && typeof overlay === 'object') {
          modalOverlay = 0;
          DOC[body].removeChild(overlay);
          overlay = null;
        }
      },
      // triggers
      triggerShow = function () {
        setFocus(modal);
        modal[isAnimating] = false;
        bootstrapCustomEvent.call(modal, shownEvent, component, relatedTarget);
        on(globalObject, resizeEvent, self.update, passiveHandler);
        on(modal, clickEvent, dismissHandler);
        on(DOC, keydownEvent, keyHandler);
      },
      triggerHide = function () {
        modal[style].display = '';
        element && setFocus(element);
        bootstrapCustomEvent.call(modal, hiddenEvent, component);
        (function () {
          if (!getElementsByClassName(DOC, component + ' ' + showClass)[0]) {
            resetScrollbar();
            removeClass(DOC[body], component + '-open');
            overlay && hasClass(overlay, 'fade') ? (removeClass(overlay, showClass), emulateTransitionEnd(overlay, removeOverlay)) : removeOverlay();
            off(globalObject, resizeEvent, self.update, passiveHandler);
            off(modal, clickEvent, dismissHandler);
            off(DOC, keydownEvent, keyHandler);
          }
        })();
        modal[isAnimating] = false;
      },
      // handlers
      clickHandler = function (e) {
        if (modal[isAnimating]) return;
        var clickTarget = e[target];
        clickTarget = clickTarget[hasAttribute](dataTarget) || clickTarget[hasAttribute]('href') ? clickTarget : clickTarget[parentNode];
        if (clickTarget === element && !hasClass(modal, showClass)) {
          modal[modalTrigger] = element;
          relatedTarget = element;
          self.show();
          e[preventDefault]();
        }
      },
      keyHandler = function (e) {
        if (modal[isAnimating]) return;
        if (self[keyboard] && e.which == 27 && hasClass(modal, showClass)) {
          self.hide();
        }
      },
      dismissHandler = function (e) {
        if (modal[isAnimating]) return;
        var clickTarget = e[target];
        if (hasClass(modal, showClass) && (clickTarget[parentNode][getAttribute](dataDismiss) === component || clickTarget[getAttribute](dataDismiss) === component || clickTarget === modal && self[backdrop] !== staticString)) {
          self.hide();
          relatedTarget = null;
          e[preventDefault]();
        }
      };

    // public methods
    this.toggle = function () {
      if (hasClass(modal, showClass)) {
        this.hide();
      } else {
        this.show();
      }
    };
    this.show = function () {
      if (hasClass(modal, showClass) || modal[isAnimating]) {
        return;
      }
      clearTimeout(modalTimer);
      modalTimer = setTimeout(function () {
        modal[isAnimating] = true;
        bootstrapCustomEvent.call(modal, showEvent, component, relatedTarget);

        // we elegantly hide any opened modal
        var currentOpen = getElementsByClassName(DOC, component + ' ' + showClass)[0];
        if (currentOpen && currentOpen !== modal) {
          modalTrigger in currentOpen && currentOpen[modalTrigger][stringModal].hide();
          stringModal in currentOpen && currentOpen[stringModal].hide();
        }
        if (self[backdrop]) {
          !modalOverlay && !overlay && createOverlay();
        }
        if (overlay && !hasClass(overlay, showClass)) {
          overlay[offsetWidth]; // force reflow to enable trasition
          overlayDelay = getTransitionDurationFromElement(overlay);
          addClass(overlay, showClass);
        }
        setTimeout(function () {
          modal[style].display = 'block';
          checkScrollbar();
          setScrollbar();
          addClass(DOC[body], component + '-open');
          addClass(modal, showClass);
          modal[setAttribute](ariaHidden, false);
          hasClass(modal, 'fade') ? emulateTransitionEnd(modal, triggerShow) : triggerShow();
        }, supportTransitions && overlay && overlayDelay ? overlayDelay : 1);
      }, 1);
    };
    this.hide = function () {
      if (modal[isAnimating] || !hasClass(modal, showClass)) {
        return;
      }
      clearTimeout(modalTimer);
      modalTimer = setTimeout(function () {
        modal[isAnimating] = true;
        bootstrapCustomEvent.call(modal, hideEvent, component);
        overlay = queryElement('.' + modalBackdropString);
        overlayDelay = overlay && getTransitionDurationFromElement(overlay);
        removeClass(modal, showClass);
        modal[setAttribute](ariaHidden, true);
        setTimeout(function () {
          hasClass(modal, 'fade') ? emulateTransitionEnd(modal, triggerHide) : triggerHide();
        }, supportTransitions && overlay && overlayDelay ? overlayDelay : 2);
      }, 2);
    };
    this.setContent = function (content) {
      queryElement('.' + component + '-content', modal)[innerHTML] = content;
    };
    this.update = function () {
      if (hasClass(modal, showClass)) {
        checkScrollbar();
        setScrollbar();
      }
    };

    // init
    // prevent adding event handlers over and over
    // modal is independent of a triggering element
    if (!!element && !(stringModal in element)) {
      on(element, clickEvent, clickHandler);
    }
    if (!!self[content]) {
      self.setContent(self[content]);
    }
    if (element) {
      element[stringModal] = self;
      modal[modalTrigger] = element;
    } else {
      modal[stringModal] = self;
    }
  };

  // DATA API
  supports[push]([stringModal, Modal, '[' + dataToggle + '="modal"]']);

  /* Native Javascript for Bootstrap 4 | Popover
  ----------------------------------------------*/

  // POPOVER DEFINITION
  // ==================
  var Popover = function (element, options) {
    // initialization element
    element = queryElement(element);

    // set options
    options = options || {};

    // DATA API
    var triggerData = element[getAttribute](dataTrigger),
      // click / hover / focus
      animationData = element[getAttribute](dataAnimation),
      // true / false
      placementData = element[getAttribute](dataPlacement),
      dismissibleData = element[getAttribute](dataDismissible),
      delayData = element[getAttribute](dataDelay),
      containerData = element[getAttribute](dataContainer),
      // internal strings
      component = 'popover',
      template = 'template',
      trigger = 'trigger',
      classString = 'class',
      div = 'div',
      fade = 'fade',
      dataContent = 'data-content',
      dismissible = 'dismissible',
      closeBtn = '<button type="button" class="close">×</button>',
      // check container
      containerElement = queryElement(options[container]),
      containerDataElement = queryElement(containerData),
      // maybe the element is inside a modal
      modal = getClosest(element, '.modal'),
      // maybe the element is inside a fixed navbar
      navbarFixedTop = getClosest(element, '.' + fixedTop),
      navbarFixedBottom = getClosest(element, '.' + fixedBottom);

    // set instance options
    this[template] = options[template] ? options[template] : null; // JavaScript only
    this[trigger] = options[trigger] ? options[trigger] : triggerData || hoverEvent;
    this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade;
    this[placement] = options[placement] ? options[placement] : placementData || top;
    this[delay] = parseInt(options[delay] || delayData) || 200;
    this[dismissible] = options[dismissible] || dismissibleData === 'true' ? true : false;
    this[container] = containerElement ? containerElement : containerDataElement ? containerDataElement : navbarFixedTop ? navbarFixedTop : navbarFixedBottom ? navbarFixedBottom : modal ? modal : DOC[body];

    // bind, content
    var self = this,
      titleString = options.title || element[getAttribute](dataTitle) || null,
      contentString = options.content || element[getAttribute](dataContent) || null;
    if (!contentString && !this[template]) return; // invalidate

    // constants, vars
    var popover = null,
      timer = 0,
      placementSetting = this[placement],
      // handlers
      dismissibleHandler = function (e) {
        if (popover !== null && e[target] === queryElement('.close', popover)) {
          self.hide();
        }
      },
      // private methods
      removePopover = function () {
        self[container].removeChild(popover);
        timer = null;
        popover = null;
      },
      createPopover = function () {
        titleString = options.title || element[getAttribute](dataTitle);
        contentString = options.content || element[getAttribute](dataContent);
        // fixing https://github.com/thednp/bootstrap.native/issues/233
        contentString = !!contentString ? contentString.trim() : null;
        popover = DOC[createElement](div);

        // popover arrow
        var popoverArrow = DOC[createElement](div);
        popoverArrow[setAttribute](classString, 'arrow');
        popover[appendChild](popoverArrow);
        if (contentString !== null && self[template] === null) {
          //create the popover from data attributes

          popover[setAttribute]('role', 'tooltip');
          if (titleString !== null) {
            var popoverTitle = DOC[createElement]('h3');
            popoverTitle[setAttribute](classString, component + '-header');
            popoverTitle[innerHTML] = self[dismissible] ? titleString + closeBtn : titleString;
            popover[appendChild](popoverTitle);
          }

          //set popover content
          var popoverContent = DOC[createElement](div);
          popoverContent[setAttribute](classString, component + '-body');
          popoverContent[innerHTML] = self[dismissible] && titleString === null ? contentString + closeBtn : contentString;
          popover[appendChild](popoverContent);
        } else {
          // or create the popover from template
          var popoverTemplate = DOC[createElement](div);
          self[template] = self[template].trim();
          popoverTemplate[innerHTML] = self[template];
          popover[innerHTML] = popoverTemplate.firstChild[innerHTML];
        }

        //append to the container
        self[container][appendChild](popover);
        popover[style].display = 'block';
        popover[setAttribute](classString, component + ' bs-' + component + '-' + placementSetting + ' ' + self[animation]);
      },
      showPopover = function () {
        !hasClass(popover, showClass) && addClass(popover, showClass);
      },
      updatePopover = function () {
        styleTip(element, popover, placementSetting, self[container]);
      },
      // event toggle
      dismissHandlerToggle = function (type) {
        if (clickEvent == self[trigger] || 'focus' == self[trigger]) {
          !self[dismissible] && type(element, 'blur', self.hide);
        }
        self[dismissible] && type(DOC, clickEvent, dismissibleHandler);
        type(globalObject, resizeEvent, self.hide, passiveHandler);
      },
      // triggers
      showTrigger = function () {
        dismissHandlerToggle(on);
        bootstrapCustomEvent.call(element, shownEvent, component);
      },
      hideTrigger = function () {
        dismissHandlerToggle(off);
        removePopover();
        bootstrapCustomEvent.call(element, hiddenEvent, component);
      };

    // public methods / handlers
    this.toggle = function () {
      if (popover === null) {
        self.show();
      } else {
        self.hide();
      }
    };
    this.show = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (popover === null) {
          placementSetting = self[placement]; // we reset placement in all cases
          createPopover();
          updatePopover();
          showPopover();
          bootstrapCustomEvent.call(element, showEvent, component);
          !!self[animation] ? emulateTransitionEnd(popover, showTrigger) : showTrigger();
        }
      }, 20);
    };
    this.hide = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (popover && popover !== null && hasClass(popover, showClass)) {
          bootstrapCustomEvent.call(element, hideEvent, component);
          removeClass(popover, showClass);
          !!self[animation] ? emulateTransitionEnd(popover, hideTrigger) : hideTrigger();
        }
      }, self[delay]);
    };

    // init
    if (!(stringPopover in element)) {
      // prevent adding event handlers twice
      if (self[trigger] === hoverEvent) {
        on(element, mouseHover[0], self.show);
        if (!self[dismissible]) {
          on(element, mouseHover[1], self.hide);
        }
      } else if (clickEvent == self[trigger] || 'focus' == self[trigger]) {
        on(element, self[trigger], self.toggle);
      }
    }
    element[stringPopover] = self;
  };

  // POPOVER DATA API
  // ================
  supports[push]([stringPopover, Popover, '[' + dataToggle + '="popover"]']);

  /* Native Javascript for Bootstrap 4 | Tab
  -----------------------------------------*/

  // TAB DEFINITION
  // ==============
  var Tab = function (element, options) {
    // initialization element
    element = queryElement(element);

    // DATA API
    var heightData = element[getAttribute](dataHeight),
      // strings
      component = 'tab',
      height = 'height',
      float = 'float',
      isAnimating = 'isAnimating';

    // set options
    options = options || {};
    this[height] = supportTransitions ? options[height] || heightData === 'true' : false;

    // bind, event targets
    var self = this,
      next,
      tabs = getClosest(element, '.nav'),
      tabsContentContainer = false,
      dropdown = tabs && queryElement('.dropdown-toggle', tabs),
      activeTab,
      activeContent,
      nextContent,
      containerHeight,
      equalContents,
      nextHeight,
      // trigger
      triggerEnd = function () {
        tabsContentContainer[style][height] = '';
        removeClass(tabsContentContainer, collapsing);
        tabs[isAnimating] = false;
      },
      triggerShow = function () {
        if (tabsContentContainer) {
          // height animation
          if (equalContents) {
            triggerEnd();
          } else {
            setTimeout(function () {
              // enables height animation
              tabsContentContainer[style][height] = nextHeight + 'px'; // height animation
              tabsContentContainer[offsetWidth];
              emulateTransitionEnd(tabsContentContainer, triggerEnd);
            }, 50);
          }
        } else {
          tabs[isAnimating] = false;
        }
        bootstrapCustomEvent.call(next, shownEvent, component, activeTab);
      },
      triggerHide = function () {
        if (tabsContentContainer) {
          activeContent[style][float] = left;
          nextContent[style][float] = left;
          containerHeight = activeContent[scrollHeight];
        }
        addClass(nextContent, active);
        bootstrapCustomEvent.call(next, showEvent, component, activeTab);
        removeClass(activeContent, active);
        bootstrapCustomEvent.call(activeTab, hiddenEvent, component, next);
        if (tabsContentContainer) {
          nextHeight = nextContent[scrollHeight];
          equalContents = nextHeight === containerHeight;
          addClass(tabsContentContainer, collapsing);
          tabsContentContainer[style][height] = containerHeight + 'px'; // height animation
          tabsContentContainer[offsetHeight];
          activeContent[style][float] = '';
          nextContent[style][float] = '';
        }
        if (hasClass(nextContent, 'fade')) {
          setTimeout(function () {
            addClass(nextContent, showClass);
            emulateTransitionEnd(nextContent, triggerShow);
          }, 20);
        } else {
          triggerShow();
        }
      };
    if (!tabs) return; // invalidate

    // set default animation state
    tabs[isAnimating] = false;

    // private methods
    var getActiveTab = function () {
        var activeTabs = getElementsByClassName(tabs, active),
          activeTab;
        if (activeTabs[length] === 1 && !hasClass(activeTabs[0][parentNode], 'dropdown')) {
          activeTab = activeTabs[0];
        } else if (activeTabs[length] > 1) {
          activeTab = activeTabs[activeTabs[length] - 1];
        }
        return activeTab;
      },
      getActiveContent = function () {
        return queryElement(getActiveTab()[getAttribute]('href'));
      },
      // handler 
      clickHandler = function (e) {
        e[preventDefault]();
        next = e[currentTarget];
        !tabs[isAnimating] && !hasClass(next, active) && self.show();
      };

    // public method
    this.show = function () {
      // the tab we clicked is now the next tab
      next = next || element;
      nextContent = queryElement(next[getAttribute]('href')); //this is the actual object, the next tab content to activate
      activeTab = getActiveTab();
      activeContent = getActiveContent();
      tabs[isAnimating] = true;
      removeClass(activeTab, active);
      activeTab[setAttribute](ariaSelected, 'false');
      addClass(next, active);
      next[setAttribute](ariaSelected, 'true');
      if (dropdown) {
        if (!hasClass(element[parentNode], 'dropdown-menu')) {
          if (hasClass(dropdown, active)) removeClass(dropdown, active);
        } else {
          if (!hasClass(dropdown, active)) addClass(dropdown, active);
        }
      }
      bootstrapCustomEvent.call(activeTab, hideEvent, component, next);
      if (hasClass(activeContent, 'fade')) {
        removeClass(activeContent, showClass);
        emulateTransitionEnd(activeContent, triggerHide);
      } else {
        triggerHide();
      }
    };

    // init
    if (!(stringTab in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, clickHandler);
    }
    if (self[height]) {
      tabsContentContainer = getActiveContent()[parentNode];
    }
    element[stringTab] = self;
  };

  // TAB DATA API
  // ============
  supports[push]([stringTab, Tab, '[' + dataToggle + '="tab"]']);

  /* Native Javascript for Bootstrap | Initialize Data API
  --------------------------------------------------------*/
  var initializeDataAPI = function (constructor, collection) {
      for (var i = 0, l = collection[length]; i < l; i++) {
        new constructor(collection[i]);
      }
    },
    initCallback = BSN.initCallback = function (lookUp) {
      lookUp = lookUp || DOC;
      for (var i = 0, l = supports[length]; i < l; i++) {
        initializeDataAPI(supports[i][1], lookUp[querySelectorAll](supports[i][2]));
      }
    };

  // bulk initialize all components
  DOC[body] ? initCallback() : on(DOC, 'DOMContentLoaded', function () {
    initCallback();
  });
  return {
    Alert: Alert,
    Button: Button,
    Collapse: Collapse,
    Dropdown: Dropdown,
    Modal: Modal,
    Popover: Popover,
    Tab: Tab
  };
});

/***/ }),

/***/ 5399:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5282:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6160:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3015:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6172:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 7080:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2745:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3928:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4058:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9703:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9484:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6922:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8105:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1188:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9761:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 119:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9224:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9866:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4186:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4669:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3449:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6943:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5048:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8189:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8398:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8799:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6486:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 7593:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2543:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 782:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4311:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5382:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9769:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3638:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 7829:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3871:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2259:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5605:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9320:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2910:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9790:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8258:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8539);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2977);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3683:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var map = {
	"./af.js": [
		6898,
		9210
	],
	"./am.js": [
		8207,
		5073
	],
	"./ar-dz.js": [
		3630,
		9406
	],
	"./ar-iq.js": [
		7295,
		2990
	],
	"./ar-kw.js": [
		2799,
		9897
	],
	"./ar-ly.js": [
		4536,
		3521
	],
	"./ar-ma.js": [
		1830,
		5313
	],
	"./ar-sa.js": [
		1085,
		485
	],
	"./ar-tn.js": [
		6954,
		8040
	],
	"./ar.js": [
		7701,
		6755
	],
	"./az.js": [
		7991,
		4963
	],
	"./be.js": [
		1235,
		9478
	],
	"./bg.js": [
		2789,
		578
	],
	"./bi.js": [
		3158,
		2984
	],
	"./bm.js": [
		6227,
		2263
	],
	"./bn-bd.js": [
		5690,
		1351
	],
	"./bn.js": [
		673,
		280
	],
	"./bo.js": [
		3786,
		9950
	],
	"./br.js": [
		9332,
		760
	],
	"./bs.js": [
		1080,
		9833
	],
	"./ca.js": [
		5993,
		102
	],
	"./cs.js": [
		3607,
		7400
	],
	"./cv.js": [
		4310,
		4481
	],
	"./cy.js": [
		583,
		6740
	],
	"./da.js": [
		4353,
		2548
	],
	"./de-at.js": [
		6182,
		7175
	],
	"./de-ch.js": [
		8534,
		1679
	],
	"./de.js": [
		8696,
		52
	],
	"./dv.js": [
		6702,
		5569
	],
	"./el.js": [
		8561,
		1606
	],
	"./en-au.js": [
		8667,
		5485
	],
	"./en-ca.js": [
		297,
		4035
	],
	"./en-gb.js": [
		7116,
		6031
	],
	"./en-ie.js": [
		1671,
		8129
	],
	"./en-il.js": [
		3535,
		3463
	],
	"./en-in.js": [
		2842,
		6898
	],
	"./en-nz.js": [
		9221,
		8547
	],
	"./en-sg.js": [
		6316,
		1735
	],
	"./en-tt.js": [
		7297,
		6105
	],
	"./en.js": [
		8241,
		535
	],
	"./eo.js": [
		9383,
		5121
	],
	"./es-do.js": [
		3028,
		8758
	],
	"./es-mx.js": [
		5939,
		7416
	],
	"./es-pr.js": [
		8016,
		911
	],
	"./es-us.js": [
		5720,
		3208
	],
	"./es.js": [
		4040,
		3411
	],
	"./et.js": [
		7715,
		4153
	],
	"./eu.js": [
		274,
		1396
	],
	"./fa.js": [
		4578,
		5544
	],
	"./fi.js": [
		8710,
		2130
	],
	"./fo.js": [
		5267,
		8745
	],
	"./fr-ca.js": [
		3455,
		7363
	],
	"./fr-ch.js": [
		3127,
		7952
	],
	"./fr.js": [
		8457,
		1910
	],
	"./fy.js": [
		1316,
		6376
	],
	"./ga.js": [
		9163,
		688
	],
	"./gd.js": [
		8312,
		5050
	],
	"./gl.js": [
		9846,
		5818
	],
	"./gom-latn.js": [
		9011,
		825
	],
	"./gu.js": [
		281,
		3623
	],
	"./he.js": [
		6572,
		9372
	],
	"./hi.js": [
		9030,
		8010
	],
	"./hr.js": [
		6141,
		7419
	],
	"./ht.js": [
		337,
		5822
	],
	"./hu.js": [
		672,
		8214
	],
	"./hy-am.js": [
		9511,
		5407
	],
	"./id.js": [
		9105,
		9513
	],
	"./is.js": [
		7918,
		1194
	],
	"./it-ch.js": [
		8427,
		6010
	],
	"./it.js": [
		1608,
		1880
	],
	"./ja.js": [
		2398,
		1107
	],
	"./jv.js": [
		5880,
		4305
	],
	"./ka.js": [
		4454,
		5186
	],
	"./kk.js": [
		6835,
		5206
	],
	"./km.js": [
		7248,
		2475
	],
	"./kn.js": [
		1359,
		7523
	],
	"./ko.js": [
		1635,
		3446
	],
	"./ku.js": [
		5989,
		7024
	],
	"./ky.js": [
		3877,
		5055
	],
	"./lb.js": [
		5053,
		5215
	],
	"./lo.js": [
		3792,
		1204
	],
	"./lt.js": [
		4523,
		7899
	],
	"./lv.js": [
		932,
		631
	],
	"./me.js": [
		8099,
		145
	],
	"./mi.js": [
		4443,
		7454
	],
	"./mk.js": [
		8495,
		4951
	],
	"./ml.js": [
		8069,
		7679
	],
	"./mn.js": [
		4513,
		8618
	],
	"./mr.js": [
		31,
		5600
	],
	"./ms-my.js": [
		6054,
		882
	],
	"./ms.js": [
		4368,
		9095
	],
	"./mt.js": [
		1110,
		9665
	],
	"./my.js": [
		9126,
		5166
	],
	"./nb.js": [
		7172,
		646
	],
	"./ne.js": [
		1391,
		9030
	],
	"./nl-be.js": [
		3515,
		3155
	],
	"./nl.js": [
		6104,
		1520
	],
	"./nn.js": [
		4416,
		7050
	],
	"./oc-lnc.js": [
		7770,
		7203
	],
	"./pa-in.js": [
		3248,
		5850
	],
	"./pl.js": [
		4363,
		1211
	],
	"./pt-br.js": [
		4876,
		5274
	],
	"./pt.js": [
		5229,
		265
	],
	"./rn.js": [
		5013,
		4678
	],
	"./ro.js": [
		5818,
		8022
	],
	"./ru.js": [
		825,
		559
	],
	"./rw.js": [
		4611,
		3221
	],
	"./sd.js": [
		332,
		1298
	],
	"./se.js": [
		2046,
		1942
	],
	"./si.js": [
		3138,
		9333
	],
	"./sk.js": [
		1515,
		6783
	],
	"./sl.js": [
		8089,
		9625
	],
	"./sq.js": [
		1261,
		8603
	],
	"./sr-cyrl.js": [
		7863,
		3435
	],
	"./sr.js": [
		9729,
		7390
	],
	"./ss.js": [
		5500,
		9238
	],
	"./sv-fi.js": [
		1211,
		9997
	],
	"./sv.js": [
		4386,
		9652
	],
	"./sw.js": [
		1976,
		9733
	],
	"./ta.js": [
		7969,
		7645
	],
	"./te.js": [
		9326,
		7714
	],
	"./tet.js": [
		5292,
		555
	],
	"./tg.js": [
		2947,
		2446
	],
	"./th.js": [
		1337,
		1729
	],
	"./tk.js": [
		6541,
		5256
	],
	"./tl-ph.js": [
		2086,
		9443
	],
	"./tlh.js": [
		3618,
		2814
	],
	"./tr.js": [
		8698,
		8665
	],
	"./tzl.js": [
		4425,
		2843
	],
	"./tzm-latn.js": [
		5957,
		3933
	],
	"./tzm.js": [
		3262,
		4342
	],
	"./ug-cn.js": [
		6698,
		6890
	],
	"./uk.js": [
		110,
		1619
	],
	"./ur.js": [
		1826,
		9568
	],
	"./uz-latn.js": [
		8960,
		1110
	],
	"./uz.js": [
		4811,
		3153
	],
	"./vi.js": [
		3961,
		8073
	],
	"./x-pseudo.js": [
		9781,
		4423
	],
	"./yo.js": [
		8376,
		8692
	],
	"./zh-cn.js": [
		5038,
		9630
	],
	"./zh-hk.js": [
		8131,
		3755
	],
	"./zh-tw.js": [
		1904,
		6776
	],
	"./zh.js": [
		4713,
		8458
	]
};
function webpackAsyncContext(req) {
	if(!__webpack_require__.o(map, req)) {
		return Promise.resolve().then(() => {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		});
	}

	var ids = map[req], id = ids[0];
	return __webpack_require__.e(ids[1]).then(() => {
		return __webpack_require__.t(id, 7 | 16);
	});
}
webpackAsyncContext.keys = () => (Object.keys(map));
webpackAsyncContext.id = 3683;
module.exports = webpackAsyncContext;

/***/ }),

/***/ 3379:
/***/ ((module) => {

"use strict";


var stylesInDOM = [];
function getIndexByIdentifier(identifier) {
  var result = -1;
  for (var i = 0; i < stylesInDOM.length; i++) {
    if (stylesInDOM[i].identifier === identifier) {
      result = i;
      break;
    }
  }
  return result;
}
function modulesToDom(list, options) {
  var idCountMap = {};
  var identifiers = [];
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var count = idCountMap[id] || 0;
    var identifier = "".concat(id, " ").concat(count);
    idCountMap[id] = count + 1;
    var indexByIdentifier = getIndexByIdentifier(identifier);
    var obj = {
      css: item[1],
      media: item[2],
      sourceMap: item[3],
      supports: item[4],
      layer: item[5]
    };
    if (indexByIdentifier !== -1) {
      stylesInDOM[indexByIdentifier].references++;
      stylesInDOM[indexByIdentifier].updater(obj);
    } else {
      var updater = addElementStyle(obj, options);
      options.byIndex = i;
      stylesInDOM.splice(i, 0, {
        identifier: identifier,
        updater: updater,
        references: 1
      });
    }
    identifiers.push(identifier);
  }
  return identifiers;
}
function addElementStyle(obj, options) {
  var api = options.domAPI(options);
  api.update(obj);
  var updater = function updater(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
        return;
      }
      api.update(obj = newObj);
    } else {
      api.remove();
    }
  };
  return updater;
}
module.exports = function (list, options) {
  options = options || {};
  list = list || [];
  var lastIdentifiers = modulesToDom(list, options);
  return function update(newList) {
    newList = newList || [];
    for (var i = 0; i < lastIdentifiers.length; i++) {
      var identifier = lastIdentifiers[i];
      var index = getIndexByIdentifier(identifier);
      stylesInDOM[index].references--;
    }
    var newLastIdentifiers = modulesToDom(newList, options);
    for (var _i = 0; _i < lastIdentifiers.length; _i++) {
      var _identifier = lastIdentifiers[_i];
      var _index = getIndexByIdentifier(_identifier);
      if (stylesInDOM[_index].references === 0) {
        stylesInDOM[_index].updater();
        stylesInDOM.splice(_index, 1);
      }
    }
    lastIdentifiers = newLastIdentifiers;
  };
};

/***/ }),

/***/ 569:
/***/ ((module) => {

"use strict";


var memo = {};

/* istanbul ignore next  */
function getTarget(target) {
  if (typeof memo[target] === "undefined") {
    var styleTarget = document.querySelector(target);

    // Special case to return head of iframe instead of iframe itself
    if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
      try {
        // This will throw an exception if access to iframe is blocked
        // due to cross-origin restrictions
        styleTarget = styleTarget.contentDocument.head;
      } catch (e) {
        // istanbul ignore next
        styleTarget = null;
      }
    }
    memo[target] = styleTarget;
  }
  return memo[target];
}

/* istanbul ignore next  */
function insertBySelector(insert, style) {
  var target = getTarget(insert);
  if (!target) {
    throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
  }
  target.appendChild(style);
}
module.exports = insertBySelector;

/***/ }),

/***/ 9216:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function insertStyleElement(options) {
  var element = document.createElement("style");
  options.setAttributes(element, options.attributes);
  options.insert(element, options.options);
  return element;
}
module.exports = insertStyleElement;

/***/ }),

/***/ 3565:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/* istanbul ignore next  */
function setAttributesWithoutAttributes(styleElement) {
  var nonce =  true ? __webpack_require__.nc : 0;
  if (nonce) {
    styleElement.setAttribute("nonce", nonce);
  }
}
module.exports = setAttributesWithoutAttributes;

/***/ }),

/***/ 7795:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function apply(styleElement, options, obj) {
  var css = "";
  if (obj.supports) {
    css += "@supports (".concat(obj.supports, ") {");
  }
  if (obj.media) {
    css += "@media ".concat(obj.media, " {");
  }
  var needLayer = typeof obj.layer !== "undefined";
  if (needLayer) {
    css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
  }
  css += obj.css;
  if (needLayer) {
    css += "}";
  }
  if (obj.media) {
    css += "}";
  }
  if (obj.supports) {
    css += "}";
  }
  var sourceMap = obj.sourceMap;
  if (sourceMap && typeof btoa !== "undefined") {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  }

  // For old IE
  /* istanbul ignore if  */
  options.styleTagTransform(css, styleElement, options.options);
}
function removeStyleElement(styleElement) {
  // istanbul ignore if
  if (styleElement.parentNode === null) {
    return false;
  }
  styleElement.parentNode.removeChild(styleElement);
}

/* istanbul ignore next  */
function domAPI(options) {
  if (typeof document === "undefined") {
    return {
      update: function update() {},
      remove: function remove() {}
    };
  }
  var styleElement = options.insertStyleElement(options);
  return {
    update: function update(obj) {
      apply(styleElement, options, obj);
    },
    remove: function remove() {
      removeStyleElement(styleElement);
    }
  };
}
module.exports = domAPI;

/***/ }),

/***/ 4589:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function styleTagTransform(css, styleElement) {
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = css;
  } else {
    while (styleElement.firstChild) {
      styleElement.removeChild(styleElement.firstChild);
    }
    styleElement.appendChild(document.createTextNode(css));
  }
}
module.exports = styleTagTransform;

/***/ }),

/***/ 7521:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var map = {
	"./af/LC_MESSAGES/converse.po": [
		4534,
		5830
	],
	"./ar/LC_MESSAGES/converse.po": [
		4201,
		4469
	],
	"./bg/LC_MESSAGES/converse.po": [
		5384,
		2551
	],
	"./ca/LC_MESSAGES/converse.po": [
		122,
		1553
	],
	"./cs/LC_MESSAGES/converse.po": [
		3893,
		5301
	],
	"./da/LC_MESSAGES/converse.po": [
		7889,
		1163
	],
	"./de/LC_MESSAGES/converse.po": [
		1658,
		2895
	],
	"./el/LC_MESSAGES/converse.po": [
		7530,
		5524
	],
	"./eo/LC_MESSAGES/converse.po": [
		1758,
		2433
	],
	"./es/LC_MESSAGES/converse.po": [
		7790,
		8269
	],
	"./eu/LC_MESSAGES/converse.po": [
		9398,
		3103
	],
	"./fa/LC_MESSAGES/converse.po": [
		2897,
		321
	],
	"./fi/LC_MESSAGES/converse.po": [
		9583,
		7618
	],
	"./fr/LC_MESSAGES/converse.po": [
		5011,
		5129
	],
	"./gl/LC_MESSAGES/converse.po": [
		8816,
		777
	],
	"./he/LC_MESSAGES/converse.po": [
		6725,
		4363
	],
	"./hi/LC_MESSAGES/converse.po": [
		411,
		4468
	],
	"./hu/LC_MESSAGES/converse.po": [
		2825,
		6239
	],
	"./id/LC_MESSAGES/converse.po": [
		6042,
		6678
	],
	"./it/LC_MESSAGES/converse.po": [
		3741,
		3719
	],
	"./ja/LC_MESSAGES/converse.po": [
		6893,
		6249
	],
	"./lt/LC_MESSAGES/converse.po": [
		5176,
		513
	],
	"./mr/LC_MESSAGES/converse.po": [
		6292,
		1784
	],
	"./nb/LC_MESSAGES/converse.po": [
		8467,
		473
	],
	"./nl/LC_MESSAGES/converse.po": [
		8544,
		2473
	],
	"./nl_BE/LC_MESSAGES/converse.po": [
		8133,
		8131
	],
	"./oc/LC_MESSAGES/converse.po": [
		8857,
		5500
	],
	"./pl/LC_MESSAGES/converse.po": [
		2503,
		3606
	],
	"./pt/LC_MESSAGES/converse.po": [
		1132,
		6227
	],
	"./pt_BR/LC_MESSAGES/converse.po": [
		6380,
		1455
	],
	"./ro/LC_MESSAGES/converse.po": [
		9740,
		3539
	],
	"./ru/LC_MESSAGES/converse.po": [
		2276,
		7917
	],
	"./sv/LC_MESSAGES/converse.po": [
		1025,
		8859
	],
	"./th/LC_MESSAGES/converse.po": [
		4297,
		457
	],
	"./tr/LC_MESSAGES/converse.po": [
		2266,
		4195
	],
	"./ug/LC_MESSAGES/converse.po": [
		3915,
		8676
	],
	"./uk/LC_MESSAGES/converse.po": [
		9642,
		7979
	],
	"./vi/LC_MESSAGES/converse.po": [
		1298,
		2110
	],
	"./zh_CN/LC_MESSAGES/converse.po": [
		9771,
		3325
	],
	"./zh_TW/LC_MESSAGES/converse.po": [
		4133,
		1458
	]
};
function webpackAsyncContext(req) {
	if(!__webpack_require__.o(map, req)) {
		return Promise.resolve().then(() => {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		});
	}

	var ids = map[req], id = ids[0];
	return __webpack_require__.e(ids[1]).then(() => {
		return __webpack_require__.t(id, 3 | 16);
	});
}
webpackAsyncContext.keys = () => (Object.keys(map));
webpackAsyncContext.id = 7521;
module.exports = webpackAsyncContext;

/***/ }),

/***/ 4038:
/***/ ((module) => {

"use strict";
module.exports = localforage;

/***/ }),

/***/ 8563:
/***/ ((module) => {

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }
  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}
function _asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 4662:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var toPropertyKey = __webpack_require__(8288);
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;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 6049:
/***/ ((module) => {

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 4737:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _typeof = (__webpack_require__(4741)["default"]);
function _regeneratorRuntime() {
  "use strict";

  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
    return exports;
  }, module.exports.__esModule = true, module.exports["default"] = module.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;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 6043:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _typeof = (__webpack_require__(4741)["default"]);
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);
}
module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 8288:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _typeof = (__webpack_require__(4741)["default"]);
var toPrimitive = __webpack_require__(6043);
function _toPropertyKey(arg) {
  var key = toPrimitive(arg, "string");
  return _typeof(key) === "symbol" ? key : String(key);
}
module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 4741:
/***/ ((module) => {

function _typeof(obj) {
  "@babel/helpers - typeof";

  return (module.exports = _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;
  }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 80:
/***/ ((module, __unused_webpack_exports, __webpack_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);
}
// TODO(Babel 8): Remove this file.

var runtime = __webpack_require__(4737)();
module.exports = runtime;

// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  if ((typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis)) === "object") {
    globalThis.regeneratorRuntime = runtime;
  } else {
    Function("r", "regeneratorRuntime = r")(runtime);
  }
}

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			id: moduleId,
/******/ 			loaded: false,
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/create fake namespace object */
/******/ 	(() => {
/******/ 		var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
/******/ 		var leafPrototypes;
/******/ 		// create a fake namespace object
/******/ 		// mode & 1: value is a module id, require it
/******/ 		// mode & 2: merge all properties of value into the ns
/******/ 		// mode & 4: return value when already ns object
/******/ 		// mode & 16: return value when it's Promise-like
/******/ 		// mode & 8|1: behave like require
/******/ 		__webpack_require__.t = function(value, mode) {
/******/ 			if(mode & 1) value = this(value);
/******/ 			if(mode & 8) return value;
/******/ 			if(typeof value === 'object' && value) {
/******/ 				if((mode & 4) && value.__esModule) return value;
/******/ 				if((mode & 16) && typeof value.then === 'function') return value;
/******/ 			}
/******/ 			var ns = Object.create(null);
/******/ 			__webpack_require__.r(ns);
/******/ 			var def = {};
/******/ 			leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
/******/ 			for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
/******/ 				Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
/******/ 			}
/******/ 			def['default'] = () => (value);
/******/ 			__webpack_require__.d(ns, def);
/******/ 			return ns;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/ensure chunk */
/******/ 	(() => {
/******/ 		__webpack_require__.f = {};
/******/ 		// This file contains only the entry chunk.
/******/ 		// The chunk loading function for additional chunks
/******/ 		__webpack_require__.e = (chunkId) => {
/******/ 			return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ 				__webpack_require__.f[key](chunkId, promises);
/******/ 				return promises;
/******/ 			}, []));
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/get javascript chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks
/******/ 		__webpack_require__.u = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return "" + {"52":"locales/dayjs/de-js","102":"locales/dayjs/ca-js","145":"locales/dayjs/me-js","265":"locales/dayjs/pt-js","280":"locales/dayjs/bn-js","321":"locales/fa-LC_MESSAGES-converse-po","457":"locales/th-LC_MESSAGES-converse-po","473":"locales/nb-LC_MESSAGES-converse-po","485":"locales/dayjs/ar-sa-js","513":"locales/lt-LC_MESSAGES-converse-po","535":"locales/dayjs/en-js","555":"locales/dayjs/tet-js","559":"locales/dayjs/ru-js","578":"locales/dayjs/bg-js","631":"locales/dayjs/lv-js","646":"locales/dayjs/nb-js","688":"locales/dayjs/ga-js","760":"locales/dayjs/br-js","777":"locales/gl-LC_MESSAGES-converse-po","825":"locales/dayjs/gom-latn-js","882":"locales/dayjs/ms-my-js","911":"locales/dayjs/es-pr-js","1107":"locales/dayjs/ja-js","1110":"locales/dayjs/uz-latn-js","1163":"locales/da-LC_MESSAGES-converse-po","1194":"locales/dayjs/is-js","1204":"locales/dayjs/lo-js","1211":"locales/dayjs/pl-js","1298":"locales/dayjs/sd-js","1351":"locales/dayjs/bn-bd-js","1396":"locales/dayjs/eu-js","1455":"locales/pt_BR-LC_MESSAGES-converse-po","1458":"locales/zh_TW-LC_MESSAGES-converse-po","1520":"locales/dayjs/nl-js","1553":"locales/ca-LC_MESSAGES-converse-po","1606":"locales/dayjs/el-js","1619":"locales/dayjs/uk-js","1679":"locales/dayjs/de-ch-js","1729":"locales/dayjs/th-js","1735":"locales/dayjs/en-sg-js","1784":"locales/mr-LC_MESSAGES-converse-po","1880":"locales/dayjs/it-js","1910":"locales/dayjs/fr-js","1942":"locales/dayjs/se-js","2110":"locales/vi-LC_MESSAGES-converse-po","2130":"locales/dayjs/fi-js","2263":"locales/dayjs/bm-js","2433":"locales/eo-LC_MESSAGES-converse-po","2446":"locales/dayjs/tg-js","2473":"locales/nl-LC_MESSAGES-converse-po","2475":"locales/dayjs/km-js","2548":"locales/dayjs/da-js","2551":"locales/bg-LC_MESSAGES-converse-po","2814":"locales/dayjs/tlh-js","2843":"locales/dayjs/tzl-js","2895":"locales/de-LC_MESSAGES-converse-po","2984":"locales/dayjs/bi-js","2990":"locales/dayjs/ar-iq-js","3103":"locales/eu-LC_MESSAGES-converse-po","3153":"locales/dayjs/uz-js","3155":"locales/dayjs/nl-be-js","3208":"locales/dayjs/es-us-js","3221":"locales/dayjs/rw-js","3325":"locales/zh_CN-LC_MESSAGES-converse-po","3411":"locales/dayjs/es-js","3435":"locales/dayjs/sr-cyrl-js","3446":"locales/dayjs/ko-js","3463":"locales/dayjs/en-il-js","3521":"locales/dayjs/ar-ly-js","3539":"locales/ro-LC_MESSAGES-converse-po","3606":"locales/pl-LC_MESSAGES-converse-po","3623":"locales/dayjs/gu-js","3719":"locales/it-LC_MESSAGES-converse-po","3755":"locales/dayjs/zh-hk-js","3933":"locales/dayjs/tzm-latn-js","4035":"locales/dayjs/en-ca-js","4153":"locales/dayjs/et-js","4195":"locales/tr-LC_MESSAGES-converse-po","4305":"locales/dayjs/jv-js","4342":"locales/dayjs/tzm-js","4363":"locales/he-LC_MESSAGES-converse-po","4423":"locales/dayjs/x-pseudo-js","4468":"locales/hi-LC_MESSAGES-converse-po","4469":"locales/ar-LC_MESSAGES-converse-po","4481":"locales/dayjs/cv-js","4610":"emojis","4678":"locales/dayjs/rn-js","4951":"locales/dayjs/mk-js","4963":"locales/dayjs/az-js","5050":"locales/dayjs/gd-js","5055":"locales/dayjs/ky-js","5073":"locales/dayjs/am-js","5121":"locales/dayjs/eo-js","5129":"locales/fr-LC_MESSAGES-converse-po","5166":"locales/dayjs/my-js","5186":"locales/dayjs/ka-js","5206":"locales/dayjs/kk-js","5215":"locales/dayjs/lb-js","5256":"locales/dayjs/tk-js","5274":"locales/dayjs/pt-br-js","5301":"locales/cs-LC_MESSAGES-converse-po","5313":"locales/dayjs/ar-ma-js","5407":"locales/dayjs/hy-am-js","5485":"locales/dayjs/en-au-js","5500":"locales/oc-LC_MESSAGES-converse-po","5524":"locales/el-LC_MESSAGES-converse-po","5544":"locales/dayjs/fa-js","5569":"locales/dayjs/dv-js","5600":"locales/dayjs/mr-js","5818":"locales/dayjs/gl-js","5822":"locales/dayjs/ht-js","5830":"locales/af-LC_MESSAGES-converse-po","5850":"locales/dayjs/pa-in-js","6010":"locales/dayjs/it-ch-js","6031":"locales/dayjs/en-gb-js","6105":"locales/dayjs/en-tt-js","6227":"locales/pt-LC_MESSAGES-converse-po","6239":"locales/hu-LC_MESSAGES-converse-po","6249":"locales/ja-LC_MESSAGES-converse-po","6376":"locales/dayjs/fy-js","6678":"locales/id-LC_MESSAGES-converse-po","6740":"locales/dayjs/cy-js","6755":"locales/dayjs/ar-js","6776":"locales/dayjs/zh-tw-js","6783":"locales/dayjs/sk-js","6890":"locales/dayjs/ug-cn-js","6898":"locales/dayjs/en-in-js","7024":"locales/dayjs/ku-js","7050":"locales/dayjs/nn-js","7175":"locales/dayjs/de-at-js","7203":"locales/dayjs/oc-lnc-js","7363":"locales/dayjs/fr-ca-js","7390":"locales/dayjs/sr-js","7400":"locales/dayjs/cs-js","7416":"locales/dayjs/es-mx-js","7419":"locales/dayjs/hr-js","7454":"locales/dayjs/mi-js","7523":"locales/dayjs/kn-js","7618":"locales/fi-LC_MESSAGES-converse-po","7645":"locales/dayjs/ta-js","7679":"locales/dayjs/ml-js","7714":"locales/dayjs/te-js","7899":"locales/dayjs/lt-js","7917":"locales/ru-LC_MESSAGES-converse-po","7952":"locales/dayjs/fr-ch-js","7979":"locales/uk-LC_MESSAGES-converse-po","8010":"locales/dayjs/hi-js","8022":"locales/dayjs/ro-js","8040":"locales/dayjs/ar-tn-js","8073":"locales/dayjs/vi-js","8129":"locales/dayjs/en-ie-js","8131":"locales/nl_BE-LC_MESSAGES-converse-po","8214":"locales/dayjs/hu-js","8269":"locales/es-LC_MESSAGES-converse-po","8458":"locales/dayjs/zh-js","8547":"locales/dayjs/en-nz-js","8603":"locales/dayjs/sq-js","8618":"locales/dayjs/mn-js","8665":"locales/dayjs/tr-js","8676":"locales/ug-LC_MESSAGES-converse-po","8692":"locales/dayjs/yo-js","8745":"locales/dayjs/fo-js","8758":"locales/dayjs/es-do-js","8859":"locales/sv-LC_MESSAGES-converse-po","9030":"locales/dayjs/ne-js","9095":"locales/dayjs/ms-js","9210":"locales/dayjs/af-js","9238":"locales/dayjs/ss-js","9333":"locales/dayjs/si-js","9372":"locales/dayjs/he-js","9406":"locales/dayjs/ar-dz-js","9443":"locales/dayjs/tl-ph-js","9478":"locales/dayjs/be-js","9513":"locales/dayjs/id-js","9568":"locales/dayjs/ur-js","9625":"locales/dayjs/sl-js","9630":"locales/dayjs/zh-cn-js","9652":"locales/dayjs/sv-js","9665":"locales/dayjs/mt-js","9733":"locales/dayjs/sw-js","9833":"locales/dayjs/bs-js","9897":"locales/dayjs/ar-kw-js","9950":"locales/dayjs/bo-js","9997":"locales/dayjs/sv-fi-js"}[chunkId] + ".js";
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/get mini-css chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks
/******/ 		__webpack_require__.miniCssF = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return undefined;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/load script */
/******/ 	(() => {
/******/ 		var inProgress = {};
/******/ 		var dataWebpackPrefix = "converse.js:";
/******/ 		// loadScript function to load a script via script tag
/******/ 		__webpack_require__.l = (url, done, key, chunkId) => {
/******/ 			if(inProgress[url]) { inProgress[url].push(done); return; }
/******/ 			var script, needAttach;
/******/ 			if(key !== undefined) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				for(var i = 0; i < scripts.length; i++) {
/******/ 					var s = scripts[i];
/******/ 					if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
/******/ 				}
/******/ 			}
/******/ 			if(!script) {
/******/ 				needAttach = true;
/******/ 				script = document.createElement('script');
/******/ 		
/******/ 				script.charset = 'utf-8';
/******/ 				script.timeout = 120;
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/ 				script.setAttribute("data-webpack", dataWebpackPrefix + key);
/******/ 		
/******/ 				script.src = url;
/******/ 			}
/******/ 			inProgress[url] = [done];
/******/ 			var onScriptComplete = (prev, event) => {
/******/ 				// avoid mem leaks in IE.
/******/ 				script.onerror = script.onload = null;
/******/ 				clearTimeout(timeout);
/******/ 				var doneFns = inProgress[url];
/******/ 				delete inProgress[url];
/******/ 				script.parentNode && script.parentNode.removeChild(script);
/******/ 				doneFns && doneFns.forEach((fn) => (fn(event)));
/******/ 				if(prev) return prev(event);
/******/ 			}
/******/ 			var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
/******/ 			script.onerror = onScriptComplete.bind(null, script.onerror);
/******/ 			script.onload = onScriptComplete.bind(null, script.onload);
/******/ 			needAttach && document.head.appendChild(script);
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/node module decorator */
/******/ 	(() => {
/******/ 		__webpack_require__.nmd = (module) => {
/******/ 			module.paths = [];
/******/ 			if (!module.children) module.children = [];
/******/ 			return module;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/publicPath */
/******/ 	(() => {
/******/ 		var scriptUrl;
/******/ 		if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
/******/ 		var document = __webpack_require__.g.document;
/******/ 		if (!scriptUrl && document) {
/******/ 			if (document.currentScript)
/******/ 				scriptUrl = document.currentScript.src;
/******/ 			if (!scriptUrl) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				if(scripts.length) {
/******/ 					var i = scripts.length - 1;
/******/ 					while (i > -1 && !scriptUrl) scriptUrl = scripts[i--].src;
/******/ 				}
/******/ 			}
/******/ 		}
/******/ 		// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
/******/ 		// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
/******/ 		if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
/******/ 		scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
/******/ 		__webpack_require__.p = scriptUrl;
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/ 		
/******/ 		// object to store loaded and loading chunks
/******/ 		// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 		// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ 		var installedChunks = {
/******/ 			7335: 0
/******/ 		};
/******/ 		
/******/ 		__webpack_require__.f.j = (chunkId, promises) => {
/******/ 				// JSONP chunk loading for javascript
/******/ 				var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ 				if(installedChunkData !== 0) { // 0 means "already installed".
/******/ 		
/******/ 					// a Promise means "currently loading".
/******/ 					if(installedChunkData) {
/******/ 						promises.push(installedChunkData[2]);
/******/ 					} else {
/******/ 						if(true) { // all chunks have JS
/******/ 							// setup Promise in chunk cache
/******/ 							var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
/******/ 							promises.push(installedChunkData[2] = promise);
/******/ 		
/******/ 							// start chunk loading
/******/ 							var url = __webpack_require__.p + __webpack_require__.u(chunkId);
/******/ 							// create error before stack unwound to get useful stacktrace later
/******/ 							var error = new Error();
/******/ 							var loadingEnded = (event) => {
/******/ 								if(__webpack_require__.o(installedChunks, chunkId)) {
/******/ 									installedChunkData = installedChunks[chunkId];
/******/ 									if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
/******/ 									if(installedChunkData) {
/******/ 										var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 										var realSrc = event && event.target && event.target.src;
/******/ 										error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 										error.name = 'ChunkLoadError';
/******/ 										error.type = errorType;
/******/ 										error.request = realSrc;
/******/ 										installedChunkData[1](error);
/******/ 									}
/******/ 								}
/******/ 							};
/******/ 							__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
/******/ 						}
/******/ 					}
/******/ 				}
/******/ 		};
/******/ 		
/******/ 		// no prefetching
/******/ 		
/******/ 		// no preloaded
/******/ 		
/******/ 		// no HMR
/******/ 		
/******/ 		// no HMR manifest
/******/ 		
/******/ 		// no on chunks loaded
/******/ 		
/******/ 		// install a JSONP callback for chunk loading
/******/ 		var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			// add "moreModules" to the modules object,
/******/ 			// then flag all "chunkIds" as loaded and fire callback
/******/ 			var moduleId, chunkId, i = 0;
/******/ 			if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ 				for(moduleId in moreModules) {
/******/ 					if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 						__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 					}
/******/ 				}
/******/ 				if(runtime) var result = runtime(__webpack_require__);
/******/ 			}
/******/ 			if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ 			for(;i < chunkIds.length; i++) {
/******/ 				chunkId = chunkIds[i];
/******/ 				if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 					installedChunks[chunkId][0]();
/******/ 				}
/******/ 				installedChunks[chunkId] = 0;
/******/ 			}
/******/ 		
/******/ 		}
/******/ 		
/******/ 		var chunkLoadingGlobal = self["webpackChunkconverse_js"] = self["webpackChunkconverse_js"] || [];
/******/ 		chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ 		chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/nonce */
/******/ 	(() => {
/******/ 		__webpack_require__.nc = undefined;
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// Converse.js
// https://conversejs.org
//
// Copyright (c) 2020, the Converse.js contributors
// Licensed under the Mozilla Public License (MPLv2)
//
// Webpack entry file
//
// The purpose of this file is to provide an initial temporary public API
// (window.converse) for **before** the rest of converse.js is loaded so
// that we can set the __webpack_public_path__ global variable.
//
// Once the rest converse.js has been loaded, window.converse will be replaced
// with the full-fledged public API.

var plugins = {};
var converse = {
  plugins: {
    add: function add(name, plugin) {
      if (plugins[name] !== undefined) {
        throw new TypeError("Error: plugin with name \"".concat(name, "\" has already been ") + 'registered!');
      }
      plugins[name] = plugin;
    }
  },
  initialize: function initialize() {
    var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return converse.load(settings).initialize(settings);
  },
  /**
   * Public API method which explicitly loads Converse and allows you the
   * possibility to pass in configuration settings which need to be defined
   * before loading. Currently this is only the [assets_path](https://conversejs.org/docs/html/configuration.html#assets_path)
   * setting.
   *
   * If not called explicitly, this method will be called implicitly once
   * {@link converse.initialize} is called.
   *
   * In most cases, you probably don't need to explicitly call this method,
   * however, until converse.js has been loaded you won't have access to the
   * utility methods and globals exposed via {@link converse.env}. So if you
   * need to access `converse.env` outside of any plugins and before
   * `converse.initialize` has been called, then you need to call
   * `converse.load` first.
   *
   * @memberOf converse
   * @method load
   * @param { object } settings A map of configuration-settings that are needed at load time.
   * @example
   * converse.load({assets_path: '/path/to/assets/'});
   */
  load: function load() {
    var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (settings.assets_path) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      __webpack_require__.p = settings.assets_path; // eslint-disable-line no-undef
    }

    __webpack_require__(9265);
    Object.keys(plugins).forEach(function (name) {
      return converse.plugins.add(name, plugins[name]);
    });
    return converse;
  }
};
window['converse'] = converse;

/**
 * Once Converse.js has loaded, it'll dispatch a custom event with the name `converse-loaded`.
 * You can listen for this event in order to be informed as soon as converse.js has been
 * loaded and parsed, which would mean it's safe to call `converse.initialize`.
 * @event converse-loaded
 * @example window.addEventListener('converse-loaded', () => converse.initialize());
 */
var ev = new CustomEvent('converse-loaded', {
  'detail': {
    converse: converse
  }
});
window.dispatchEvent(ev);
/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = ((/* unused pure expression or super */ null && (converse)));
})();

/******/ })()
;
//# sourceMappingURL=converse-no-dependencies.js.map