!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Tinode=e()}((function(){var e=function(e){var t;return function(n){return t||e(t={exports:{},parent:n},t.exports),t.exports}},t=e((function(e,t){e.exports={version:"0.16.9-beta1"}})),n=e((function(e,t){"use strict";const n=[{name:"ST",start:/(?:^|[\W_])(\*)[^\s*]/,end:/[^\s*](\*)(?=$|[\W_])/},{name:"EM",start:/(?:^|\W)(_)[^\s_]/,end:/[^\s_](_)(?=$|\W)/},{name:"DL",start:/(?:^|[\W_])(~)[^\s~]/,end:/[^\s~](~)(?=$|[\W_])/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],s=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@(\w\w+)/g},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#(\w\w+)/g}],i={ST:{name:"b",isVoid:!1},EM:{name:"i",isVoid:!1},DL:{name:"del",isVoid:!1},CO:{name:"tt",isVoid:!1},BR:{name:"br",isVoid:!0},LN:{name:"a",isVoid:!1},MN:{name:"a",isVoid:!1},HT:{name:"a",isVoid:!1},IM:{name:"img",isVoid:!0},FM:{name:"div",isVoid:!1},RW:{name:"div",isVoid:!1},BN:{name:"button",isVoid:!1},HD:{name:"",isVoid:!1}};function o(e,t){if(!e)return null;try{const n=atob(e),s=n.length,i=new ArrayBuffer(s),o=new Uint8Array(i);for(let e=0;e"},close:function(){return""}},EM:{open:function(){return""},close:function(){return""}},DL:{open:function(){return""},close:function(){return""}},CO:{open:function(){return""},close:function(){return""}},BR:{open:function(){return"
"},close:function(){return""}},HD:{open:function(){return""},close:function(){return""}},LN:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{href:e.url,target:"_blank"}:null}},MN:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{name:e.val}:null}},HT:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{name:e.val}:null}},BN:{open:function(e){return""},props:function(e){return e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null}},IM:{open:function(e){const t=o(e.val,e.mime),n=e.ref?e.ref:t;return(e.name?'':"")+''},close:function(e){return e.name?"":""},props:function(e){return e?{src:o(e.val,e.mime)||e.ref,title:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0,"data-mime":e.mime}:null}},FM:{open:function(e){return"
"},close:function(e){return"
"}},RW:{open:function(e){return"
"},close:function(e){return"
"}}};var a=function(){};a.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),i=[],o={},r=[];t.map((function(e){let t,a,c=[];if(n.map((function(t){c=c.concat(function(e,t,n,s){const i=[];let o=0,r=e.slice(0);for(;r.length>0;){const a=t.exec(r);if(null==a)break;let c=a.index+a[0].lastIndexOf(a[1]);r=r.slice(c+1),o=(c+=o)+1;const u=n?n.exec(r):null;if(null==u)break;let h=u.index+u[0].indexOf(u[1]);r=r.slice(h+1),o=(h+=o)+1,i.push({text:e.slice(c+1,h),children:[],start:c,end:h,type:s})}return i}(e,t.start,t.end,t.name))})),0==c.length)a={txt:e};else{c.sort((function(e,t){return e.start-t.start})),c=function e(t){if(0==t.length)return[];const n=[t[0]];let s=t[0];for(let e=1;es.end?(n.push(t[e]),s=t[e]):t[e].endn&&o.push({text:t.slice(n,r.start)});const a={type:r.type},c=e(t,r.start+1,r.end,r.children);c.length>0?a.children=c:a.text=r.text,o.push(a),n=r.end+1}return ni;return i=e.offset+e.len,t}))}(a.txt)).length>0){const e=[];for(let n in t){const s=t[n];let r=o[s.unique];r||(r=i.length,o[s.unique]=r,i.push({tp:s.type,data:s.data})),e.push({at:s.offset,len:s.len,key:r})}a.ent=e}r.push(a)}));const a={txt:""};if(r.length>0){a.txt=r[0].txt,a.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e0&&(a.ent=i)}return a},a.init=function(e){return"string"!=typeof e?null:{txt:e}},a.append=function(e,t){if(null==e)return t;if(null==t)return e;e.txt=e.txt||"",t.txt=t.txt||"";const n=e.txt.length;return e.txt+=t.txt,Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach(s=>{const i={at:s.at+n,len:s.len};s.tp?i.tp=s.tp:(i.key=e.ent.length,e.ent.push(t.ent[s.key||0])),e.fmt.push(i)})),e},a.insertImage=function(e,t,n,s,i,o,r,a,c){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:1,key:e.ent.length});const u={tp:"IM",data:{mime:n,val:s,width:i,height:o,name:r,size:0|a}};return c instanceof Promise?c.then(e=>{u.data.ref=e},e=>{}):u.data.ref=c,e.ent.push(u),e},a.appendImage=function(e,t,n,s,i,o,r,c){return(e=e||{txt:""}).txt+=" ",a.insertImage(e,e.txt.length-1,t,n,s,i,o,r,c)},a.attachFile=function(e,t,n,s,i,o){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});const r={tp:"EX",data:{mime:t,val:n,name:s,ref:o,size:0|i}};return o instanceof Promise&&(r.data.ref=o.then(e=>{r.data.ref=e},e=>{})),e.ent.push(r),e},a.wrapAsForm=function(e,t,n){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:t,len:n,tp:"FM"}),e},a.insertButton=function(e,t,n,s,i,o,r){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length{let t,n=e.tp;return n||(e.key=e.key||0,r[e.key]&&(t=r[e.key].data,n=r[e.key].tp)),{tp:n=n||"HD",data:t,at:e.at,len:e.len}}),function e(t,n,s,o,r,a){const c=[];for(let s=0;s0)for(var t in e.ent)if(e.ent[t]&&"EX"==e.ent[t].tp)return!0;return!1},a.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(var s in e.ent)e.ent[s]&&"EX"==e.ent[s].tp&&t.call(n,e.ent[s].data,s)},a.getDownloadUrl=function(e){let t=null;return"application/json"!=e.mime&&e.val?t=o(e.val,e.mime):"string"==typeof e.ref&&(t=e.ref),t},a.isUploading=function(e){return e.ref instanceof Promise},a.getPreviewUrl=function(e){return e.val?o(e.val,e.mime):null},a.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},a.getEntityMimeType=function(e){return e.mime||"text/plain"},a.tagName=function(e){return i[e]?i[e].name:void 0},a.attrValue=function(e,t){if(t&&r[e])return r[e].props(t)},a.getContentType=function(){return"text/x-drafty"},void 0!==e&&(e.exports=a)})),s={exports:{}};return function(e){"use strict";if(void 0===i)var i=n({});var o=t({}).version;let r,a;"undefined"!=typeof WebSocket&&(r=WebSocket),"undefined"!=typeof XMLHttpRequest&&(a=XMLHttpRequest),function(){if("undefined"==typeof btoa){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.btoa=function(e=""){let n=e,s="";for(let e,i=0,o=0,r=t;n.charAt(0|o)||(r="=",o%1);s+=r.charAt(63&i>>8-o%1*8)){if((e=n.charCodeAt(o+=.75))>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");i=i<<8|e}return s}}"undefined"==typeof atob&&(e.atob=function(e=""){let t=e.replace(/=+$/,""),n="";if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let e,s=0,i=0,o=0;e=t.charAt(o++);~e&&(i=s%4?64*i+e:e,s++%4)?n+=String.fromCharCode(255&i>>(-2*s&6)):0)e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);return n}),"undefined"==typeof window&&(e.window={WebSocket:r,XMLHttpRequest:a,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}})}();const c=o||"0.16",u="tinodejs/"+c,h="Connection failed",l=418,d="Disconnected by client";function f(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function p(e,t,n){if("object"!=typeof t){if(t===M.DEL_CHAR)return;return void 0===t?e:t}if(null===t)return t;if(t instanceof Date)return e&&e instanceof Date&&!(e=20&&t.length<=24){let e=new Date(t);if(e)return e}else if("acs"===e&&"object"==typeof t)return new x(t);return t}function b(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":function(e,t){if(t instanceof Date)t=function(e){if(!e||0==e.getTime())return;function t(e,t){return"0".repeat((t=t||2)-(""+e).length)+e}const n=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+(n?"."+t(n,3):"")+"Z"}(t);else if(t instanceof x)t=t.jsonHelper();else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"==typeof t&&0==Object.keys(t).length)return;return t}(0,t)}function w(e,t,n){let s=null;return"http"!==t&&"https"!==t&&"ws"!==t&&"wss"!==t||(s=t+"://","/"!==(s+=e).charAt(s.length-1)&&(s+="/"),s+="v0/channels","http"!==t&&"https"!==t||(s+="/lp"),s+="?apikey="+n),s}var v=function(e,t,n,s,i){let o=e,a=s,c=t,u=i;let f=null,p=0,g=!1,m=(e,...t)=>{this.logger&&this.logger(e,...t)};function b(){clearTimeout(f);let e=Math.pow(2,p)*(1+.3*Math.random())*2e3;p=p>=10?p:p+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),f=setTimeout(()=>{if(m("Reconnecting, iter="+p+", timeout="+e),g)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{let e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch(()=>{})}},e)}function v(){clearTimeout(f),f=null}function M(e){let t=null;e.connect=function(n,s){if(g=!1,t){if(!s&&t.readyState==t.OPEN)return Promise.resolve();t.close(),t=null}return n&&(o=n),new Promise((function(n,s){const i=w(o,a?"wss":"ws",c);m("Connecting to: ",i);const f=new r(i);f.onerror=function(e){s(e)},f.onopen=function(t){u&&v(),e.onOpen&&e.onOpen(),n()},f.onclose=function(n){if(t=null,e.onDisconnect){const t=g?l:503;e.onDisconnect(new Error(g?d:h+" ("+t+")"),t)}!g&&u&&b.call(e)},f.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=f}))},e.reconnect=function(t){v(),e.connect(null,t)},e.disconnect=function(){g=!0,t&&(v(),t.close(),t=null)},e.sendText=function(e){if(!t||t.readyState!=t.OPEN)throw new Error("Websocket is not connected");t.send(e)},e.isConnected=function(){return t&&t.readyState==t.OPEN},e.transport=function(){return"ws"},e.probe=function(){e.sendText("1")}}function S(e){let t=null,n=null,s=null;e.connect=function(s,i){if(g=!1,n){if(!i)return Promise.resolve();n.onreadystatechange=void 0,n.abort(),n=null}return s&&(o=s),new Promise((function(s,i){const r=w(o,a?"https":"http",c);m("Connecting to: ",r),(n=function n(s,i,o){let r=new XMLHttpRequest,a=!1;return r.onreadystatechange=function(c){if(4==r.readyState)if(201==r.status){let o=JSON.parse(r.responseText,_);t=s+"&sid="+o.ctrl.params.sid,(r=n(t)).send(null),e.onOpen&&e.onOpen(),i&&(a=!0,i()),u&&v()}else if(r.status<400)e.onMessage&&e.onMessage(r.responseText),(r=n(t)).send(null);else{if(o&&!a&&(a=!0,o(r.responseText)),e.onMessage&&r.responseText&&e.onMessage(r.responseText),e.onDisconnect){const t=r.status||(g?l:503),n=r.responseText||(g?d:h);e.onDisconnect(new Error(n+" ("+t+")"),t)}r=null,!g&&u&&b.call(e)}},r.open("GET",s,!0),r}(r,s,i)).send(null)})).catch(e=>{console.log("LP connection failed:",e)})},e.reconnect=function(t){v(),e.connect(null,t)},e.disconnect=function(){g=!0,v(),s&&(s.onreadystatechange=void 0,s.abort(),s=null),n&&(n.onreadystatechange=void 0,n.abort(),n=null),e.onDisconnect&&e.onDisconnect(new Error(d+" ("+"418)"),l),t=null},e.sendText=function(e){if(!(s=function(e){let t=new XMLHttpRequest;return t.onreadystatechange=function(e){if(4==t.readyState&&t.status>=400)throw new Error("LP sender failed, "+t.status)},t.open("POST",e,!0),t}(t))||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(e)},e.isConnected=function(){return n&&!0},e.transport=function(){return"lp"},e.probe=function(){e.sendText("1")}}let x=!1;if("lp"===n?(S(this),x=!0):"ws"===n?(M(this),x=!0):"object"==typeof window&&(window.WebSocket?(M(this),x=!0):window.XMLHttpRequest&&(S(this),x=!0)),!x)throw console.log("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'.");this.transportAvailable=function(e){switch(e){case"ws":return"object"==typeof window&&window.WebSocket;case"lp":return"object"==typeof window&&window.XMLHttpRequest;default:return console.log("Request for unknown transport",e),!1}},this.backoffReset=function(){p=0},this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.onAutoreconnectIteration=void 0,this.logger=void 0},M=function(e,t,n,s,i,o){this._appName=e||"Undefined",this._apiKey=n,this._browser="",this._platform=o,this._hwos="undefined",this._humanLanguage="xx","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let n="";/reactnative/i.test(t)&&(n="ReactNative; ");let s,i=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(i){let t=["chrome","safari","mobile","version"],n=e.substr(i.index+i[0].length).split(" "),o=[];for(let e=0;e0?o[0][0]+"/"+o[0][1]:i[1]}else s=/trident/i.test(e)?(i=/(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(e))?"MSIE/"+(i[1]||i[2]):"MSIE/?":/firefox/i.test(e)?(i=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+i[1]:"Firefox/?":/presto/i.test(e)?(i=/Opera\/([.\d]+)/g.exec(e))?"Opera/"+i[1]:"Opera/?":(i=/([\w.]+)\/([.\d]+)/.exec(e))?i[1]+"/"+i[2]:(i=e.split(" "))[0];if((i=s.split("/")).length>1){let e=i[1].split(".");s=i[0]+"/"+e[0]+(e[1]?"."+e[1]:"")}return n+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),this._loggingEnabled=!1,this._trimLongStrings=!1,this._myUID=null,this._authenticated=!1,this._login=null,this._authToken=null,this._inPacketCount=0,this._messageId=Math.floor(65535*Math.random()+65535),this._serverInfo=null,this._deviceToken=null,this._pendingPromises={},this._expirePromises=null,this._connection=new v(t,n,s,i,!0),this.logger=(e,...t)=>{if(this._loggingEnabled){const n=new Date,s=("0"+n.getUTCHours()).slice(-2)+":"+("0"+n.getUTCMinutes()).slice(-2)+":"+("0"+n.getUTCSeconds()).slice(-2)+"."+("00"+n.getUTCMilliseconds()).slice(-3);console.log("["+s+"]",e,t.join(" "))}},this._connection.logger=this.logger,this._cache={};const r=this.cachePut=(e,t,n)=>{this._cache[e+":"+t]=n},a=this.cacheGet=(e,t)=>this._cache[e+":"+t],h=this.cacheDel=(e,t)=>{delete this._cache[e+":"+t]},l=this.cacheMap=(e,t)=>{for(let n in this._cache)if(e(this._cache[n],n,t))break};this.attachCacheToTopic=e=>{e._tinode=this,e._cacheGetUser=e=>{const t=a("user",e);if(t)return{user:e,public:p({},t)}},e._cachePutUser=(e,t)=>r("user",e,p({},t.public)),e._cacheDelUser=e=>h("user",e),e._cachePutSelf=()=>r("topic",e.name,e),e._cacheDelSelf=()=>h("topic",e.name)};const d=(e,t,n,s)=>{const i=this._pendingPromises[e];i&&(delete this._pendingPromises[e],t>=200&&t<400?i.resolve&&i.resolve(n):i.reject&&i.reject(new Error(s+" ("+t+")")))},f=e=>{let t=null;return e&&(t=new Promise((t,n)=>{this._pendingPromises[e]={resolve:t,reject:n,ts:new Date}})),t},g=this.getNextUniqueId=()=>0!=this._messageId?""+this._messageId++:void 0,m=()=>this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+u;this.initPacket=(e,t)=>{switch(e){case"hi":return{hi:{id:g(),ver:c,ua:m(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:g(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:g(),scheme:null,secret:null}};case"sub":return{sub:{id:g(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:g(),topic:t,unsub:!1}};case"pub":return{pub:{id:g(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:g(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:g(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:g(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error("Unknown packet type requested: "+e)}},this.send=(e,t)=>{let n;t&&(n=f(t)),e=function e(t){return Object.keys(t).forEach((function(n){"_"==n[0]?delete t[n]:t[n]?Array.isArray(t[n])&&0==t[n].length?delete t[n]:t[n]?"object"!=typeof t[n]||t[n]instanceof Date||(e(t[n]),0==Object.getOwnPropertyNames(t[n]).length&&delete t[n]):delete t[n]:delete t[n]})),t}(e);let s=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,b):s));try{this._connection.sendText(s)}catch(e){if(!t)throw e;d(t,503,null,e.message)}return n},this.loginSuccessful=e=>{e.params&&e.params.user&&(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:new Date(e.params.expires)}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text))},this._connection.onMessage=e=>{if(!e)return;if(this._inPacketCount++,this.onRawMessage&&this.onRawMessage(e),"0"===e)return void(this.onNetworkProbe&&this.onNetworkProbe());let t=JSON.parse(e,_);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,b):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&d(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout(()=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=a("topic",t.ctrl.topic);e&&e._resetSub()}else if(t.ctrl.params&&"data"==t.ctrl.params.what){const e=a("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if(t.ctrl.params&&"sub"==t.ctrl.params.what){const e=a("topic",t.ctrl.topic);e&&e._processMetaSub([])}},0)):setTimeout(()=>{if(t.meta){const e=a("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&d(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=a("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=a("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=a("topic",t.info.topic);e&&e._routeInfo(t.info),this.onInfoMessage&&this.onInfoMessage(t.info)}else this.logger("ERROR: Unknown packet received.")},0)):(this.logger("in: "+e),this.logger("ERROR: failed to parse data"))},this._connection.onOpen=()=>{this._expirePromises||(this._expirePromises=setInterval(()=>{const e=new Error("Timeout (504)"),t=new Date((new Date).getTime()-5e3);for(let n in this._pendingPromises){let s=this._pendingPromises[n];s&&s.ts{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._connection.onDisconnect=(e,t)=>{this._inPacketCount=0,this._serverInfo=null,this._authenticated=!1,this._expirePromises&&(clearInterval(this._expirePromises),this._expirePromises=null),l((e,t)=>{0===t.lastIndexOf("topic:",0)&&e._resetSub()});for(let t in this._pendingPromises){let n=this._pendingPromises[t];n&&n.reject&&n.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}};M.credential=function(e,t,n,s){return"object"==typeof e&&({val:t,params:n,resp:s,meth:e}=e),e&&(t||s)?[{meth:e,val:t,resp:s,params:n}]:null},M.topicType=function(e){return{me:"me",fnd:"fnd",grp:"grp",new:"grp",nch:"grp",chn:"grp",usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]},M.isGroupTopicName=function(e){return"grp"===M.topicType(e)},M.isP2PTopicName=function(e){return"p2p"===M.topicType(e)},M.isNewGroupTopicName=function(e){return"string"==typeof e&&("new"==e.substring(0,3)||"nch"==e.substring(0,3))},M.isChannelTopicName=function(e){return"string"==typeof e&&("chn"==e.substring(0,3)||"nch"==e.substring(0,3))},M.getVersion=function(){return c},M.setNetworkProviders=function(e,t){r=e,a=t},M.getLibrary=function(){return u},M.MESSAGE_STATUS_NONE=0,M.MESSAGE_STATUS_QUEUED=1,M.MESSAGE_STATUS_SENDING=2,M.MESSAGE_STATUS_FAILED=3,M.MESSAGE_STATUS_SENT=4,M.MESSAGE_STATUS_RECEIVED=5,M.MESSAGE_STATUS_READ=6,M.MESSAGE_STATUS_TO_ME=7,M.DEL_CHAR="␡",M.isNullValue=function(e){return e===M.DEL_CHAR},M.isRelativeURL=function(e){return!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)},M.MAX_MESSAGE_SIZE="maxMessageSize",M.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",M.MAX_TAG_COUNT="maxTagCount",M.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",M.prototype={connect:function(e){return this._connection.connect(e)},reconnect:function(e){this._connection.reconnect(e)},disconnect:function(){this._connection.disconnect()},networkProbe:function(){this._connection.probe()},isConnected:function(){return this._connection.isConnected()},isAuthenticated:function(){return this._authenticated},authorizeURL:function(e){if(!e)return e;if(M.isRelativeURL(e)){const t="scheme://host/",n=new URL(e,t);this._apiKey&&n.searchParams.append("apikey",this._apiKey),this._authToken.token&&(n.searchParams.append("auth","token"),n.searchParams.append("secret",this._authToken.token)),e=n.toString().substring(t.length-1)}return e},account:function(e,t,n,s,i){const o=this.initPacket("acc");return o.acc.user=e,o.acc.scheme=t,o.acc.secret=n,o.acc.login=s,i&&(o.acc.desc.defacs=i.defacs,o.acc.desc.public=i.public,o.acc.desc.private=i.private,o.acc.tags=i.tags,o.acc.cred=i.cred,o.acc.token=i.token),this.send(o,o.acc.id)},createAccount:function(e,t,n,s){let i=this.account("new",e,t,n,s);return n&&(i=i.then(e=>(this.loginSuccessful(e),e))),i},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",f(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,s){return t=t||"",n=n||"",this.account(e,"basic",f(t+":"+n),!1,s)},hello:function(){const e=this.initPacket("hi");return this.send(e,e.hi.id).then(e=>(this._connection.backoffReset(),e.params&&(this._serverInfo=e.params),this.onConnect&&this.onConnect(),e)).catch(e=>{this._connection.reconnect(!0),this.onDisconnect&&this.onDisconnect(e)})},setDeviceToken:function(e,t){let n=!1;return e&&e!=this._deviceToken&&(this._deviceToken=e,t&&this.isConnected()&&this.isAuthenticated()&&(this.send({hi:{dev:e}}),n=!0)),n},login:function(e,t,n){const s=this.initPacket("login");return s.login.scheme=e,s.login.secret=t,s.login.cred=n,this.send(s,s.login.id).then(e=>(this.loginSuccessful(e),e))},loginBasic:function(e,t,n){return this.login("basic",f(e+":"+t),n).then(t=>(this._login=e,t))},loginToken:function(e,t){return this.login("token",e,t)},requestResetAuthSecret:function(e,t,n){return this.login("reset",f(e+":"+t+":"+n))},getAuthToken:function(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)},setAuthToken:function(e){this._authToken=e},subscribe:function(e,t,n){const s=this.initPacket("sub",e);return e||(e="new"),s.sub.get=t,n&&(n.sub&&(s.sub.set.sub=n.sub),n.desc&&(M.isNewGroupTopicName(e)?s.sub.set.desc=n.desc:M.isP2PTopicName(e)&&n.desc.defacs&&(s.sub.set.desc={defacs:n.desc.defacs})),n.tags&&(s.sub.set.tags=n.tags)),this.send(s,s.sub.id)},leave:function(e,t){const n=this.initPacket("leave",e);return n.leave.unsub=t,this.send(n,n.leave.id)},createMessage:function(e,t,n){const s=this.initPacket("pub",e);let o="string"==typeof t?i.parse(t):t;return o&&!i.isPlainText(o)&&(s.pub.head={mime:i.getContentType()},t=o),s.pub.noecho=n,s.pub.content=t,s.pub},publish:function(e,t,n){return this.publishMessage(this.createMessage(e,t,n))},publishMessage:function(e){return(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0,this.send({pub:e},e.id)},getMeta:function(e,t){const n=this.initPacket("get",e);return n.get=p(n.get,t),this.send(n,n.get.id)},setMeta:function(e,t){const n=this.initPacket("set",e),s=[];return t&&["desc","sub","tags","cred"].map((function(e){t.hasOwnProperty(e)&&(s.push(e),n.set[e]=t[e])})),0==s.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(n,n.set.id)},delMessages:function(e,t,n){const s=this.initPacket("del",e);return s.del.what="msg",s.del.delseq=t,s.del.hard=n,this.send(s,s.del.id)},delTopic:function(e,t){const n=this.initPacket("del",e);return n.del.what="topic",n.del.hard=t,this.send(n,n.del.id).then(t=>(this.cacheDel("topic",e),this.ctrl))},delSubscription:function(e,t){const n=this.initPacket("del",e);return n.del.what="sub",n.del.user=t,this.send(n,n.del.id)},delCredential:function(e,t){const n=this.initPacket("del","me");return n.del.what="cred",n.del.cred={meth:e,val:t},this.send(n,n.del.id)},delCurrentUser:function(e){const t=this.initPacket("del",null);return t.del.what="user",t.del.hard=e,this.send(t,t.del.id).then(e=>{this._myUID=null})},note:function(e,t,n){if(n<=0||n>=268435455)throw new Error("Invalid message id "+n);const s=this.initPacket("note",e);s.note.what=t,s.note.seq=n,this.send(s)},noteKeyPress:function(e){const t=this.initPacket("note",e);t.note.what="kp",this.send(t)},getTopic:function(e){let t=this.cacheGet("topic",e);return!t&&e&&(t="me"==e?new y:"fnd"==e?new D:new T(e),this.cachePut("topic",e,t),this.attachCacheToTopic(t)),t},newTopic:function(e){const t=new T("new",e);return this.attachCacheToTopic(t),t},newChannel:function(e){const t=new T("nch",e);return this.attachCacheToTopic(t),t},newGroupTopicName:function(e){return(e?"nch":"new")+this.getNextUniqueId()},newTopicWith:function(e,t){const n=new T(e,t);return this.attachCacheToTopic(n),n},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new R(this)},getCurrentUserID:function(){return this._myUID},isMe:function(e){return this._myUID===e},getCurrentLogin:function(){return this._login},getServerInfo:function(){return this._serverInfo},getServerLimit:function(e,t){return(this._serverInfo?this._serverInfo[e]:null)||t},enableLogging:function(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t},setHumanLanguage:function(e){e&&(this._humanLanguage=e)},isTopicOnline:function(e){const t=this.getMeTopic(),n=t&&t.getContact(e);return n&&n.online},getTopicAccessMode:function(e){const t=this.getMeTopic(),n=t&&t.getContact(e);return n?n.acs:null},wantAkn:function(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0},onWebsocketOpen:void 0,onConnect:void 0,onDisconnect:void 0,onLogin:void 0,onCtrlMessage:void 0,onDataMessage:void 0,onPresMessage:void 0,onMessage:void 0,onRawMessage:void 0,onNetworkProbe:void 0,onAutoreconnectIteration:void 0};var S=function(e){this.topic=e;const t=e._tinode.getMeTopic();this.contact=t&&t.getContact(e.name),this.what={}};S.prototype={_get_ims:function(){const e=this.contact&&this.contact.updated,t=this.topic._lastDescUpdate||0;return e>t?e:t},withData:function(e,t,n){return this.what.data={since:e,before:t,limit:n},this},withLaterData:function(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)},withEarlierData:function(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)},withDesc:function(e){return this.what.desc={ims:e},this},withLaterDesc:function(){return this.withDesc(this._get_ims())},withSub:function(e,t,n){const s={ims:e,limit:t};return"me"==this.topic.getType()?s.topic=n:s.user=n,this.what.sub=s,this},withOneSub:function(e,t){return this.withSub(e,void 0,t)},withLaterOneSub:function(e){return this.withOneSub(this.topic._lastSubsUpdate,e)},withLaterSub:function(e){return this.withSub(this.topic.isP2P()?this._get_ims():this.topic._lastSubsUpdate,e)},withTags:function(){return this.what.tags=!0,this},withCred:function(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),this},withDel:function(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this},withLaterDel:function(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)},build:function(){const e=[],t=this;let n={};return["data","sub","desc","tags","cred","del"].map((function(s){t.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(t.what[s]).length>0&&(n[s]=t.what[s]))})),e.length>0?n.what=e.join(" "):n=void 0,n}};var x=function(e){e&&(this.given="number"==typeof e.given?e.given:x.decode(e.given),this.want="number"==typeof e.want?e.want:x.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:x.decode(e.mode):this.given&this.want)};x._NONE=0,x._JOIN=1,x._READ=2,x._WRITE=4,x._PRES=8,x._APPROVE=16,x._SHARE=32,x._DELETE=64,x._OWNER=128,x._BITMASK=x._JOIN|x._READ|x._WRITE|x._PRES|x._APPROVE|x._SHARE|x._DELETE|x._OWNER,x._INVALID=1048576,x._checkFlag=function(e,t,n){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&n);throw new Error("Invalid AccessMode component '"+t+"'")},x.decode=function(e){if(!e)return null;if("number"==typeof e)return e&x._BITMASK;if("N"===e||"n"===e)return x._NONE;const t={J:x._JOIN,R:x._READ,W:x._WRITE,P:x._PRES,A:x._APPROVE,S:x._SHARE,D:x._DELETE,O:x._OWNER};let n=x._NONE;for(let s=0;s0)){c=!0;break}o=r-1}return c?{idx:r,exact:!0}:s?{idx:-1}:{idx:a<0?r+1:r}}function i(e,t){const n=s(e,t,!1),i=n.exact?1:0;return t.splice(n.idx,i,e),t}return e=e||function(e,t){return e===t?0:e0?n[n.length-1]:void 0},put:function(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)i(e[t],n)},delAt:function(e){let t=n.splice(e,1);if(t&&t.length>0)return t[0]},delRange:function(e,t){return n.splice(e,t-e)},length:function(){return n.length},reset:function(){n=[]},forEach:function(e,t,s,i){t|=0,s=s||n.length;for(let o=t;o{if(e.code>=300)return e;if(this._subscribed=!0,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(this._new=!1,this.name=e.topic,this.created=e.ts,this.updated=e.ts,this._cachePutSelf(),"me"!=this.name&&"fnd"!=this.name){const t=this._tinode.getMeTopic();t&&t._processMetaSub([{_noForwarding:!0,topic:this.name,created:e.ts,updated:e.ts,acs:this.acs}])}t&&t.desc&&(t.desc._noForwarding=!0,this._processMetaDesc(t.desc))}return e})},createMessage:function(e,t){return this._tinode.createMessage(this.name,e,t)},publish:function(e,t){return this.publishMessage(this.createMessage(e,t))},publishMessage:function(e){if(!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));if(i.hasAttachments(e.content)&&!e.head.attachments){let t=[];i.attachments(e.content,e=>{t.push(e.ref)}),e.head.attachments=t}return e._sending=!0,e._failed=!1,this._tinode.publishMessage(e).then(t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),this._routeData(e),t)).catch(t=>{this._tinode.logger("WARNING: Message rejected by the server",t),e._sending=!1,e._failed=!0,this.onData&&this.onData()})},publishDraft:function(e,t){if(!t&&!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));const n=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=n,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this.onData&&this.onData(e)),(t||Promise.resolve()).then(()=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e),t=>{this._tinode.logger("WARNING: Message draft rejected by the server",t),e._sending=!1,e._failed=!0,this._messages.delAt(this._messages.find(e)),this.onData&&this.onData()})},leave:function(e){return this._subscribed||e?this._tinode.leave(this.name,e).then(t=>(this._resetSub(),e&&(this._tinode.cacheDel("topic",this.name),this._gone()),t)):Promise.reject(new Error("Cannot leave inactive topic"))},getMeta:function(e){return this._tinode.getMeta(this.name,e)},getMessagesPage:function(e,t){const n=this.startMetaQuery();t?n.withLaterData(e):n.withEarlierData(e);let s=this.getMeta(n.build());return t||(s=s.then(e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)})),s},setMeta:function(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let n=0,s=e.length;n1&&t.push(s)}t.sort().filter((function(e,t,n){return!t||e!=n[t-1]}))}return 0==t.length&&t.push(M.DEL_CHAR),t}(e.tags)),this._tinode.setMeta(this.name,e).then(t=>(t&&t.code>=300||(e.sub&&(e.sub.topic=this.name,t.params&&t.params.acs&&(e.sub.acs=t.params.acs,e.sub.updated=t.ts),e.sub.user||(e.sub.user=this._tinode.getCurrentUserID(),e.desc||(e.desc={})),e.sub._noForwarding=!0,this._processMetaSub([e.sub])),e.desc&&(t.params&&t.params.acs&&(e.desc.acs=t.params.acs,e.desc.updated=t.ts),this._processMetaDesc(e.desc)),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds([e.cred],!0)),t))},updateMode:function(e,t){const n=e?this.subscriber(e):null,s=n?n.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:s}})},invite:function(e,t){return this.setMeta({sub:{user:e,mode:t}})},archive:function(e){return this.private&&this.private.arch==e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||M.DEL_CHAR}}})},delMessages:function(e,t){if(!this._subscribed)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort((e,t)=>e.low=t.hi));let n,s=e.reduce((e,t)=>(t.low<268435455&&(!t.hi||t.hi<268435455?e.push(t):e.push({low:t.low,hi:this._maxSeq+1})),e),[]);return(n=s.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}})).then(t=>(t.params.del>this._maxDel&&(this._maxDel=t.params.del),e.map(e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low)}),this._updateDeletedRanges(),this.onData&&this.onData(),t))},delMessagesAll:function(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)},delMessagesList:function(e,t){e.sort((e,t)=>e-t);let n=e.reduce((e,t)=>{if(0==e.length)e.push({low:t});else{let n=e[e.length-1];!n.hi&&t!=n.low+1||t>n.hi?e.push({low:t}):n.hi=n.hi?Math.max(n.hi,t+1):t+1}return e},[]);return this.delMessages(n,t)},delTopic:function(e){return this._tinode.delTopic(this.name,e).then(e=>(this._resetSub(),this._gone(),e))},delSubscription:function(e){return this._subscribed?this._tinode.delSubscription(this.name,e).then(t=>(delete this._users[e],this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users)),t)):Promise.reject(new Error("Cannot delete subscription in inactive topic"))},note:function(e,t){if(!this._subscribed)return;const n=this._tinode.getMeTopic(),s=this._users[this._tinode.getCurrentUserID()];let i=!1;s?(!s[e]||s[e]0&&this.note("read",e)},noteKeyPress:function(){this._subscribed?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")},userDesc:function(e){const t=this._cacheGetUser(e);if(t)return t},p2pPeerDesc:function(){if(this.isP2P())return this._users[this.name]},subscribers:function(e,t){const n=e||this.onMetaSub;if(n)for(let e in this._users)n.call(t,this._users[e],e,this._users)},tags:function(){return this._tags.slice(0)},subscriber:function(e){return this._users[e]},messages:function(e,t,n,s){const i=e||this.onData;if(i){let e="number"==typeof t?this._messages.find({seq:t},!0):void 0,o="number"==typeof n?this._messages.find({seq:n},!0):void 0;-1!=e&&-1!=o&&this._messages.forEach(i,e,o,s)}},queuedMessages:function(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,268435455,void 0,t)},msgReceiptCount:function(e,t){let n=0;if(t>0){const s=this._tinode.getCurrentUserID();for(let i in this._users){const o=this._users[i];o.user!==s&&o[e]>=t&&n++}}return n},msgReadCount:function(e){return this.msgReceiptCount("read",e)},msgRecvCount:function(e){return this.msgReceiptCount("recv",e)},msgHasMoreMessages:function(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs},isNewMessage:function(e){return this._maxSeq<=e},flushMessage:function(e){const t=this._messages.find({seq:e});return t>=0?this._messages.delAt(t):void 0},swapMessageId:function(e,t){const n=this._messages.find({seq:e.seq}),s=this._messages.length();e.seq=t,0<=n&&n0&&this._messages.getAt(n-1).seq>=t||n+1=0?this._messages.delRange(n,this._messages.find({seq:t},!0)):[]},cancelSend:function(e){const t=this._messages.find({seq:e});if(t>=0){const e=this._messages.getAt(t),n=this.msgStatus(e);if(1==n||3==n)return e._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1},getType:function(){return M.topicType(this.name)},getAccessMode:function(){return this.acs},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new S(this)},isArchived:function(){return!(!this.private||!this.private.arch)},isChannel:function(){return M.isChannelTopicName(this.name)},isGroup:function(){return M.isGroupTopicName(this.name)},isP2P:function(){return M.isP2PTopicName(this.name)},msgStatus:function(e){let t=0;return this._tinode.isMe(e.from)?e._sending?t=2:e._failed?t=3:e.seq>=268435455?t=1:this.msgReadCount(e.seq)>0?t=6:this.msgRecvCount(e.seq)>0?t=5:e.seq>0&&(t=4):t=7,t},_routeData:function(e){e.content&&(!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq),(e.seq0&&(this._lastSubsUpdate=e.ts,this._processMetaSub(e.sub)),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds(e.cred),this.onMeta&&this.onMeta(e)},_routePres:function(e){let t;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":(t=this._users[e.src])?t.online="on"==e.what:this._tinode.logger("WARNING: Presence update for an unknown user",this.name,e.src);break;case"term":this._resetSub();break;case"acs":const n=e.src||this._tinode.getCurrentUserID();if(t=this._users[n])t.acs.updateAll(e.dacs),this._processMetaSub([{user:n,updated:new Date,acs:t.acs}]);else{const s=(new x).updateAll(e.dacs);s&&s.mode!=x._NONE&&((t=this._cacheGetUser(n))?t.acs=s:(t={user:n,acs:s},this.getMeta(this.startMetaQuery().withOneSub(void 0,n).build())),t.updated=new Date,this._processMetaSub([t]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)},_routeInfo:function(e){if("kp"!==e.what){const t=this._users[e.from];if(t&&(t[e.what]=e.seq,t.recv0&&(this._updateDeletedRanges(),this.onData&&this.onData())},_allMessagesReceived:function(e){this._updateDeletedRanges(),this.onAllMessagesReceived&&this.onAllMessagesReceived(e)},_resetSub:function(){this._subscribed=!1},_gone:function(){this._messages.reset(),this._users={},this.acs=new x(null),this.private=null,this.public=null,this._maxSeq=0,this._minSeq=0,this._subscribed=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()},_updateCachedUser:function(e,t){let n=this._cacheGetUser(e);return n=p(n||{},t),this._cachePutUser(e,n),g(this._users,e,n)},_getQueuedSeqId:function(){return this._queuedSeqId++},_updateDeletedRanges:function(){const e=[];let t=null;const n=this._messages.getAt(0);n&&this._minSeq>1&&!this._noEarlierMsgs?n.hi?(n.seq>1&&(n.seq=1),n.hi{n.seq>=268435455||(n.seq!=(t.hi||t.seq)+1?t.hi?t.hi=n.hi||n.seq:(t={seq:(t.hi||t.seq)+1,hi:n.hi||n.seq},e.push(t)):t=n)});const s=this._messages.getLast(),i=Math.max(this.seq,this._maxSeq)||0;(i>0&&!s||s&&(s.hi||s.seq){this._messages.put(e)})}};var y=function(e){T.call(this,"me",e),this._contacts={},e&&(this.onContactUpdate=e.onContactUpdate)};y.prototype=Object.create(T.prototype,{_processMetaDesc:{value:function(e){const t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();p(this,e),m(this),t&&Object.values(this._contacts).map(e=>{e.online&&(e.online=!1,e.seen?e.seen.when=new Date:e.seen={when:new Date},this.onContactUpdate&&this.onContactUpdate("off",e))}),this.onMetaDesc&&this.onMetaDesc(this)},enumerable:!0,configurable:!0,writable:!1},_processMetaSub:{value:function(e){let t=0;for(let n in e){const s=e[n],i=s.topic;if("fnd"==i||"me"==i)continue;s.updated=new Date(s.updated),s.touched=s.touched?new Date(s.touched):void 0,s.deleted=s.deleted?new Date(s.deleted):null;let o=null;if(s.deleted)o=s,delete this._contacts[i];else if(void 0!==s.seq&&(s.seq=0|s.seq,s.recv=0|s.recv,s.read=0|s.read,s.unread=s.seq-s.read),s.seen&&s.seen.when&&(s.seen.when=new Date(s.seen.when)),o=g(this._contacts,i,s),M.isP2PTopicName(i)&&this._cachePutUser(i,o),!s._noForwarding){const e=this._tinode.getTopic(i);e&&(s._noForwarding=!0,e._processMetaDesc(s))}t++,this.onMetaSub&&this.onMetaSub(o)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts),t)},enumerable:!0,configurable:!0,writable:!1},_processMetaCreds:{value:function(e,t){1==e.length&&e[0]==M.DEL_CHAR&&(e=[]),t?e.map(e=>{if(e.val){let t=this._credentials.findIndex(t=>t.meth==e.meth&&t.val==e.val);t<0?(e.done||(t=this._credentials.findIndex(t=>t.meth==e.meth&&!t.done))>=0&&this._credentials.splice(t,1),this._credentials.push(e)):this._credentials[t].done=e.done}else if(e.resp){const t=this._credentials.findIndex(t=>t.meth==e.meth&&!t.done);t>=0&&(this._credentials[t].done=!0)}}):this._credentials=e,this.onCredsUpdated&&this.onCredsUpdated(this._credentials)},enumerable:!0,configurable:!0,writable:!1},_routePres:{value:function(e){if("term"==e.what)return void this._resetSub();if("upd"==e.what&&"me"==e.src)return void this.getMeta(this.startMetaQuery().withDesc().build());const t=this._contacts[e.src];if(t){switch(e.what){case"on":t.online=!0;break;case"off":t.online&&(t.online=!1,t.seen?t.seen.when=new Date:t.seen={when:new Date});break;case"msg":t.touched=new Date,t.seq=0|e.seq,e.act&&!this._tinode.isMe(e.act)||(t.read=t.read?Math.max(t.read,t.seq):t.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.recv),t.unread=t.seq-t.read;break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":t.acs?t.acs.updateAll(e.dacs):t.acs=(new x).updateAll(e.dacs),t.touched=new Date;break;case"ua":t.seen={when:new Date,ua:e.ua};break;case"recv":e.seq=0|e.seq,t.recv=t.recv?Math.max(t.recv,e.seq):e.seq;break;case"read":e.seq=0|e.seq,t.read=t.read?Math.max(t.read,e.seq):e.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.recv,t.unread=t.seq-t.read;break;case"gone":delete this._contacts[e.src];break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}this.onContactUpdate&&this.onContactUpdate(e.what,t)}else if("acs"==e.what){const t=new x(e.dacs);if(!t||t.mode==x._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==x._NONE)return void this._tinode.logger("WARNING: Removing non-existent subscription",e.src,e.dacs);this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build()),this._contacts[e.src]={touched:new Date,topic:e.src,online:!1,acs:t}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'me' is not supported"))},enumerable:!0,configurable:!0,writable:!1},delCredential:{value:function(e,t){return this._subscribed?this._tinode.delCredential(e,t).then(n=>{const s=this._credentials.findIndex(n=>n.meth==e&&n.val==t);return s>-1&&this._credentials.splice(s,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),n}):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t,n){for(let s in this._contacts){const i=this._contacts[s];t&&!t(i)||e.call(n,i,s,this._contacts)}},enumerable:!0,configurable:!0,writable:!0},setMsgReadRecv:{value:function(e,t,n,s){const i=this._contacts[e];let o,r=!1;if(i){switch(n|=0,i.seq=0|i.seq,i.read=0|i.read,i.recv=0|i.recv,t){case"recv":o=i.recv,i.recv=Math.max(i.recv,n),r=o!=i.recv;break;case"read":o=i.read,i.read=Math.max(i.read,n),r=o!=i.read;break;case"msg":o=i.seq,i.seq=Math.max(i.seq,n),(!i.touched||i.touched0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))},enumerable:!0,configurable:!0,writable:!1},setMeta:{value:function(e){const t=this;return Object.getPrototypeOf(D.prototype).setMeta.call(this,e).then((function(){Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))}))},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t){const n=e||this.onMetaSub;if(n)for(let e in this._contacts)n.call(t,this._contacts[e],e,this._contacts)},enumerable:!0,configurable:!0,writable:!0}}),D.prototype.constructor=D;var R=function(e){this._tinode=e,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._msgId=e.getNextUniqueId(),this.xhr=new XMLHttpRequest,this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null};R.prototype={uploadWithBaseUrl:function(e,t,n,s,i){if(!this._authToken)throw new Error("Must authenticate first");const o=this;let r="/v0/file/u/";if(e){if(0!=e.indexOf("http://")&&0!=e.indexOf("https://"))throw new Error("Invalid base URL '"+e+"'");r=e+r}this.xhr.open("POST",r,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token);const a=new Promise((e,t)=>{this.toResolve=e,this.toReject=t});this.onProgress=n,this.onSuccess=s,this.onFailure=i,this.xhr.upload.onprogress=e=>{e.lengthComputable&&o.onProgress&&o.onProgress(e.loaded/e.total)},this.xhr.onload=function(){let e;try{e=JSON.parse(this.response,_)}catch(t){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(o.toResolve&&o.toResolve(e.ctrl.params.url),o.onSuccess&&o.onSuccess(e.ctrl)):this.status>=400?(o.toReject&&o.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")")),o.onFailure&&o.onFailure(e.ctrl)):o._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){o.toReject&&o.toReject(new Error("failed")),o.onFailure&&o.onFailure(null)},this.xhr.onabort=function(e){o.toReject&&o.toReject(new Error("upload cancelled by user")),o.onFailure&&o.onFailure(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._msgId),this.xhr.send(e)}catch(e){this.toReject&&this.toReject(e),this.onFailure&&this.onFailure(null)}return a},upload:function(e,t,n,s){return this.uploadWithBaseUrl(void 0,e,t,n,s)},download:function(e,t,n,s){if(M.isRelativeURL(e))throw new Error("The URL '"+e+"' must be relative, not absolute");if(!this._authToken)throw new Error("Must authenticate first");const i=this;this.xhr.open("GET",e,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),this.xhr.responseType="blob",this.onProgress=s,this.xhr.onprogress=function(e){i.onProgress&&i.onProgress(e.loaded)};const o=new Promise((e,t)=>{this.toResolve=e,this.toReject=t});this.xhr.onload=function(){if(200==this.status){const e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:n})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),i.toResolve&&i.toResolve()}else if(this.status>=400&&i.toReject){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,_);i.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")"))}catch(e){i._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),i.toReject(e)}},e.readAsText(this.response)}},this.xhr.onerror=function(e){i.toReject&&i.toReject(new Error("failed"))},this.xhr.onabort=function(){i.toReject&&i.toReject(null)};try{this.xhr.send()}catch(e){this.toReject&&this.toReject(e)}return o},cancel:function(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()},getId:function(){return this._msgId}};var A=function(e,t){this.status=A.STATUS_NONE,this.topic=e,this.content=t};A.STATUS_NONE=0,A.STATUS_QUEUED=1,A.STATUS_SENDING=2,A.STATUS_FAILED=3,A.STATUS_SENT=4,A.STATUS_RECEIVED=5,A.STATUS_READ=6,A.STATUS_TO_ME=7,A.prototype={toJSON:function(){},fromJSON:function(e){}},A.prototype.constructor=A,s.exports=M,s.exports.Drafty=i,s.exports.AccessMode=x}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),s=s.exports}));