1 line
69 KiB
JavaScript
1 line
69 KiB
JavaScript
!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={exports:({},function(e,t){let n=[];function s(t,n,s){let i=0,r=n.length-1,o=0,a=0,c=!1;for(;i<=r;)if((a=e(n[o=(i+r)/2|0],t))<0)i=o+1;else{if(!(a>0)){c=!0;break}r=o-1}return c?{idx:o,exact:!0}:s?{idx:-1}:{idx:a<0?o+1:o}}function i(e,n){const i=s(e,n,!1),r=i.exact&&t?1:0;return n.splice(i.idx,r,e),n}return e=e||function(e,t){return e===t?0:e<t?-1:1},{getAt:function(e){return n[e]},getLast:function(){return n.length>0?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 r=t;r<s;r++)e.call(i,n[r],r)},find:function(e,t){const{idx:i}=s(e,n,!t);return i}}})};e=e.exports;var t={exports:{}};(function(e){(function(){"use strict";let n,s;function i(e,t,n,s){let i=null;return"http"!==t&&"https"!==t&&"ws"!==t&&"wss"!==t||(i=t+"://","/"!==(i+=e).charAt(i.length-1)&&(i+="/"),i+="v"+n+"/channels","http"!==t&&"https"!==t||(i+="/lp"),i+="?apikey="+s),i}"undefined"!=typeof WebSocket&&(n=WebSocket),"undefined"!=typeof XMLHttpRequest&&(s=XMLHttpRequest),"undefined"==typeof window&&(e.window={WebSocket:n,XMLHttpRequest:s});const r=function(e,t,s,r,o,a){let c=e,u=t,h=o,l=s,d=a,p=null,f=0,g=!1;const m=(e,...t)=>{this.logger&&this.logger(e,...t)};function _(){clearTimeout(p);const e=Math.pow(2,f)*(1+.3*Math.random())*2e3;f=f>=10?f:f+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),p=setTimeout((()=>{if(m(`Reconnecting, iter=${f}, timeout=${e}`),g)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((()=>{}))}}),e)}function b(){clearTimeout(p),p=null}function w(e){let t=null;e.connect=function(s,r){if(g=!1,t){if(!r&&t.readyState==t.OPEN)return Promise.resolve();t.close(),t=null}return s&&(c=s),new Promise((function(s,r){const o=i(c,h?"wss":"ws",u,l);m("Connecting to: ",o);const a=new n(o);a.onerror=function(e){r(e)},a.onopen=function(t){d&&b(),e.onOpen&&e.onOpen(),s()},a.onclose=function(n){if(t=null,e.onDisconnect){const t=g?418:503;e.onDisconnect(new Error(g?"Disconnected by client":"Connection failed ("+t+")"),t)}!g&&d&&_.call(e)},a.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=a}))},e.reconnect=function(t){b(),e.connect(null,t)},e.disconnect=function(){g=!0,b(),t&&(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 v(e){let t=null,n=null,s=null;e.connect=function(s,r){if(g=!1,n){if(!r)return Promise.resolve();n.onreadystatechange=void 0,n.abort(),n=null}return s&&(c=s),new Promise((function(s,r){const o=i(c,h?"https":"http",u,l);m("Connecting to: ",o),(n=function n(s,i,r){let o=new XMLHttpRequest,a=!1;return o.onreadystatechange=function(c){if(4==o.readyState)if(201==o.status){let r=JSON.parse(o.responseText,jsonParseHelper);t=s+"&sid="+r.ctrl.params.sid,(o=n(t)).send(null),e.onOpen&&e.onOpen(),i&&(a=!0,i()),d&&b()}else if(o.status<400)e.onMessage&&e.onMessage(o.responseText),(o=n(t)).send(null);else{if(r&&!a&&(a=!0,r(o.responseText)),e.onMessage&&o.responseText&&e.onMessage(o.responseText),e.onDisconnect){const t=o.status||(g?418:503),n=o.responseText||(g?"Disconnected by client":"Connection failed");e.onDisconnect(new Error(n+" ("+t+")"),t)}o=null,!g&&d&&_.call(e)}},o.open("GET",s,!0),o}(o,s,r)).send(null)})).catch((e=>{m("LP connection failed:",e)}))},e.reconnect=function(t){b(),e.connect(null,t)},e.disconnect=function(){g=!0,b(),s&&(s.onreadystatechange=void 0,s.abort(),s=null),n&&(n.onreadystatechange=void 0,n.abort(),n=null),e.onDisconnect&&e.onDisconnect(new Error("Disconnected by client (418)"),418),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 M=!1;if("lp"===r?(v(this),M=!0):"ws"===r?(w(this),M=!0):"object"==typeof window&&(window.WebSocket?(w(this),M=!0):window.XMLHttpRequest&&(v(this),M=!0)),!M)throw m("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 m("Request for unknown transport",e),!1}},this.backoffReset=function(){f=0},this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.onAutoreconnectIteration=void 0,this.logger=void 0};r.setNetworkProviders=function(e,t){n=e,s=t},r.NETWORK_ERROR=503,r.NETWORK_ERROR_TEXT="Connection failed",r.NETWORK_USER=418,r.NETWORK_USER_TEXT="Disconnected by client",t.exports=r}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),t=t.exports;var n={exports:({},function(e,t){e=e||function(){},t=t||function(){};let n=null,s=!1;const i=["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","private","touched"];function r(e,t){const n=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(n[e]=t[e])})),n}return{initDatabase:function(){return new Promise(((s,i)=>{const r=indexedDB.open("tinode-web",1);r.onsuccess=e=>{n=e.target.result,s(n)},r.onerror=n=>{t("PCache","failed to initialize",n),i(n.target.error),e&&e(n.target.error)},r.onupgradeneeded=function(s){(n=s.target.result).onerror=function(n){t("PCache","failed to create storage",n),e&&e(n.target.error)},n.createObjectStore("topic",{keyPath:"name"}),n.createObjectStore("user",{keyPath:"uid"}),n.createObjectStore("subscription",{keyPath:["topic","uid"]}),n.createObjectStore("message",{keyPath:["topic","seq"]})}}))},deleteDatabase:function(){return new Promise(((e,n)=>{const s=indexedDB.deleteDatabase("tinode-web");s.onsuccess=function(t){e(!0)},s.onerror=function(e){t("PCache","deleteDatabase",e.target.error),n(e.target.error)}}))},isReady:function(){return!!n},disable:function(){n=null,s=!0},updTopic:function(e){return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["topic"],"readwrite");o.oncomplete=e=>{s(e.target.result)},o.onerror=e=>{t("PCache","updTopic",e.target.error),r(e.target.error)};const a=o.objectStore("topic").get(e.name);a.onsuccess=t=>{o.objectStore("topic").put(function(e,t){const n=e||{name:t.name};return i.forEach((e=>{t.hasOwnProperty(e)&&(n[e]=t[e])})),Array.isArray(t._tags)&&(n.tags=t._tags),t.acs&&(n.acs=t.getAccessMode().jsonHelper()),n}(a.result,e)),o.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remTopic:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["topic","subscription","message"],"readwrite");r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t("PCache","remTopic",e.target.error),i(e.target.error)},r.objectStore("topic").delete(IDBKeyRange.only(e)),r.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),r.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),r.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},mapTopics:function(e,i){return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["topic"]);o.onerror=e=>{t("PCache","mapTopics",e.target.error),r(e.target.error)},o.objectStore("topic").getAll().onsuccess=t=>{e&&t.target.result.forEach((t=>{e.call(i,t)})),s(t.target.result)}})):s?Promise.resolve([]):Promise.reject(new Error("not initialized"))},deserializeTopic:function(e,t){!function(e,t){i.forEach((n=>{t.hasOwnProperty(n)&&(e[n]=t[n])})),Array.isArray(t.tags)&&(e._tags=t.tags),t.acs&&e.setAccessMode(t.acs)}(e,t)},updUser:function(e,i){if(!(arguments.length<2||void 0===i))return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["user"],"readwrite");o.oncomplete=e=>{s(e.target.result)},o.onerror=e=>{t("PCache","updUser",e.target.error),r(e.target.error)},o.objectStore("user").put({uid:e,public:i}),o.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remUser:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["user"],"readwrite");r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t("PCache","remUser",e.target.error),i(e.target.error)},r.objectStore("user").delete(IDBKeyRange.only(e)),r.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},getUser:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["user"]);r.oncomplete=e=>{const t=e.target.result;s({user:t.uid,public:t.public})},r.onerror=e=>{t("PCache","getUser",e.target.error),i(e.target.error)},r.objectStore("user").get(e)})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},updSubscription:function(e,i,r){return this.isReady()?new Promise(((s,o)=>{const a=n.transaction(["subscription"],"readwrite");a.oncomplete=e=>{s(e.target.result)},a.onerror=e=>{t("PCache","updSubscription",e.target.error),o(e.target.error)},a.objectStore("subscription").get([e,i]).onsuccess=t=>{a.objectStore("subscription").put(function(e,t,n,s){const i=e||{topic:t,uid:n};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{s.hasOwnProperty(e)&&(i[e]=s[e])})),i}(t.target.result,e,i,r)),a.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},mapSubscriptions:function(e,i,r){return this.isReady()?new Promise(((s,o)=>{const a=n.transaction(["subscription"]);a.onerror=e=>{t("PCache","mapSubscriptions",e.target.error),o(e.target.error)},a.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{i&&e.target.result.forEach((e=>{i.call(r,e)})),s(e.target.result)}})):s?Promise.resolve([]):Promise.reject(new Error("not initialized"))},addMessage:function(e){return this.isReady()?new Promise(((s,i)=>{const o=n.transaction(["message"],"readwrite");o.onsuccess=e=>{s(e.target.result)},o.onerror=e=>{t("PCache","addMesssage",e.target.error),i(e.target.error)},o.objectStore("message").add(r(null,e)),o.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},updMessageStatus:function(e,i,o){return this.isReady()?new Promise(((s,a)=>{const c=n.transaction(["message"],"readwrite");c.onsuccess=e=>{s(e.target.result)},c.onerror=e=>{t("PCache","updMessageStatus",e.target.error),a(e.target.error)};const u=c.objectStore("message").get(IDBKeyRange.only([e,i]));u.onsuccess=t=>{const n=u.result||t.target.result;n&&n._status!=o?(c.objectStore("message").put(r(n,{topic:e,seq:i,_status:o})),c.commit()):c.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remMessages:function(e,i,r){return this.isReady()?new Promise(((s,o)=>{i||r||(i=0,r=Number.MAX_SAFE_INTEGER);const a=r>0?IDBKeyRange.bound([e,i],[e,r],!1,!0):IDBKeyRange.only([e,i]),c=n.transaction(["message"],"readwrite");c.onsuccess=e=>{s(e.target.result)},c.onerror=e=>{t("PCache","remMessages",e.target.error),o(e.target.error)},c.objectStore("message").delete(a),c.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},readMessages:function(e,i,r,o){return this.isReady()?new Promise(((s,a)=>{const c=(i=i||{}).from>0?i.from:0,u=i.to>0?i.to:Number.MAX_SAFE_INTEGER,h=0|i.limit,l=[],d=IDBKeyRange.bound([e,c],[e,u],!1,!0),p=n.transaction(["message"]);p.onerror=e=>{t("PCache","readMessages",e.target.error),a(e.target.error)},p.objectStore("message").openCursor(d,"prev").onsuccess=e=>{const t=e.target.result;t?(r&&r.call(o,t.value),l.push(t.value),h<=0||l.length<h?t.continue():s(l)):s(l)}})):s?Promise.resolve([]):Promise.reject(new Error("not initialized"))}}})};n=n.exports;var s={exports:{}};const i=[{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)/}],r=[{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}],o={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},HL:{name:"span",isVoid:!1}};function a(e,t,n){if(!e)return null;try{const n=atob(e),s=n.length,i=new ArrayBuffer(s),r=new Uint8Array(i);for(let e=0;e<s;e++)r[e]=n.charCodeAt(e);return URL.createObjectURL(new Blob([i],{type:t}))}catch(e){n&&n("Drafty: failed to convert object.",e.message)}return null}function c(e,t){return e?"data:"+(t=t||"image/jpeg")+";base64,"+e:null}const u={ST:{open:function(){return"<b>"},close:function(){return"</b>"}},EM:{open:function(){return"<i>"},close:function(){return"</i>"}},DL:{open:function(){return"<del>"},close:function(){return"</del>"}},CO:{open:function(){return"<tt>"},close:function(){return"</tt>"}},BR:{open:function(){return"<br/>"},close:function(){return""}},HD:{open:function(){return""},close:function(){return""}},HL:{open:function(){return'<span style="color:teal">'},close:function(){return"</span>"}},LN:{open:function(e){return'<a href="'+e.url+'">'},close:function(e){return"</a>"},props:function(e){return e?{href:e.url,target:"_blank"}:null}},MN:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{name:e.val}:null}},HT:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{name:e.val}:null}},BN:{open:function(e){return"<button>"},close:function(e){return"</button>"},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=c(e._tempPreview,e.mime),n=a(e.val,e.mime,h.logger),s=e.ref||n;return(e.name?'<a href="'+s+'" download="'+e.name+'">':"")+'<img src="'+(t||n)+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"':"")+' border="0" />'},close:function(e){return e.name?"</a>":""},props:function(e){return e?{src:c(e._tempPreview,e.mime)||e.ref||a(e.val,e.mime,h.logger),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|e.size,"data-mime":e.mime}:null}},FM:{open:function(e){return"<div>"},close:function(e){return"</div>"}},RW:{open:function(e){return"<div>"},close:function(e){return"</div>"}}},h=function(){};h.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),n=[],s={},o=[];t.map((function(e){let t,a,c=[];if(i.map((function(t){c=c.concat(function(e,t,n,s){const i=[];let r=0,o=e.slice(0);for(;o.length>0;){const a=t.exec(o);if(null==a)break;let c=a.index+a[0].lastIndexOf(a[1]);o=o.slice(c+1),r=(c+=r)+1;const u=n?n.exec(o):null;if(null==u)break;let h=u.index+u[0].indexOf(u[1]);o=o.slice(h+1),r=(h+=r)+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;e<t.length;e++)t[e].start>s.end?(n.push(t[e]),s=t[e]):t[e].end<s.end&&s.children.push(t[e]);for(let t in n)n[t].children=e(n[t].children);return n}(c);const t=function e(t,n){let s="",i=[];for(let r in t){const o=t[r];if(!o.text){const t=e(o.children,s.length+n);o.text=t.txt,i=i.concat(t.fmt)}o.type&&i.push({at:s.length+n,len:o.text.length,tp:o.type}),s+=o.text}return{txt:s,fmt:i}}(function e(t,n,s,i){const r=[];if(0==i.length)return[];for(let s in i){const o=i[s];o.start>n&&r.push({text:t.slice(n,o.start)});const a={type:o.type},c=e(t,o.start+1,o.end,o.children);c.length>0?a.children=c:a.text=o.text,r.push(a),n=o.end+1}return n<s&&r.push({text:t.slice(n,s)}),r}(e,0,e.length,c),0);a={txt:t.txt,fmt:t.fmt}}if((t=function(e){let t,n=[];if(r.map((function(s){for(;null!==(t=s.re.exec(e));)n.push({offset:t.index,len:t[0].length,unique:t[0],data:s.pack(t[0]),type:s.name})})),0==n.length)return n;n.sort((function(e,t){return e.offset-t.offset}));let s=-1;return n=n.filter((function(e){const t=e.offset>s;return s=e.offset+e.len,t}))}(a.txt)).length>0){const e=[];for(let i in t){const r=t[i];let o=s[r.unique];o||(o=n.length,s[r.unique]=o,n.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:o})}a.ent=e}o.push(a)}));const a={txt:""};if(o.length>0){a.txt=o[0].txt,a.fmt=(o[0].fmt||[]).concat(o[0].ent||[]);for(let e=1;e<o.length;e++){const t=o[e],n=a.txt.length+1;a.fmt.push({tp:"BR",len:1,at:n-1}),a.txt+=" "+t.txt,t.fmt&&(a.fmt=a.fmt.concat(t.fmt.map((function(e){return e.at+=n,e})))),t.ent&&(a.fmt=a.fmt.concat(t.ent.map((function(e){return e.at+=n,e}))))}0==a.fmt.length&&delete a.fmt,n.length>0&&(a.ent=n)}return a},h.init=function(e){return"string"!=typeof e?null:{txt:e}},h.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},h.insertImage=function(e,t,n){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:1,key:e.ent.length});const s={tp:"IM",data:{mime:n.mime,val:n.preview,width:n.width,height:n.height,name:n.filename,size:0|n.size,ref:n.refurl}};return n.urlPromise&&(s.data._tempPreview=n._tempPreview,s.data._processing=!0,n.urlPromise.then((e=>{s.data.ref=e,s.data._tempPreview=void 0,s.data._processing=void 0}),(e=>{s.data._processing=void 0}))),e.ent.push(s),e},h.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",h.insertImage(e,e.txt.length-1,t)},h.attachFile=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});const n={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(n.data._processing=!0,t.urlPromise.then((e=>{n.data.ref=e,n.data._processing=void 0}),(e=>{n.data._processing=void 0}))),e.ent.push(n),e},h.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},h.insertButton=function(e,t,n,s,i,r,o){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length<t+n||n<=0||-1==["url","pub"].indexOf(i)?null:"url"!=i||o?(o=""+o,e.ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:n,key:e.ent.length}),e.ent.push({tp:"BN",data:{act:i,val:r,ref:o,name:s}}),e):null},h.appendButton=function(e,t,n,s,i,r){const o=(e=e||{txt:""}).txt.length;return e.txt+=t,h.insertButton(e,o,t.length,n,s,i,r)},h.attachJSON=function(e,t){return(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length}),e.ent.push({tp:"EX",data:{mime:"application/json",val:t}}),e},h.appendLineBreak=function(e){return(e=e||{txt:""}).fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:1,tp:"BR"}),e.txt+=" ",e},h.UNSAFE_toHTML=function(e){let{txt:t,fmt:n,ent:s}=e;const i=[];if(n)for(let e in n){const t=n[e],r=0|t.at;let o,a=t.tp;if(!a){const e=s[0|t.key];e&&(a=e.tp,o=e.data)}u[a]&&(i.push({idx:r+t.len,len:-t.len,what:u[a].close(o)}),i.push({idx:r,len:t.len,what:u[a].open(o)}))}i.sort((function(e,t){return t.idx==e.idx?t.len-e.len:t.idx-e.idx}));for(let e in i)i[e].what&&(r=t,o=i[e].idx,a=i[e].what,t=r.slice(0,o)+a+r.slice(o));var r,o,a;return t},h.format=function(e,t,n){let{txt:s,fmt:i,ent:r}=e;if(s=s||"",Array.isArray(r)||(r=[]),!Array.isArray(i)){if(1!=r.length)return[s];i=[{at:0,len:0,key:0}]}let a=[].concat(i);return a.map((function(e){e.at=e.at||0,e.len=e.len||0,e.len<0&&(e.len=0),e.at<-1&&(e.at=-1)})),a.sort((function(e,t){return e.at-t.at==0?t.len-e.len:e.at-t.at})),a=a.map((e=>{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,i,r,a){const c=[];for(let s=0;s<i.length;s++){const u=i[s];if(u.at<0){const e=r.call(a,u.tp,u.data,void 0,c.length);e&&c.push(e);continue}n<u.at&&(c.push(r.call(a,null,void 0,t.slice(n,u.at),c.length)),n=u.at);const h=[];for(let e=s+1;e<i.length&&i[e].at<u.at+u.len;e++)h.push(i[e]),s=e;const l=o[u.tp]||{};c.push(r.call(a,u.tp,u.data,l.isVoid?null:e(t,n,u.at+u.len,h,r,a),c.length)),n=u.at+u.len}return n<s&&c.push(r.call(a,null,void 0,t.slice(n,s),c.length)),c}(s,0,s.length,a,t,n)},h.toPlainText=function(e){return"string"==typeof e?e:e.txt},h.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},h.isValid=function(e){if(!e)return!1;const{txt:t,fmt:n,ent:s}=e;if(!t&&""!==t&&!n&&!s)return!1;const i=typeof t;return!("string"!=i&&"undefined"!=i&&null!==t||void 0!==n&&!Array.isArray(n)&&null!==n||void 0!==s&&!Array.isArray(s)&&null!==s)},h.hasAttachments=function(e){if(e.ent&&e.ent.length>0)for(let t in e.ent)if(e.ent[t]&&"EX"==e.ent[t].tp)return!0;return!1},h.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(let s in e.ent)e.ent[s]&&"EX"==e.ent[s].tp&&t.call(n,e.ent[s].data,s)},h.getDownloadUrl=function(e){let t=null;return"application/json"!=e.mime&&e.val?t=a(e.val,e.mime,h.logger):"string"==typeof e.ref&&(t=e.ref),t},h.isProcessing=function(e){return!!e._processing},h.getPreviewUrl=function(e){return e.val?a(e.val,e.mime,h.logger):null},h.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},h.getEntityMimeType=function(e){return e.mime||"text/plain"},h.tagName=function(e){return e?o[e]?o[e].name:"_UNKN":void 0},h.attrValue=function(e,t){if(t&&u[e])return u[e].props(t)},h.getContentType=function(){return"text/x-drafty"},h.preview=function(e,t){if(!e||t<=0||"object"!=typeof e)return null;const{txt:n,fmt:s,ent:i}=e,r={txt:""};let o=0;if("string"==typeof n&&(n.length>t?r.txt=n.substr(0,t):r.txt=n,o=r.txt.length),Array.isArray(s)&&s.length>0){const e=[];let t=0,n=0;if(s.forEach((s=>{if(s.at<o&&(t++,!s.tp)){const t=0|s.key;e[t]||(e[t]=n,n++)}})),0==t)return r;r.fmt=[],Array.isArray(i)&&e.length>0&&(r.ent=[]);let a=0;s.forEach((t=>{if(t.at<o){const n={at:t.at,len:t.len},s=0|t.key;if(t.tp)n.tp=""+t.tp;else{if(!(Array.isArray(i)&&i.length>s&&"number"==typeof e[s]))return;n.key=e[s],r.ent[n.key]=function(e){let t={tp:e.tp};if(e.data&&0!=Object.entries(e.data).length){const n={};["mime","name","width","height","size"].forEach((t=>{const s=e.data[t];s&&(n[t]=s)})),0!=Object.entries(n).length&&(t.data=n)}return t}(i[s])}r.fmt[a++]=n}}))}return r},s.exports=h,s=s.exports;var l={exports:{}};return function(i){(function(){"use strict";let r,o;"undefined"!=typeof WebSocket&&(r=WebSocket),"undefined"!=typeof XMLHttpRequest&&(o=XMLHttpRequest),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(i.btoa=function(t=""){let n=t,s="";for(let t,i=0,r=0,o=e;n.charAt(0|r)||(o="=",r%1);s+=o.charAt(63&i>>8-r%1*8)){if((t=n.charCodeAt(r+=.75))>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");i=i<<8|t}return s}),"undefined"==typeof atob&&(i.atob=function(t=""){let n=t.replace(/=+$/,""),s="";if(n.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let t,i=0,r=0,o=0;t=n.charAt(o++);~t&&(r=i%4?64*r+t:t,i++%4)?s+=String.fromCharCode(255&r>>(-2*i&6)):0)t=e.indexOf(t);return s}),"undefined"==typeof window&&(i.window={WebSocket:r,XMLHttpRequest:o,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),t.setNetworkProviders(r,o)}();const a="0.17.0-alpha3",c="tinodejs/"+a;function u(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function h(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<t)?e:t;if(t instanceof b)return new b(t);if(t instanceof Array)return t;e&&e!==m.DEL_CHAR||(e=t.constructor());for(let s in t)!t.hasOwnProperty(s)||n&&n[s]||"_noForwarding"==s||(e[s]=h(e[s],t[s]));return e}function d(e,t,n,s){return e[t]=h(e[t],n,s),e[t]}function p(e){"string"==typeof e.created&&(e.created=new Date(e.created)),"string"==typeof e.updated&&(e.updated=new Date(e.updated)),"string"==typeof e.touched&&(e.touched=new Date(e.touched))}function f(e,t){if("ts"===e&&"string"==typeof t&&t.length>=20&&t.length<=24){let e=new Date(t);if(e)return e}else if("acs"===e&&"object"==typeof t)return new b(t);return t}function g(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 b)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)}var m=function(e,i){this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._browser="",this._platform=e.platform||"web",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(" "),r=[];for(let e=0;e<n.length;e++){let s=/([\w.]+)[\/]([\.\d]+)/.exec(n[e]);s&&r.push([s[1],s[2],t.findIndex((function(e){return e==s[1].toLowerCase()}))])}r.sort((function(e,t){let n=e[2]-t[2];return 0!=n?n:t[0].length-e[0].length})),s=r.length>0?r[0][0]+"/"+r[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 t(e.host,"0",e.apiKey,e.transport,e.secure,!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,s.logger=this.logger,this._lastTopicUpdate=null,this._cache={};const r=this.cachePut=(e,t,n)=>{this._cache[e+":"+t]=n},o=this.cacheGet=(e,t)=>this._cache[e+":"+t],u=this.cacheDel=(e,t)=>{delete this._cache[e+":"+t]},l=this.cacheMap=(e,t,n)=>{const s=e?e+":":void 0;for(let e in this._cache)if((!s||0==e.indexOf(s))&&t.call(n,this._cache[e],e))break};this.attachCacheToTopic=e=>{e._tinode=this,e._cacheGetUser=e=>{const t=o("user",e);if(t)return{user:e,public:h({},t)}},e._cachePutUser=(e,t)=>r("user",e,h({},t.public)),e._cacheDelUser=e=>u("user",e),e._cachePutSelf=()=>(e.updated&&e.updated>this._lastTopicUpdate&&(this._lastTopicUpdate=e.updated),r("topic",e.name,e)),e._cacheDelSelf=()=>u("topic",e.name)},this._persist=e.persist,this._db=n((e=>{this.logger("DB",e)}),this.logger),this._persist?this._db.initDatabase().then((()=>{const e=[];return this._db.mapTopics((t=>{let n=this.cacheGet("topic",t.name);n||(n="me"==t.name?new v:"fnd"==t.name?new M:new w(t.name),this._db.deserializeTopic(n,t),this.attachCacheToTopic(n),n._cachePutSelf(),e.push(n._loadMessages(this._db)))})).then((()=>Promise.all(e))).then((()=>{i&&i(),this.logger("Persistent cache initialized.")}))})):this._db.disable();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})`)))},p=e=>{let t=null;return e&&(t=new Promise(((t,n)=>{this._pendingPromises[e]={resolve:t,reject:n,ts:new Date}}))),t},m=this.getNextUniqueId=()=>0!=this._messageId?""+this._messageId++:void 0,_=()=>this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+c;this.initPacket=(e,t)=>{switch(e){case"hi":return{hi:{id:m(),ver:a,ua:_(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:m(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:m(),scheme:null,secret:null}};case"sub":return{sub:{id:m(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:m(),topic:t,unsub:!1}};case"pub":return{pub:{id:m(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:m(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:m(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:m(),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,n)=>{let s;n&&(s=p(n)),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 i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,g):i));try{this._connection.sendText(i)}catch(e){if(!n)throw e;d(n,t.NETWORK_ERROR,null,e.message)}return s},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),e):e,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,f);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,g):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=o("topic",t.ctrl.topic);e&&(e._resetSub(),t.ctrl.params&&t.ctrl.params.unsub&&e._gone())}else if(t.ctrl.params&&"data"==t.ctrl.params.what){const e=o("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if(t.ctrl.params&&"sub"==t.ctrl.params.what){const e=o("topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((()=>{if(t.meta){const e=o("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=o("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=o("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=o("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<t&&(this.logger("Promise expired",n),delete this._pendingPromises[n],s.reject&&s.reject(e))}}),1e3)),this.hello()},this._connection.onAutoreconnectIteration=(e,t)=>{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("topic",((e,t)=>{e._resetSub()}));for(let t in this._pendingPromises){const 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.isMeTopicName=function(e){return"me"==m.topicType(e)},m.isGroupTopicName=function(e){return"grp"==m.topicType(e)},m.isP2PTopicName=function(e){return"p2p"==m.topicType(e)},m.isCommTopicName=function(e){return m.isP2PTopicName(e)||m.isGroupTopicName(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 a},m.setNetworkProviders=function(e,t){r=e,o=t},m.getLibrary=function(){return c},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()},clearStorage:function(){this._db&&this._db.deleteDatabase()},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 r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=n,r.acc.login=s,i&&(r.acc.desc.defacs=i.defacs,r.acc.desc.public=i.public,r.acc.desc.private=i.private,r.acc.tags=i.tags,r.acc.cred=i.cred,r.acc.token=i.token),this.send(r,r.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)))),i},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",u(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,s){return t=t||"",n=n||"",this.account(e,"basic",u(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){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(this.send({hi:{dev:e||m.DEL_CHAR}}),t=!0)),t},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)))},loginBasic:function(e,t,n){return this.login("basic",u(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",u(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 i=this.initPacket("pub",e);let r="string"==typeof t?s.parse(t):t;return r&&!s.isPlainText(r)&&(i.pub.head={mime:s.getContentType()},t=r),i.pub.noecho=n,i.pub.content=t,i.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=h(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)},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 v:"fnd"==e?new M:new w(e),this._db.updTopic(t),this.attachCacheToTopic(t),t._cachePutSelf()),t},isTopicCached:function(e){return!!this.cacheGet("topic",e)},newGroupTopicName:function(e){return(e?"nch":"new")+this.getNextUniqueId()},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new S(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.cacheGet("topic",e);return t&&t.online},getTopicAccessMode:function(e){const t=this.cacheGet("topic",e);return t?t.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 _=function(e){this.topic=e,this.what={}};_.prototype={_get_desc_ims:function(){const e=this.topic._lastDescUpdate||0;return this.topic.updated>e?this.topic.updated:e},_get_subs_ims:function(){if(this.topic.isP2PType())return this._get_desc_ims();if(this.topic.isMeType()){const e=this.topic._tinode._lastTopicUpdate||0;if(e>this.topic._lastSubsUpdate)return e}return this.topic._lastSubsUpdate},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_desc_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._get_subs_ims(),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 b=function(e){e&&(this.given="number"==typeof e.given?e.given:b.decode(e.given),this.want="number"==typeof e.want?e.want:b.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:b.decode(e.mode):this.given&this.want)};b._NONE=0,b._JOIN=1,b._READ=2,b._WRITE=4,b._PRES=8,b._APPROVE=16,b._SHARE=32,b._DELETE=64,b._OWNER=128,b._BITMASK=b._JOIN|b._READ|b._WRITE|b._PRES|b._APPROVE|b._SHARE|b._DELETE|b._OWNER,b._INVALID=1048576,b._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}'`)},b.decode=function(e){if(!e)return null;if("number"==typeof e)return e&b._BITMASK;if("N"===e||"n"===e)return b._NONE;const t={J:b._JOIN,R:b._READ,W:b._WRITE,P:b._PRES,A:b._APPROVE,S:b._SHARE,D:b._DELETE,O:b._OWNER};let n=b._NONE;for(let s=0;s<e.length;s++){const i=t[e.charAt(s).toUpperCase()];i&&(n|=i)}return n},b.encode=function(e){if(null===e||e===b._INVALID)return null;if(e===b._NONE)return"N";const t=["J","R","W","P","A","S","D","O"];let n="";for(let s=0;s<t.length;s++)0!=(e&1<<s)&&(n+=t[s]);return n},b.update=function(e,t){if(!t||"string"!=typeof t)return e;let n=t.charAt(0);if("+"==n||"-"==n){let s=e;const i=t.split(/([-+])/);for(let t=1;t<i.length-1;t+=2){n=i[t];const r=b.decode(i[t+1]);if(r==b._INVALID)return e;null!=r&&("+"===n?s|=r:"-"===n&&(s&=~r))}e=s}else{const n=b.decode(t);n!=b._INVALID&&(e=n)}return e},b.diff=function(e,t){return e=b.decode(e),t=b.decode(t),e==b._INVALID||t==b._INVALID?b._INVALID:e&~t},b.prototype={toString:function(){return'{"mode": "'+b.encode(this.mode)+'", "given": "'+b.encode(this.given)+'", "want": "'+b.encode(this.want)+'"}'},jsonHelper:function(){return{mode:b.encode(this.mode),given:b.encode(this.given),want:b.encode(this.want)}},setMode:function(e){return this.mode=b.decode(e),this},updateMode:function(e){return this.mode=b.update(this.mode,e),this},getMode:function(){return b.encode(this.mode)},setGiven:function(e){return this.given=b.decode(e),this},updateGiven:function(e){return this.given=b.update(this.given,e),this},getGiven:function(){return b.encode(this.given)},setWant:function(e){return this.want=b.decode(e),this},updateWant:function(e){return this.want=b.update(this.want,e),this},getWant:function(){return b.encode(this.want)},getMissing:function(){return b.encode(this.want&~this.given)},getExcessive:function(){return b.encode(this.given&~this.want)},updateAll:function(e){return e&&(this.updateGiven(e.given),this.updateWant(e.want),this.mode=this.given&this.want),this},isOwner:function(e){return b._checkFlag(this,e,b._OWNER)},isPresencer:function(e){return b._checkFlag(this,e,b._PRES)},isMuted:function(e){return!this.isPresencer(e)},isJoiner:function(e){return b._checkFlag(this,e,b._JOIN)},isReader:function(e){return b._checkFlag(this,e,b._READ)},isWriter:function(e){return b._checkFlag(this,e,b._WRITE)},isApprover:function(e){return b._checkFlag(this,e,b._APPROVE)},isAdmin:function(e){return this.isOwner(e)||this.isApprover(e)},isSharer:function(e){return this.isAdmin(e)||b._checkFlag(this,e,b._SHARE)},isDeleter:function(e){return b._checkFlag(this,e,b._DELETE)}};var w=function(t,n){this._tinode=null,this.name=t,this.created=null,this.updated=null,this.touched=null,this.acs=new b(null),this.private=null,this.public=null,this._users={},this._queuedSeqId=268435455,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._tags=[],this._credentials=[],this._messages=e((function(e,t){return e.seq-t.seq}),!0),this._subscribed=!1,this._lastDescUpdate=null,this._lastSubsUpdate=null,this._new=!0,n&&(this.onData=n.onData,this.onMeta=n.onMeta,this.onPres=n.onPres,this.onInfo=n.onInfo,this.onMetaDesc=n.onMetaDesc,this.onMetaSub=n.onMetaSub,this.onSubsUpdated=n.onSubsUpdated,this.onTagsUpdated=n.onTagsUpdated,this.onCredsUpdated=n.onCredsUpdated,this.onDeleteTopic=n.onDeleteTopic,this.onAllMessagesReceived=n.onAllMessagesReceived)};w.prototype={isSubscribed:function(){return this._subscribed},subscribe:function(e,t){return this._subscribed?Promise.resolve(this):this._tinode.subscribe(this.name||"new",e,t).then((e=>{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 e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}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(s.hasAttachments(e.content)&&!e.head.attachments){let t=[];s.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._tinode._db.addMessage(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",t),e._sending=!1,e._failed=!0,this._messages.delAt(this._messages.find(e)),this._tinode._db.remMessages(this.name,e.seq),this.onData&&this.onData()}))},leave:function(e){return this._subscribed||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&(this._tinode._db.remTopic(this.name),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;n<s;n++){let s=e[n];s&&(s=s.trim().toLowerCase()).length>1&&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.low||e.low==t.low&&(!t.hi||e.hi>=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._users[this._tinode.getCurrentUserID()];let s=!1;n?(!n[e]||n[e]<t)&&(n[e]=t,s=!0):s=(0|this[e])<t,s&&(this._tinode.note(this.name,e,t),this._updateReadRecv(e,t),null!=this.acs&&!this.acs.isMuted())&&this._tinode.getMeTopic()._refreshContact(e,this)},noteRecv:function(e){this.note("recv",e)},noteRead:function(e){(e=e||this._maxSeq)>0&&this.note("read",e)},noteKeyPress:function(){this._subscribed?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")},_updateReadRecv:function(e,t,n){let s,i=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":s=this.recv,this.recv=Math.max(this.recv,t),i=s!=this.recv;break;case"read":s=this.read,this.read=Math.max(this.read,t),i=s!=this.read;break;case"msg":s=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched<n)&&(this.touched=n),i=s!=this.seq}return this.recv<this.read&&(this.recv=this.read,i=!0),this.seq<this.recv&&(this.seq=this.recv,(!this.touched||this.touched<n)&&(this.touched=n),i=!0),this.unread=this.seq-this.read,i},userDesc:function(e){const t=this._cacheGetUser(e);if(t)return t},p2pPeerDesc:function(){if(this.isP2PType())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,r="number"==typeof n?this._messages.find({seq:n},!0):void 0;-1!=e&&-1!=r&&this._messages.forEach(i,e,r,s)}},latestMessage:function(){return this._messages.getLast()},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 r=this._users[i];r.user!==s&&r[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});if(t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)},swapMessageId:function(e,t){const n=this._messages.find(e),s=this._messages.length();0<=n&&n<s&&(this._messages.delAt(n),this._tinode._db.remMessages(this.name,e.seq),e.seq=t,this._messages.put(e),this._tinode._db.addMessage(e))},flushMessageRange:function(e,t){this._tinode._db.remMessages(this.name,e,t);const n=this._messages.find({seq:e},!0);return n>=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 n=this._messages.getAt(t),s=this.msgStatus(n);if(1==s||3==s)return this._tinode._db.remMessages(this.name,e),n._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},setAccessMode:function(e){return this.acs=new b(e)},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new _(this)},isArchived:function(){return!(!this.private||!this.private.arch)},isMeType:function(){return m.isMeTopicName(this.name)},isChannelType:function(){return m.isChannelTopicName(this.name)},isGroupType:function(){return m.isGroupTopicName(this.name)},isP2PType:function(){return m.isP2PTopicName(this.name)},isCommType:function(){return m.isCommTopicName(this.name)},msgStatus:function(e,t){let n=0;return this._tinode.isMe(e.from)?e._sending?n=2:e._failed||e._cancelled?n=3:e.seq>=268435455?n=1:this.msgReadCount(e.seq)>0?n=6:this.msgRecvCount(e.seq)>0?n=5:e.seq>0&&(n=4):n=7,t&&e._status!=n&&(e._status=n,this._tinode._db.updMessageStatus(this.name,e.seq,n)),n},_routeData:function(e){e.content&&(!this.touched||this.touched<e.ts)&&(this.touched=e.ts),e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq),e._noForwarding||(this._messages.put(e),this._tinode._db.addMessage(e),this._updateDeletedRanges()),this.onData&&this.onData(e);const t=!this.isChannelType()&&!e.from||this._tinode.isMe(e.from)?"read":"msg";this._updateReadRecv(t,e.seq,e.ts),this._tinode.getMeTopic()._refreshContact(t,this)},_routeMeta:function(e){e.desc&&(this._lastDescUpdate=e.ts,this._processMetaDesc(e.desc)),e.sub&&e.sub.length>0&&(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 b).updateAll(e.dacs);s&&s.mode!=b._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];t&&(t[e.what]=e.seq,t.recv<t.read&&(t.recv=t.read));const n=this.latestMessage();n&&this.msgStatus(n,!0),this._tinode.isMe(e.from)&&this._updateReadRecv(e.what,e.seq),this._tinode.getMeTopic()._refreshContact(e.what,this)}this.onInfo&&this.onInfo(e)},_processMetaDesc:function(e){if(this.isP2PType()&&(delete e.defacs,this._tinode._db.updUser(this.name,e.public)),h(this,e),p(this),this._tinode._db.updTopic(this),"me"!==this.name&&!e._noForwarding){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}this.onMetaDesc&&this.onMetaDesc(this)},_processMetaSub:function(e){for(let t in e){const n=e[t];n.updated=new Date(n.updated),n.deleted=n.deleted?new Date(n.deleted):null,n.online=!!n.online;let s=null;n.deleted?(delete this._users[n.user],s=n):(this._tinode.isMe(n.user)&&n.acs&&this._processMetaDesc({updated:n.updated||new Date,touched:n.updated,acs:n.acs}),s=this._updateCachedUser(n.user,n)),this.onMetaSub&&this.onMetaSub(s)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))},_processMetaTags:function(e){1==e.length&&e[0]==m.DEL_CHAR&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)},_processMetaCreds:function(e){},_processDelMessages:function(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);const n=this;let s=0;Array.isArray(t)&&t.map((function(e){if(e.hi)for(let t=e.low;t<e.hi;t++)s++,n.flushMessage(t);else s++,n.flushMessage(e.low)})),s>0&&(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._tinode._db.remMessages(this.name),this._users={},this.acs=new b(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=h(n||{},t),this._cachePutUser(e,n),d(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<this._minSeq-1&&(n.hi=this._minSeq-1),t=n):(t={seq:1,hi:this._minSeq-1},e.push(t)):t={seq:0,hi:0},this._messages.forEach((n=>{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)<i)&&(s&&s.hi?s.hi=i:e.push({seq:s?s.seq+1:1,hi:i})),e.map((e=>{this._messages.put(e)}))},_loadMessages:function(e){return e.readMessages(this.name,{limit:24}).then((e=>(e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq),this._messages.put(e)})),this._updateDeletedRanges(),this.name)))}};var v=function(e){w.call(this,"me",e),e&&(this.onContactUpdate=e.onContactUpdate)};v.prototype=Object.create(w.prototype,{_processMetaDesc:{value:function(e){const t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();h(this,e),this._tinode._db.updTopic(this),p(this),t&&this._tinode.cacheMap("topic",(e=>{e.online&&(e.online=!1,e.seen?e.seen.when=new Date:e.seen={when:new Date},this._refreshContact("off",e))})),this.onMetaDesc&&this.onMetaDesc(this)},enumerable:!0,configurable:!0},_processMetaSub:{value:function(e){let t=0;if(e.forEach((e=>{const n=e.topic;if("fnd"==n||"me"==n)return;e.updated=new Date(e.updated),e.touched=e.touched?new Date(e.touched):void 0,e.deleted=e.deleted?new Date(e.deleted):null,e.online=!!e.online;let s=null;if(e.deleted)s=e,this._tinode.cacheDel("topic",n),this._tinode._db.remTopic(n);else if(void 0!==e.seq&&(e.seq=0|e.seq,e.recv=0|e.recv,e.read=0|e.read,e.unread=e.seq-e.read),e.seen&&e.seen.when&&(e.seen.when=new Date(e.seen.when)),s=h(this._tinode.getTopic(n),e),this._tinode._db.updTopic(s),m.isP2PTopicName(n)&&(this._cachePutUser(n,s),this._tinode._db.updUser(n,s.public)),!e._noForwarding){const t=this._tinode.getTopic(n);t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(s)})),this.onSubsUpdated&&t>0){const n=[];e.forEach((e=>{n.push(e.topic)})),this.onSubsUpdated(n,t)}},enumerable:!0,configurable:!0},_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},_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._tinode.cacheGet("topic",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.read),t.unread=t.seq-(0|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 b).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":this._tinode.cacheDel("topic",e.src),this._tinode._db.remTopic(e.src);break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}this._refreshContact(e.what,t)}else if("acs"==e.what){const t=new b(e.dacs);if(!t||t.mode==b._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==b._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());const n=this._tinode.getTopic(e.src);n.touched=new Date,n.topic=e.src,n.online=!1,n.acs=t,this._tinode.attachCacheToTopic(n),n._cachePutSelf(),this._db.updTopic(n)}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)},enumerable:!0,configurable:!0},_refreshContact:{value:function(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)},enumerable:!0,configurable:!0},publish:{value:function(){return Promise.reject(new Error("Publishing to 'me' is not supported"))},enumerable:!0,configurable:!0},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},contacts:{value:function(e,t,n){this._tinode.cacheMap("topic",((s,i)=>{!s.isCommType()||t&&!t(s)||e.call(n,s,i)}))},enumerable:!0,configurable:!0},getContact:{value:function(e){return this._tinode.cacheGet("topic",e)},enumerable:!0,configurable:!0},getAccessMode:{value:function(e){if(e){const t=this._tinode.cacheGet("topic",e);return t?t.acs:null}return this.acs},enumerable:!0,configurable:!0},isArchived:{value:function(e){const t=this._tinode.cacheGet("topic",e);return t?!(!t.private||!t.private.arch):null},enumerable:!0,configurable:!0},getCredentials:{value:function(){return this._credentials},enumerable:!0,configurable:!0}}),v.prototype.constructor=v;var M=function(e){w.call(this,"fnd",e),this._contacts={}};M.prototype=Object.create(w.prototype,{_processMetaSub:{value:function(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let n in e){let s=e[n];const i=s.topic?s.topic:s.user;s.updated=new Date(s.updated),s.seen&&s.seen.when&&(s.seen.when=new Date(s.seen.when)),s=d(this._contacts,i,s),t++,this.onMetaSub&&this.onMetaSub(s)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0},publish:{value:function(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))},enumerable:!0,configurable:!0},setMeta:{value:function(e){const t=this;return Object.getPrototypeOf(M.prototype).setMeta.call(this,e).then((function(){Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))}))},enumerable:!0,configurable:!0},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}}),M.prototype.constructor=M;var S=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};S.prototype={uploadWithBaseUrl:function(e,t,n,s,i){if(!this._authToken)throw new Error("Must authenticate first");const r=this;let o="/v0/file/u/";if(e){if(0!=e.indexOf("http://")&&0!=e.indexOf("https://"))throw new Error(`Invalid base URL '${e}'`);o=e+o}this.xhr.open("POST",o,!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&&r.onProgress&&r.onProgress(e.loaded/e.total)},this.xhr.onload=function(){let e;try{e=JSON.parse(this.response,f)}catch(t){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(r.toResolve&&r.toResolve(e.ctrl.params.url),r.onSuccess&&r.onSuccess(e.ctrl)):this.status>=400?(r.toReject&&r.toReject(new Error(`${e.ctrl.text} (${e.ctrl.code})`)),r.onFailure&&r.onFailure(e.ctrl)):r._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed")),r.onFailure&&r.onFailure(null)},this.xhr.onabort=function(e){r.toReject&&r.toReject(new Error("upload cancelled by user")),r.onFailure&&r.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,i){if(!m.isRelativeURL(e))return void(i&&i(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(i&&i("Must authenticate first"));const r=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){r.onProgress&&r.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),r.toResolve&&r.toResolve()}else if(this.status>=400&&r.toReject){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,f);r.toReject(new Error(`${e.ctrl.text} (${e.ctrl.code})`))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),r.toReject(e)}},e.readAsText(this.response)}},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed"))},this.xhr.onabort=function(){r.toReject&&r.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 y=function(e,t){this.status=y.STATUS_NONE,this.topic=e,this.content=t};y.STATUS_NONE=0,y.STATUS_QUEUED=1,y.STATUS_SENDING=2,y.STATUS_FAILED=3,y.STATUS_SENT=4,y.STATUS_RECEIVED=5,y.STATUS_READ=6,y.STATUS_TO_ME=7,y.prototype={toJSON:function(){},fromJSON:function(e){}},y.prototype.constructor=y,l.exports=m,l.exports.Drafty=s,l.exports.AccessMode=b}).call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),l=l.exports})); |