strophe.js
Version:
Strophe.js is an XMPP library for JavaScript
5 lines • 53.1 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Strophe={})}(this,(function(e){"use strict";const t={HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",SERVER:"jabber:server",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},s={tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"]},n={ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12,RECONNECTING:13},i={BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},r={DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},o={NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11};let a=r.DEBUG;const l={setLogLevel(e){if(e<r.DEBUG||e>r.FATAL)throw new Error("Invalid log level supplied to setLogLevel");a=e},log(e,t){var s;if(!(e<a))if(e>=r.ERROR)null===(s=console)||void 0===s||s.error(t);else if(e===r.INFO){var n;null===(n=console)||void 0===n||n.info(t)}else if(e===r.WARN){var i;null===(i=console)||void 0===i||i.warn(t)}else if(e===r.DEBUG){var o;null===(o=console)||void 0===o||o.debug(t)}},debug(e){this.log(r.DEBUG,e)},info(e){this.log(r.INFO,e)},warn(e){this.log(r.WARN,e)},error(e){this.log(r.ERROR,e)},fatal(e){this.log(r.FATAL,e)}};function c(e,t){const s=y(e),n=A(s);if(n)throw new Error(`Parser Error: ${n}`);const i=N(s);if(["message","iq","presence"].includes(i.nodeName.toLowerCase())&&"jabber:client"!==i.namespaceURI&&"jabber:server"!==i.namespaceURI){const e=`Invalid namespaceURI ${i.namespaceURI}`;if(t)throw new Error(e);l.error(e)}return i}function h(e){void 0!==e.stack&&l.fatal(e.stack),l.fatal("error: "+e.message)}function d(e){let t="";const s=e.length;for(let n=0;n<s;n++){const s=e.charCodeAt(n);s>=0&&s<=127?t+=e.charAt(n):s>2047?(t+=String.fromCharCode(224|s>>12&15),t+=String.fromCharCode(128|s>>6&63),t+=String.fromCharCode(128|63&s)):(t+=String.fromCharCode(192|s>>6&31),t+=String.fromCharCode(128|63&s))}return t}function u(e,t){const s=new Uint8Array(e),n=new Uint8Array(t),i=new Uint8Array(e.byteLength);for(let t=0;t<e.byteLength;t++)i[t]=s[t]^n[t];return i.buffer}function _(e){let t="";const s=new Uint8Array(e),n=s.byteLength;for(let e=0;e<n;e++)t+=String.fromCharCode(s[e]);return btoa(t)}function p(e){var t;return null===(t=Uint8Array.from(atob(e),(e=>e.charCodeAt(0))))||void 0===t?void 0:t.buffer}function m(e){return(new TextEncoder).encode(e).buffer}function g(e){"undefined"==typeof document&&l.error("addCookies: not adding any cookies, since there's no document object"),e=e||{};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s="",n="",i="";const r=e[t],o="object"==typeof r,a=escape(unescape(o?r.value:r));o&&(s=r.expires?";expires="+r.expires:"",n=r.domain?";domain="+r.domain:"",i=r.path?";path="+r.path:""),document.cookie=t+"="+a+s+n+i}}let f=null;function b(){return f||(f=document.implementation.createDocument("jabber:client","strophe",null)),f}function S(e){return b().createTextNode(e)}function T(e){const t=Array.from(e.childNodes);return 1===t.length&&t[0].nodeType===o.TEXT||t.forEach((t=>{"body"!==t.nodeName.toLowerCase()&&(t.nodeType!==o.TEXT||/\S/.test(t.nodeValue)?t.nodeType===o.NORMAL&&T(t):e.removeChild(t))})),e}function y(e){return(new DOMParser).parseFromString(e,"text/xml")}function A(e){var t;const s="parsererror"===(null===(t=e.firstElementChild)||void 0===t?void 0:t.nodeName)?e.firstElementChild:e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","parsererror")[0];return"parsererror"===(null==s?void 0:s.nodeName)?null==s?void 0:s.textContent:null}function N(e){if(e.firstElementChild)return e.firstElementChild;let t,s=0;const n=e.childNodes;for(;t=n[s++];)if(1===t.nodeType)return t;return null}function w(e,t,s){if(!e)return null;const n=b().createElement(e);if(!s||"string"!=typeof s&&"number"!=typeof s){if("string"==typeof t||"number"==typeof t)return n.appendChild(S(t.toString())),n}else n.appendChild(S(s.toString()));if(!t)return n;if(Array.isArray(t))for(const e of t)Array.isArray(e)&&null!=e[0]&&null!=e[1]&&n.setAttribute(e[0],e[1]);else if("object"==typeof t)for(const e of Object.keys(t))e&&null!=t[e]&&n.setAttribute(e,t[e].toString());return n}function x(e){for(let t=0;t<s.tags.length;t++)if(e===s.tags[t])return!0;return!1}function C(e,t){const n=s.attributes[e];if((null==n?void 0:n.length)>0)for(let e=0;e<n.length;e++)if(t===n[e])return!0;return!1}function E(e){for(let t=0;t<s.css.length;t++)if(e===s.css[t])return!0;return!1}function v(e){if(e.nodeType===o.NORMAL)return function(e){let t;const n=e.nodeName.toLowerCase();if(x(n))try{if(t=w(n),n in s.attributes){const r=s.attributes[n];for(let s=0;s<r.length;s++){const n=r[s];let o=e.getAttribute(n);var i;if(null!=o&&""!==o)if("style"===n&&"object"==typeof o&&(o=null!==(i=o.cssText)&&void 0!==i?i:o),"style"===n){const e=[],s=o.split(";");for(let t=0;t<s.length;t++){const n=s[t].split(":"),i=n[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(E(i)){const t=n[1].replace(/^\s*/,"").replace(/\s*$/,"");e.push(i+": "+t)}}e.length>0&&(o=e.join("; "),t.setAttribute(n,o))}else t.setAttribute(n,o)}for(let s=0;s<e.childNodes.length;s++)t.appendChild(v(e.childNodes[s]))}}catch(e){t=S("")}else{t=b().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(v(e.childNodes[s]))}return t}(e);if(e.nodeType===o.FRAGMENT){const t=b().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(v(e.childNodes[s]));return t}return e.nodeType===o.TEXT?S(e.nodeValue):void 0}function I(e){let t;if(e.nodeType===o.NORMAL){const s=e;t=w(s.tagName);for(let e=0;e<s.attributes.length;e++)t.setAttribute(s.attributes[e].nodeName,s.attributes[e].value);for(let e=0;e<s.childNodes.length;e++)t.appendChild(I(s.childNodes[e]))}else e.nodeType===o.TEXT&&(t=b().createTextNode(e.nodeValue));return t}function R(e){return e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,""")}function H(e,t,s){for(let n=0;n<e.childNodes.length;n++){const i=e.childNodes[n];i.nodeType!==o.NORMAL||t&&!this.isTagEqual(i,t)||s(i)}}function O(e,t){return e.tagName===t}function q(e){if(!e)return null;let t="";e.childNodes.length||e.nodeType!==o.TEXT||(t+=e.nodeValue);for(const s of e.childNodes)s.nodeType===o.TEXT&&(t+=s.nodeValue);return R(t)}function M(e){return e.indexOf("@")<0?null:e.split("@")[0]}function D(e){const t=L(e);if(t.indexOf("@")<0)return t;{const e=t.split("@");return e.splice(0,1),e.join("@")}}function k(e){if(!e)return null;const t=e.split("/");return t.length<2?null:(t.splice(0,1),t.join("/"))}function L(e){return e?e.split("/")[0]:null}const B={utf16to8:d,xorArrayBuffers:u,arrayBufToBase64:_,base64ToArrayBuf:p,stringToArrayBuf:m,addCookies:g};var F=Object.freeze({__proto__:null,toElement:c,handleError:h,utf16to8:d,xorArrayBuffers:u,arrayBufToBase64:_,base64ToArrayBuf:p,stringToArrayBuf:m,addCookies:g,xmlGenerator:b,xmlTextNode:S,stripWhitespace:T,xmlHtmlNode:y,getParserError:A,getFirstElementChild:N,xmlElement:w,validTag:x,validAttribute:C,validCSS:E,createHtml:v,copyElement:I,xmlescape:R,xmlunescape:function(e){return e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"')},forEachChild:H,isTagEqual:O,getText:q,escapeNode:function(e){return"string"!=typeof e?e:e.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40")},unescapeNode:function(e){return"string"!=typeof e?e:e.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")},getNodeFromJid:M,getDomainFromJid:D,getResourceFromJid:k,getBareJidFromJid:L,default:B});function j(e,t){return new W(e,t)}function U(e){return new W("message",e)}function $(e){return new W("iq",e)}function P(e){return new W("presence",e)}class W{#e;#t;#s;#n;constructor(e,s){"presence"!==e&&"message"!==e&&"iq"!==e||(s&&!s.xmlns?s.xmlns=t.CLIENT:s||(s={xmlns:t.CLIENT})),this.#s=e,this.#n=s}static fromString(e){const t=c(e,!0),s=new W("");return s.#e=t,s}buildTree(){return w(this.#s,this.#n)}get nodeTree(){return this.#e||(this.#e=this.buildTree()),this.#e}get node(){return this.#t||(this.#t=this.tree()),this.#t}set node(e){this.#t=e}static serialize(e){if(!e)return null;const t=e instanceof W?e.tree():e,s=[...Array(t.attributes.length).keys()].map((e=>t.attributes[e].nodeName));s.sort();let n=s.reduce(((e,s)=>`${e} ${s}="${R(t.attributes.getNamedItem(s).value)}"`),`<${t.nodeName}`);if(t.childNodes.length>0){n+=">";for(let e=0;e<t.childNodes.length;e++){const s=t.childNodes[e];switch(s.nodeType){case o.NORMAL:n+=W.serialize(s);break;case o.TEXT:n+=R(s.nodeValue);break;case o.CDATA:n+="<![CDATA["+s.nodeValue+"]]>"}}n+="</"+t.nodeName+">"}else n+="/>";return n}tree(){return this.nodeTree}toString(){return W.serialize(this.tree())}up(){return this.node=this.node.parentElement?this.node.parentElement:this.node.parentNode,this}root(){return this.node=this.tree(),this}attrs(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(null!=e[t]?this.node.setAttribute(t,e[t].toString()):this.node.removeAttribute(t));return this}c(e,t,s){const n=w(e,t,s);return this.node.appendChild(n),"string"!=typeof s&&"number"!=typeof s&&(this.node=n),this}cnode(e){let t;e instanceof W&&(e=e.tree());const s=b();try{t=void 0!==s.importNode}catch(e){t=!1}const n=t?s.importNode(e,!0):I(e);return this.node.appendChild(n),this.node=n,this}t(e){const t=S(e);return this.node.appendChild(t),this}h(e){const t=b().createElement("body");t.innerHTML=e;const s=v(t);for(;s.childNodes.length>0;)this.node.appendChild(s.childNodes[0]);return this}}let z=0;class G{constructor(e,t,s,n=0){this.id=++z,this.xmlData=e,this.data=W.serialize(e),this.origFunc=t,this.func=t,this.rid=s,this.date=NaN,this.sends=n,this.abort=!1,this.dead=null,this.age=()=>this.date?((new Date).valueOf()-this.date.valueOf())/1e3:0,this.timeDead=()=>this.dead?((new Date).valueOf()-this.dead.valueOf())/1e3:0,this.xhr=this._newXHR()}getResponse(){var e;const t=null===(e=this.xhr.responseXML)||void 0===e?void 0:e.documentElement;if(t){if("parsererror"===t.tagName)throw l.error("invalid response received"),l.error("responseText: "+this.xhr.responseText),l.error("responseXML: "+W.serialize(t)),new Error("parsererror")}else if(this.xhr.responseText){l.debug("Got responseText but no responseXML; attempting to parse it with DOMParser...");const e=y(this.xhr.responseText),t=A(e);if(!e||t){t&&(l.error("invalid response received: "+t),l.error("responseText: "+this.xhr.responseText));const e=new Error;throw e.name=i.BAD_FORMAT,e}}return t}_newXHR(){const e=new XMLHttpRequest;return e.overrideMimeType&&e.overrideMimeType("text/xml; charset=utf-8"),e.onreadystatechange=this.func.bind(null,this),e}}let X=1.1,J=.1;class V{constructor(e){var t;this._conn=e,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.strip=null!==(t=V.prototype.strip)&&void 0!==t&&t,this.lastResponseHeaders=null,this._requests=[]}static setTimeoutMultiplier(e){X=e}static getTimeoutMultplier(){return X}static setSecondaryTimeoutMultiplier(e){J=e}static getSecondaryTimeoutMultplier(){return J}_buildBody(){const e=j("body",{rid:this.rid++,xmlns:t.HTTPBIND});return null!==this.sid&&e.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),e}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(e,s,n){this.wait=e||this.wait,this.hold=s||this.hold,this.errors=0;const i=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":t.BOSH});n&&i.attrs({route:n});const r=this._conn._connect_cb;this._requests.push(new G(i.tree(),this._onRequestStateChange.bind(this,r.bind(this._conn)),Number(i.tree().getAttribute("rid")))),this._throttledRequestHandler()}_attach(e,t,s,i,r,o,a){this._conn.jid=e,this.sid=t,this.rid=s,this._conn.connect_callback=i,this._conn.domain=D(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=r||this.wait,this.hold=o||this.hold,this.window=a||this.window,this._conn._changeConnectStatus(n.ATTACHED,null)}_restore(e,t,s,n,i){const r=JSON.parse(sessionStorage.getItem("strophe-bosh-session"));if(!(null!=r&&r.rid&&r.sid&&r.jid&&(null==e||L(r.jid)===L(e)||null===M(e)&&D(r.jid)===e))){const e=new Error("_restore: no restoreable session.");throw e.name="StropheSessionError",e}this._conn.restored=!0,this._attach(r.jid,r.sid,r.rid,t,s,n,i)}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(e){const t=e.getAttribute("type");if(null!==t&&"terminate"===t){let t=e.getAttribute("condition");l.error("BOSH-Connection failed: "+t);const s=e.getElementsByTagName("conflict");return null!==t?("remote-stream-error"===t&&s.length>0&&(t="conflict"),this._conn._changeConnectStatus(n.CONNFAIL,t)):this._conn._changeConnectStatus(n.CONNFAIL,"unknown"),this._conn._doDisconnect(t),n.CONNFAIL}this.sid||(this.sid=e.getAttribute("sid"));const s=e.getAttribute("requests");s&&(this.window=parseInt(s,10));const i=e.getAttribute("hold");i&&(this.hold=parseInt(i,10));const r=e.getAttribute("wait");r&&(this.wait=parseInt(r,10));const o=e.getAttribute("inactivity");o&&(this.inactivity=parseInt(o,10))}_disconnect(e){this._sendTerminate(e)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(e){const t=V._getRequestStatus(e),s=this._conn.protocolErrorHandlers.HTTP[t];s&&s.call(this,t)}_hitError(e){this.errors++,l.warn("request errored, status: "+e+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(e){l.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),e=e?e.bind(this._conn):this._conn._connect_cb.bind(this._conn);const t=this._buildBody();this._requests.push(new G(t.tree(),this._onRequestStateChange.bind(this,e),Number(t.tree().getAttribute("rid")))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){const e=this._requests.pop();e.abort=!0,e.xhr.abort(),e.xhr.onreadystatechange=function(){}}}_onIdle(){const e=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===e.length&&!this._conn.disconnecting&&(l.debug("no requests during idle cycle, sending blank request"),e.push(null)),!this._conn.paused){if(this._requests.length<2&&e.length>0){const s=this._buildBody();for(let n=0;n<e.length;n++)null!==e[n]&&("restart"===e[n]?s.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":t.BOSH}):s.cnode(e[n]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new G(s.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(s.tree().getAttribute("rid")))),this._throttledRequestHandler()}if(this._requests.length>0){const e=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(X*this.wait)&&this._throttledRequestHandler(),e>Math.floor(X*this.wait)&&(l.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(X*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(e,t){let s;if(4===e.xhr.readyState)try{s=e.xhr.status}catch(e){l.error(`Caught an error while retrieving a request's status, reqStatus: ${s}, message: ${e.message}`)}return void 0===s&&(s="number"==typeof t?t:0),s}_onRequestStateChange(e,t){if(l.debug("request id "+t.id+"."+t.sends+" state changed to "+t.xhr.readyState),t.abort)return void(t.abort=!1);if(4!==t.xhr.readyState)return;const s=V._getRequestStatus(t);if(this.lastResponseHeaders=t.xhr.getAllResponseHeaders(),this._conn.disconnecting&&s>=400)return this._hitError(s),void this._callProtocolErrorHandlers(t);const i=this._requests[0]===t,r=this._requests[1]===t,o=s>0&&s<500,a=t.sends>this._conn.maxRetries;(o||a)&&(this._removeRequest(t),l.debug("request id "+t.id+" should now be removed")),200===s?((r||i&&this._requests.length>0&&this._requests[0].age()>Math.floor(X*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(t.rid+1),l.debug("request id "+t.id+"."+t.sends+" got 200"),e(t),this.errors=0):0===s||s>=400&&s<600||s>=12e3?(l.error("request id "+t.id+"."+t.sends+" error "+s+" happened"),this._hitError(s),this._callProtocolErrorHandlers(t),s>=400&&s<500&&(this._conn._changeConnectStatus(n.DISCONNECTING,null),this._conn._doDisconnect())):l.error("request id "+t.id+"."+t.sends+" error "+s+" happened"),o||a?a&&!this._conn.connected&&this._conn._changeConnectStatus(n.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(e){let t=this._requests[e];const s=V._getRequestStatus(t,-1);if(t.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();const i=t.age(),r=!isNaN(i)&&i>Math.floor(X*this.wait),o=null!==t.dead&&t.timeDead()>Math.floor(J*this.wait),a=4===t.xhr.readyState&&(s<1||s>=500);if((r||o||a)&&(o&&l.error(`Request ${this._requests[e].id} timed out (secondary), restarting`),t.abort=!0,t.xhr.abort(),t.xhr.onreadystatechange=function(){},this._requests[e]=new G(t.xmlData,t.origFunc,t.rid,t.sends),t=this._requests[e]),0===t.xhr.readyState){var c,h;l.debug("request id "+t.id+"."+t.sends+" posting");try{const e=this._conn.options.contentType||"text/xml; charset=utf-8";t.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==t.xhr.setRequestHeader&&t.xhr.setRequestHeader("Content-Type",e),this._conn.options.withCredentials&&(t.xhr.withCredentials=!0)}catch(e){return l.error("XHR open failed: "+e.toString()),this._conn.connected||this._conn._changeConnectStatus(n.CONNFAIL,"bad-service"),void this._conn.disconnect()}const e=()=>{if(t.date=(new Date).valueOf(),this._conn.options.customHeaders){const e=this._conn.options.customHeaders;for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.xhr.setRequestHeader(s,e[s])}t.xhr.send(t.data)};if(t.sends>1){const s=1e3*Math.min(Math.floor(X*this.wait),Math.pow(t.sends,3));setTimeout((function(){e()}),s)}else e();var d,u,_,p;if(t.sends++,this.strip&&"body"===t.xmlData.nodeName&&t.xmlData.childNodes.length)null===(d=(u=this._conn).xmlOutput)||void 0===d||d.call(u,t.xmlData.children[0]);else null===(_=(p=this._conn).xmlOutput)||void 0===_||_.call(p,t.xmlData);null===(c=(h=this._conn).rawOutput)||void 0===c||c.call(h,t.data)}else l.debug("_processRequest: "+(0===e?"first":"second")+" request has readyState of "+t.xhr.readyState)}_removeRequest(e){l.debug("removing request");for(let t=this._requests.length-1;t>=0;t--)e===this._requests[t]&&this._requests.splice(t,1);e.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(e){const t=this._requests[e];null===t.dead&&(t.dead=new Date),this._processRequest(e)}_reqToData(e){try{return e.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(e){l.debug("_sendTerminate was called");const t=this._buildBody().attrs({type:"terminate"}),s=e instanceof W?e.tree():e;e&&t.cnode(s);const n=new G(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(t.tree().getAttribute("rid")));this._requests.push(n),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout((()=>this._conn._onIdle()),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?l.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):l.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}}class Q{constructor(e,t,s,n,i,r,o){this.handler=e,this.ns=t,this.name=s,this.type=n,this.id=i,this.options=o||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBareFromJid?this.from=r?L(r):null:this.from=r,this.user=!0}getNamespace(e){let t=e.getAttribute("xmlns");return t&&this.options.ignoreNamespaceFragment&&(t=t.split("#")[0]),t}namespaceMatch(e){if(!this.ns||this.getNamespace(e)===this.ns)return!0;for(const s of null!==(t=e.children)&&void 0!==t?t:[]){var t;if(this.getNamespace(s)===this.ns)return!0;if(this.namespaceMatch(s))return!0}return!1}isMatch(e){let t=e.getAttribute("from");this.options.matchBareFromJid&&(t=L(t));const s=e.getAttribute("type");return!(!this.namespaceMatch(e)||this.name&&!O(e,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(s):s!==this.type)||this.id&&e.getAttribute("id")!==this.id||this.from&&t!==this.from)}run(e){let t=null;try{t=this.handler(e)}catch(e){throw h(e),e}return t}toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}}class K{constructor(e,t){this.period=e,this.handler=t,this.lastCalled=(new Date).getTime(),this.user=!0}run(){return this.lastCalled=(new Date).getTime(),this.handler()}reset(){this.lastCalled=(new Date).getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}}class Y{constructor(e,t,s){this.mechname=e,this.isClientFirst=t,this.priority=s}test(e){return!0}onStart(e){this._connection=e}onChallenge(e,t){throw new Error("You should implement challenge handling!")}clientChallenge(e){if(!this.isClientFirst)throw new Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(e)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}class Z extends Y{constructor(e="ANONYMOUS",t=!1,s=20){super(e,t,s)}test(e){return null===e.authcid}}class ee extends Y{constructor(e="EXTERNAL",t=!0,s=10){super(e,t,s)}onChallenge(e){return e.authcid===e.authzid?"":e.authzid}}class te extends Y{constructor(e="OAUTHBEARER",t=!0,s=40){super(e,t,s)}test(e){return null!==e.pass}onChallenge(e){let t="n,";return null!==e.authcid&&(t=t+"a="+e.authzid),t+=",",t+="",t+="auth=Bearer ",t+=e.pass,t+="",t+="",B.utf16to8(t)}}class se extends Y{constructor(e="PLAIN",t=!0,s=50){super(e,t,s)}test(e){return null!==e.authcid}onChallenge(e){const{authcid:t,authzid:s,domain:n,pass:i}=e;if(!n)throw new Error("SASLPlain onChallenge: domain is not defined!");let r=s!==`${t}@${n}`?s:"";return r+="\0",r+=t,r+="\0",r+=i,B.utf16to8(r)}}const ne={async scramResponse(e,t,s,n){const i=e._sasl_data.cnonce,r=function(e){let t,s,n;const i=/([a-z]+)=([^,]+)(,|$)/;for(;e.match(i);){const r=e.match(i);switch(e=e.replace(r[0],""),r[1]){case"r":t=r[2];break;case"s":s=B.base64ToArrayBuf(r[2]);break;case"i":n=parseInt(r[2],10);break;case"m":return}}if(isNaN(n)||n<4096)l.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(s)return{nonce:t,salt:s,iter:n};l.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}(t);if(!r&&(null==r?void 0:r.nonce.slice(0,i.length))!==i)return l.warn("Failing SCRAM authentication because server supplied incorrect nonce."),e._sasl_data={},e._sasl_failure_cb();let o,a;const{pass:c}=e;if("string"==typeof e.pass||e.pass instanceof String){const e=await async function(e,t,s,n,i){const r=await crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:s,hash:{name:n}},await crypto.subtle.importKey("raw",B.stringToArrayBuf(e),"PBKDF2",!1,["deriveBits"]),i),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:n},!1,["sign"]);return{ck:await crypto.subtle.sign("HMAC",o,B.stringToArrayBuf("Client Key")),sk:await crypto.subtle.sign("HMAC",o,B.stringToArrayBuf("Server Key"))}}(c,r.salt,r.iter,s,n);o=e.ck,a=e.sk}else{if((null==c?void 0:c.name)!==s||(null==c?void 0:c.salt)!==B.arrayBufToBase64(r.salt)||(null==c?void 0:c.iter)!==r.iter)return e._sasl_failure_cb();{const{ck:e,sk:t}=c;o=B.base64ToArrayBuf(e),a=B.base64ToArrayBuf(t)}}const h=e._sasl_data["client-first-message-bare"],d=t,u=`c=biws,r=${r.nonce}`,_=`${h},${d},${u}`,p=await async function(e,t,s){const n=await crypto.subtle.importKey("raw",await crypto.subtle.digest(s,t),{name:"HMAC",hash:s},!1,["sign"]),i=await crypto.subtle.sign("HMAC",n,B.stringToArrayBuf(e));return B.xorArrayBuffers(t,i)}(_,o,s),m=await async function(e,t,s){const n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:s},!1,["sign"]);return crypto.subtle.sign("HMAC",n,B.stringToArrayBuf(e))}(_,a,s);return e._sasl_data["server-signature"]=B.arrayBufToBase64(m),e._sasl_data.keys={name:s,iter:r.iter,salt:B.arrayBufToBase64(r.salt),ck:B.arrayBufToBase64(o),sk:B.arrayBufToBase64(a)},`${u},p=${B.arrayBufToBase64(p)}`},clientChallenge(e,t){const s=t||function(){const e=new Uint8Array(16);return B.arrayBufToBase64(crypto.getRandomValues(e).buffer)}(),n=`n=${e.authcid},r=${s}`;return e._sasl_data.cnonce=s,e._sasl_data["client-first-message-bare"]=n,`n,,${n}`}};class ie extends Y{constructor(e="SCRAM-SHA-1",t=!0,s=60){super(e,t,s)}test(e){return null!==e.authcid}async onChallenge(e,t){return await ne.scramResponse(e,t,"SHA-1",160)}clientChallenge(e,t){return ne.clientChallenge(e,t)}}class re extends Y{constructor(e="SCRAM-SHA-256",t=!0,s=70){super(e,t,s)}test(e){return null!==e.authcid}async onChallenge(e,t){return await ne.scramResponse(e,t,"SHA-256",256)}clientChallenge(e,t){return ne.clientChallenge(e,t)}}class oe extends Y{constructor(e="SCRAM-SHA-384",t=!0,s=71){super(e,t,s)}test(e){return null!==e.authcid}async onChallenge(e,t){return await ne.scramResponse(e,t,"SHA-384",384)}clientChallenge(e,t){return ne.clientChallenge(e,t)}}class ae extends Y{constructor(e="SCRAM-SHA-512",t=!0,s=72){super(e,t,s)}test(e){return null!==e.authcid}async onChallenge(e,t){return await ne.scramResponse(e,t,"SHA-512",512)}clientChallenge(e,t){return ne.clientChallenge(e,t)}}class le extends Y{constructor(e="X-OAUTH2",t=!0,s=30){super(e,t,s)}test(e){return null!==e.pass}onChallenge(e){let t="\0";return null!==e.authcid&&(t+=e.authzid),t+="\0",t+=e.pass,B.utf16to8(t)}}class ce extends Error{constructor(e){super(e),this.name="StropheSessionError"}}class he{constructor(e){this._conn=e,this.strip="wrapper";const t=e.service;if(0!==t.indexOf("ws:")&&0!==t.indexOf("wss:")){let s="";"ws"===e.options.protocol&&"https:"!==location.protocol?s+="ws":s+="wss",s+="://"+location.host,0!==t.indexOf("/")?s+=location.pathname+t:s+=t,e.service=s}}_buildStream(){return j("open",{xmlns:t.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(e,s){let n;if(n=e.getElementsByTagNameNS?e.getElementsByTagNameNS(t.STREAM,"error"):e.getElementsByTagName("stream:error"),0===n.length)return!1;const i=n[0];let r="",o="";for(let e=0;e<i.childNodes.length;e++){const t=i.childNodes[e];if(t.nodeType===t.ELEMENT_NODE){if("urn:ietf:params:xml:ns:xmpp-streams"!==t.getAttribute("xmlns"))break}"text"===t.nodeName?o=t.textContent:r=t.nodeName}let a="WebSocket stream error: ";return a+=r||"unknown",o&&(a+=" - "+o),l.error(a),this._conn._changeConnectStatus(s,r),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new WebSocket(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=e=>this._onInitialMessage(e)}_connect_cb(e){if(this._checkStreamError(e,n.CONNFAIL))return n.CONNFAIL}_handleStreamStart(e){let s=null;const i=e.getAttribute("xmlns");"string"!=typeof i?s="Missing xmlns in <open />":i!==t.FRAMING&&(s="Wrong xmlns in <open />: "+i);const r=e.getAttribute("version");return"string"!=typeof r?s="Missing version in <open />":"1.0"!==r&&(s="Wrong version in <open />: "+r),!s||(this._conn._changeConnectStatus(n.CONNFAIL,s),this._conn._doDisconnect(),!1)}_onInitialMessage(e){if(0===e.data.indexOf("<open ")||0===e.data.indexOf("<?xml")){const t=e.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===t)return;const s=(new DOMParser).parseFromString(t,"text/xml").documentElement;this._conn.xmlInput(s),this._conn.rawInput(e.data),this._handleStreamStart(s)&&this._connect_cb(s)}else if(0===e.data.indexOf("<close ")){const t=(new DOMParser).parseFromString(e.data,"text/xml").documentElement;this._conn.xmlInput(t),this._conn.rawInput(e.data);const s=t.getAttribute("see-other-uri");if(s){const e=this._conn.service;(e.indexOf("wss:")>=0&&s.indexOf("wss:")>=0||e.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(n.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=s,this._connect())}else this._conn._changeConnectStatus(n.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();const t=this._streamWrap(e.data),s=(new DOMParser).parseFromString(t,"text/xml").documentElement;this._conn._connect_cb(s,null,e.data)}}_replaceMessageHandler(){this.socket.onmessage=e=>this._onMessage(e)}_disconnect(e){if(this.socket&&this.socket.readyState!==WebSocket.CLOSED){e&&this._conn.send(e);const s=j("close",{xmlns:t.FRAMING});this._conn.xmlOutput(s.tree());const n=W.serialize(s);this._conn.rawOutput(n);try{this.socket.send(n)}catch(e){l.warn(`Couldn't send <close /> tag. "${e.message}"`)}}setTimeout((()=>this._conn._doDisconnect()),0)}_doDisconnect(){l.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(e){return"<wrapper>"+e+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){l.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(l.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(l.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(n.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):l.debug("Websocket closed")}_no_auth_received(e){l.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(n.CONNFAIL,i.NO_AUTH_MECH),null==e||e.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(e){l.error("Websocket error "+JSON.stringify(e)),this._conn._changeConnectStatus(n.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){const e=this._conn._data;if(e.length>0&&!this._conn.paused){for(let t=0;t<e.length;t++)if(null!==e[t]){const s="restart"===e[t]?this._buildStream().tree():e[t];if("restart"===s)throw new Error("Wrong type for stanza");const n=W.serialize(s);this._conn.xmlOutput(s),this._conn.rawOutput(n),this.socket.send(n)}this._conn._data=[]}}_onMessage(e){let t;const s='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(e.data===s)return this._conn.rawInput(s),this._conn.xmlInput(e),void(this._conn.disconnecting||this._conn._doDisconnect());if(0===e.data.search("<open ")){if(t=(new DOMParser).parseFromString(e.data,"text/xml").documentElement,!this._handleStreamStart(t))return}else{const s=this._streamWrap(e.data);t=(new DOMParser).parseFromString(s,"text/xml").documentElement}return this._checkStreamError(t,n.ERROR)?void 0:this._conn.disconnecting&&"presence"===t.firstElementChild.nodeName&&"unavailable"===t.firstElementChild.getAttribute("type")?(this._conn.xmlInput(t),void this._conn.rawInput(W.serialize(t))):void this._conn._dataRecv(t,e.data)}_onOpen(){l.debug("Websocket open");const e=this._buildStream();this._conn.xmlOutput(e.tree());const t=W.serialize(e);this._conn.rawOutput(t),this.socket.send(t)}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}}
/**
* @license MIT
* @copyright JC Brand
*/class de extends he{constructor(e){super(e),this._conn=e,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var t;null===(t=console)||void 0===t||t.error(e),l.error(`Shared Worker Error: ${e}`)}}_setSocket(){this.socket={send:e=>this.worker.port.postMessage(["send",e]),close:()=>this.worker.port.postMessage(["_closeSocket"]),onopen:()=>{},onerror:e=>this._onError(e),onclose:e=>this._onClose(e),onmessage:()=>{},readyState:null}}_connect(){this._setSocket(),this._messageHandler=e=>this._onInitialMessage(e),this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(e){this._setSocket(),this._messageHandler=e=>this._onMessage(e),this._conn.connect_callback=e,this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(e,t){e===n.ATTACHED?(this._conn.jid=t,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(n.ATTACHED)):e===n.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(n.ATTACHFAIL))}_disconnect(e){e&&this._conn.send(e);const s=j("close",{xmlns:t.FRAMING});this._conn.xmlOutput(s.tree());const n=W.serialize(s);this._conn.rawOutput(n),this.worker.port.postMessage(["send",n]),this._conn._doDisconnect()}_closeSocket(){this.socket.close()}_replaceMessageHandler(){this._messageHandler=e=>this._onMessage(e)}_onWorkerMessage(e){const{data:t}=e,s=t[0];if("_onMessage"===s)this._messageHandler(t[1]);else if(s in this)try{this[s].apply(this,e.data.slice(1))}catch(e){l.error(e)}else if("log"===s){const e={debug:r.DEBUG,info:r.INFO,warn:r.WARN,error:r.ERROR,fatal:r.FATAL},s=t[1],n=t[2];l.log(e[s],n)}else l.error(`Found unhandled service worker message: ${t}`)}}const ue={};class _e{constructor(e,s={}){this.service=e,this.options=s,this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout((()=>this._onIdle()),100),g(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new Q((e=>this.send($({type:"error",id:e.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:t.STANZAS}))),null,"iq",["get","set"]);for(const e in ue)if(Object.prototype.hasOwnProperty.call(ue,e)){const t=function(){};t.prototype=ue[e],this[e]=new t,this[e].init(this)}}static addConnectionPlugin(e,t){ue[e]=t}setProtocol(){const e=this.options.protocol||"";this.options.worker?this._proto=new de(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===e.indexOf("ws")?this._proto=new he(this):this._proto=new V(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return"string"==typeof e||"number"==typeof e?t+":"+e:t+""}addProtocolErrorHandler(e,t,s){this.protocolErrorHandlers[e][t]=s}connect(e,t,s,i,r,o,a,l=3e3){this.jid=e,this.authzid=L(this.jid),this.authcid=a||M(this.jid),this.pass=t,this.scram_keys=null,this.connect_callback=s,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=l,this.domain=D(this.jid),this._changeConnectStatus(n.CONNECTING,null),this._proto._connect(i,r,o)}attach(e,t,s,n,i,r,o){if(this._proto instanceof V&&"string"==typeof e)return this._proto._attach(e,t,s,n,i,r,o);if(this._proto instanceof de&&"function"==typeof e){const t=e;return this._proto._attach(t)}throw new ce('The "attach" method is not available for your connection protocol')}restore(e,t,s,n,i){if(!(this._proto instanceof V&&this._sessionCachingSupported()))throw new ce('The "restore" method can only be used with a BOSH connection.');this._sessionCachingSupported()&&this._proto._restore(e,t,s,n,i)}_sessionCachingSupported(){if(this._proto instanceof V){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(e){}xmlOutput(e){}rawInput(e){}rawOutput(e){}nextValidRid(e){}send(e){if(null!==e){if(Array.isArray(e))e.forEach((e=>this._queueData(e instanceof W?e.tree():e)));else{const t=e instanceof W?e.tree():e;this._queueData(t)}this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(e,t,s,n){let i=null;const r=e instanceof W?e.tree():e;let o=r.getAttribute("id");if(o||(o=this.getUniqueId("sendPresence"),r.setAttribute("id",o)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i),"error"===e.getAttribute("type")?null==s||s(e):t&&t(e)}),null,"presence",null,o);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),null==s||s(null),!1))))}return this.send(r),o}sendIQ(e,t,s,n){let i=null;const r=e instanceof W?e.tree():e;let o=r.getAttribute("id");if(o||(o=this.getUniqueId("sendIQ"),r.setAttribute("id",o)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i);const n=e.getAttribute("type");if("result"===n)null==t||t(e);else{if("error"!==n){const e=new Error(`Got bad IQ type of ${n}`);throw e.name="StropheError",e}null==s||s(e)}}),null,"iq",["error","result"],o);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),null==s||s(null),!1))))}return this.send(r),o}_queueData(e){if(null===e||!e.tagName||!e.childNodes){const e=new Error("Cannot queue non-DOMElement.");throw e.name="StropheError",e}this._data.push(e)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout((()=>this._onIdle()),100)}addTimedHandler(e,t){const s=new K(e,t);return this.addTimeds.push(s),s}deleteTimedHandler(e){this.removeTimeds.push(e)}addHandler(e,t,s,n,i,r,o){const a=new Q(e,t,s,n,i,r,o);return this.addHandlers.push(a),a}deleteHandler(e){this.removeHandlers.push(e);const t=this.addHandlers.indexOf(e);t>=0&&this.addHandlers.splice(t,1)}registerSASLMechanisms(e){this.mechanisms={},(e||[Z,ee,te,le,se,ie,re,oe,ae]).forEach((e=>this.registerSASLMechanism(e)))}registerSASLMechanism(e){const t=new e;this.mechanisms[t.mechname]=t}disconnect(e){if(this._changeConnectStatus(n.DISCONNECTING,e),e?l.info("Disconnect was called because: "+e):l.debug("Disconnect was called"),this.connected){let e=null;this.disconnecting=!0,this.authenticated&&(e=P({xmlns:t.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(e)}else l.debug("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(e,t,s){for(const s in ue)if(Object.prototype.hasOwnProperty.call(ue,s)){const n=this[s];if(n.statusChanged)try{n.statusChanged(e,t)}catch(e){l.error(`${s} plugin caused an exception changing status: ${e}`)}}if(this.connect_callback)try{this.connect_callback(e,t,s)}catch(e){h(e),l.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(e){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),l.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(n.DISCONNECTED,e),this.connected=!1}_dataRecv(e,t){const s="_reqToData"in this._proto?this._proto._reqToData(e):e;if(null===s)return;for(this.xmlInput!==_e.prototype.xmlInput&&(s.nodeName===this._proto.strip&&s.childNodes.length?this.xmlInput(s.childNodes[0]):this.xmlInput(s)),this.rawInput!==_e.prototype.rawInput&&(t?this.rawInput(t):this.rawInput(W.serialize(s)));this.removeHandlers.length>0;){const e=this.removeHandlers.pop(),t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();const r=s.getAttribute("type");if(null!==r&&"terminate"===r){if(this.disconnecting)return;let e=s.getAttribute("condition");const t=s.getElementsByTagName("conflict");return null!==e?("remote-stream-error"===e&&t.length>0&&(e="conflict"),this._changeConnectStatus(n.CONNFAIL,e)):this._changeConnectStatus(n.CONNFAIL,i.UNKNOWN_REASON),void this._doDisconnect(e)}H(s,null,(e=>{const t=[];this.handlers=this.handlers.reduce(((s,n)=>{try{!n.isMatch(e)||!this.authenticated&&n.user?s.push(n):(n.run(e)&&s.push(n),t.push(n))}catch(e){l.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return s}),[]),!t.length&&this.iqFallbackHandler.isMatch(e)&&this.iqFallbackHandler.run(e)}))}_connect_cb(e,s,r){let o;l.debug("_connect_cb was called"),this.connected=!0;try{o="_reqToData"in this._proto?this._proto._reqToData(e):e}catch(e){if(e.name!==i.BAD_FORMAT)throw e;this._changeConnectStatus(n.CONNFAIL,i.BAD_FORMAT),this._doDisconnect(i.BAD_FORMAT)}if(!o)return;this.xmlInput!==_e.prototype.xmlInput&&(o.nodeName===this._proto.strip&&o.childNodes.length?this.xmlInput(o.childNodes[0]):this.xmlInput(o)),this.rawInput!==_e.prototype.rawInput&&(r?this.rawInput(r):this.rawInput(W.serialize(o)));if(this._proto._connect_cb(o)===n.CONNFAIL)return;let a;if(a=o.getElementsByTagNameNS?o.getElementsByTagNameNS(t.STREAM,"features").length>0:o.getElementsByTagName("stream:features").length>0||o.getElementsByTagName("features").length>0,!a)return void this._proto._no_auth_received(s);const c=Array.from(o.getElementsByTagName("mechanism")).map((e=>this.mechanisms[e.textContent])).filter((e=>e));0!==c.length||0!==o.getElementsByTagName("auth").length?!1!==this.do_authentication&&this.authenticate(c):this._proto._no_auth_received(s)}sortMechanismsByPriority(e){for(let t=0;t<e.length-1;++t){let s=t;for(let n=t+1;n<e.length;++n)e[n].priority>e[s].priority&&(s=n);if(s!==t){const n=e[t];e[t]=e[s],e[s]=n}}return e}authenticate(e){this._attemptSASLAuth(e)||this._attemptLegacyAuth()}_attemptSASLAuth(e){e=this.sortMechanismsByPriority(e||[]);let s=!1;for(let n=0;n<e.length;++n){if(!e[n].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=e[n],this._sasl_mechanism.onStart(this);const i=j("auth",{xmlns:t.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){const e=this._sasl_mechanism.clientChallenge(this);i.t(btoa(e))}this.send(i.tree()),s=!0;break}return s}async _sasl_challenge_cb(e){const s=atob(q(e)),n=await this._sasl_mechanism.onChallenge(this,s),i=j("response",{xmlns:t.SASL});return n&&i.t(btoa(n)),this.send(i.tree()),!0}_attemptLegacyAuth(){null===M(this.jid)?(this._changeConnectStatus(n.CONNFAIL,i.MISSING_JID_NODE),this.disconnect(i.MISSING_JID_NODE)):(this._changeConnectStatus(n.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send($({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:t.AUTH}).c("username",{}).t(M(this.jid)).tree()))}_onLegacyAuthIQResult(){const e="string"==typeof this.pass?this.pass:"",s=$({type:"set",id:"_auth_2"}).c("query",{xmlns:t.AUTH}).c("username",{}).t(M(this.jid)).up().c("password").t(e);return k(this.jid)||(this.jid=L(this.jid)+"/strophe"),s.up().c("resource",{}).t(k(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(s.tree()),!1}_sasl_success_cb(e){if(this._sasl_data["server-signature"]){let t;const s=/([a-z]+)=([^,]+)(,|$)/,n=atob(q(e)).match(s);if("v"===n[1]&&(t=n[2]),t!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}l.info("SASL authentication succeeded."),this._sasl_data.keys&&(this.scram_keys=this._sasl_data.keys),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);const s=[],n=(e,t)=>{for(;e.length;)this.deleteHandler(e.pop());return this._onStreamFeaturesAfterSASL(t),!1};return s.push(this._addSysHandler((e=>n(s,e)),null,"stream:features",null,null)),s.push(this._addSysHandler((e=>n(s,e)),t.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(e){this.features=e;for(let t=0;t<e.childNodes.length;t++){const s=e.childNodes[t];"bind"===s.nodeName&&(this.do_bind=!0),"session"===s.nodeName&&(this.do_session=!0)}return this.do_bind?(this.options.explicitResourceBinding?this._changeConnectStatus(n.BINDREQUIRED,null):this.bind(),!1):(this._changeConnectStatus(n.AUTHFAIL,null),!1)}bind(){if(!this.do_bind)return void l.info('Connection.prototype.bind called but "do_bind" is false');this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");const e=k(this.jid);e?this.send($({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:t.BIND}).c("resource",{}).t(e).tree()):this.send($({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:t.BIND}).tree())}_onResourceBindResultIQ(e){if("error"===e.getAttribute("type")){l.warn("Resource binding failed.");let t;return e.getElementsByTagName("conflict").length>0&&(t=i.CONFLICT),this._changeConnectStatus(n.AUTHFAIL,t,e),!1}const t=e.getElementsByTagName("bind");if(!(t.length>0))return l.warn("Resource binding failed."),this._changeConnectStatus(n.AUTHFAIL,null,e),!1;{const e=t[0].getElementsByTagName("jid");e.length>0&&(this.authenticated=!0,this.jid=q(e[0]),this.do_session?this._establishSession():this._changeConnectStatus(n.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw new Error(`Connection.prototype._establishSession called but apparently ${t.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send($({type:"set",id:"_session_auth_2"}).c("session",{xmlns:t.SESSION}).tree())}_onSessionResultIQ(e){if("result"===e.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(n.CONNECTED,null);else if("error"===e.getAttribute("type"))return this.authenticated=!1,l.warn("Session creation failed."),this._changeConnectStatus(n.AUTHFAIL,null,e),!1;return!1}_sasl_failure_cb(e){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(n.AUTHFAIL,null,e),!1}_auth2_cb(e){re