!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.tinode=t():e.tinode=t()}(this,(()=>(()=>{"use strict";var e={577:e=>{const t=64,s="application/json",i=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],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)/}],r=["QQ"],a=[{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@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu}],o={AU:{html_tag:"audio",md_tag:void 0,isVoid:!1},BN:{html_tag:"button",md_tag:void 0,isVoid:!1},BR:{html_tag:"br",md_tag:"\n",isVoid:!0},CO:{html_tag:"tt",md_tag:"`",isVoid:!1},DL:{html_tag:"del",md_tag:"~",isVoid:!1},EM:{html_tag:"i",md_tag:"_",isVoid:!1},EX:{html_tag:"",md_tag:void 0,isVoid:!0},FM:{html_tag:"div",md_tag:void 0,isVoid:!1},HD:{html_tag:"",md_tag:void 0,isVoid:!1},HL:{html_tag:"span",md_tag:void 0,isVoid:!1},HT:{html_tag:"a",md_tag:void 0,isVoid:!1},IM:{html_tag:"img",md_tag:void 0,isVoid:!1},LN:{html_tag:"a",md_tag:void 0,isVoid:!1},MN:{html_tag:"a",md_tag:void 0,isVoid:!1},RW:{html_tag:"div",md_tag:void 0,isVoid:!1},QQ:{html_tag:"div",md_tag:void 0,isVoid:!1},ST:{html_tag:"b",md_tag:"*",isVoid:!1},VC:{html_tag:"div",md_tag:void 0,isVoid:!1},VD:{html_tag:"video",md_tag:void 0,isVoid:!1}};function h(e,t,s){if(!e)return null;try{const s=atob(e),i=s.length,n=new ArrayBuffer(i),r=new Uint8Array(n);for(let e=0;e"",close:e=>""},EM:{open:e=>"",close:e=>""},DL:{open:e=>"",close:e=>""},CO:{open:e=>"",close:e=>""},BR:{open:e=>"
",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'',close:e=>""},LN:{open:e=>'',close:e=>"",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},HT:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},BN:{open:e=>"",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'",props:e=>e?{src:e.ref||h(e.val,e.mime,l.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=c(e._tempPreview,e.mime),s=h(e.val,e.mime,l.logger),i=e.ref||s;return(e.name?'':"")+''},close:e=>e.name?"":"",props:e=>e?{src:c(e._tempPreview,e.mime)||e.ref||h(e.val,e.mime,l.logger),title:e.name,alt: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:e=>"
",close:e=>"
"},RW:{open:e=>"
",close:e=>"
"},QQ:{open:e=>"
",close:e=>"
",props:e=>e?{}:null},VC:{open:e=>"
",close:e=>"
",props:e=>e?{"data-duration":e.duration,"data-state":e.state}:{}},VD:{open:e=>{const t=c(e._tempPreview,e.mime),s=e.ref||h(e.preview,e.premime||"image/jpeg",l.logger);return''},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||h(e.preview,e.premime||"image/jpeg",l.logger);return{src:t,"data-src":e.ref||h(e.val,e.mime,l.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},l=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return ts.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach((e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>t.length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))})),n.sort(((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))})),a.length>0&&n.push(...a),n.forEach((e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")}));let o=f({},t,0,t.length,n);return o=b(o,(function(e){if(Array.isArray(e.children)&&1==e.children.length){const t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{const s=e.parent;(e=t).parent=s}}return e})),o}function m(e,t){return t?(e.children||(e.children=[]),e.text&&(e.children.push({text:e.text,parent:e}),delete e.text),t.parent=e,e.children.push(t),e):e}function f(e,t,s,i,n){if(!n||0==n.length)return s{_(e,t,s)})),t.type){const n=e.txt.length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){return e?(s&&(t-=s.length),b(e,(function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=e.text.length;i>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=i}return e}))):null}function y(e,t){return b(e,(e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e}))}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function x(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const i=[],n=[];for(let r in e.children){const a=e.children[r];if(a.att){if(i.length==t)continue;if(a.data.mime==s)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else n.push(a)}e.children=n.concat(i)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,s,n){if(e&&Object.entries(e).length>0){n=n||[];const r={};if(i.forEach((i=>{if(e[i]){if(s&&!n.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>t)return;if("object"==typeof e[i])return;r[i]=e[i]}})),0!=Object.entries(r).length)return r}return null}l.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},l.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],i={},r=[];t.forEach((e=>{let t,o,h=[];if(n.forEach((t=>{h=h.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let h=o.index+o[0].lastIndexOf(o[1]);a=a.slice(h+1),h+=r,r=h+1;const c=s?s.exec(a):null;if(null==c)break;let d=c.index+c[0].indexOf(c[1]);a=a.slice(d+1),d+=r,r=d+1,n.push({txt:e.slice(h+1,d),children:[],at:h,end:d,tp:i})}return n}(e,t.start,t.end,t.name))})),0==h.length)o={txt:e};else{h.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),h=p(h);const t=T(u(e,0,e.length,h),0);o={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach((i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let i=-1;return s=s.filter((e=>{const t=e.offset>i;return i=e.offset+e.len,t})),s}(o.txt),t.length>0){const e=[];for(let n in t){const r=t[n];let a=i[r.unique];a||(a=s.length,i[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}o.ent=e}r.push(o)}));const o={txt:""};if(r.length>0){o.txt=r[0].txt,o.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e(e.at+=s,e))))),t.ent&&(o.fmt=o.fmt.concat(t.ent.map((e=>(e.at+=s,e)))))}0==o.fmt.length&&delete o.fmt,s.length>0&&(o.ent=s)}return o},l.append=function(e,t){if(!e)return t;if(!t)return e;e.txt=e.txt||"";const s=e.txt.length;return"string"==typeof t?e.txt+=t:t.txt&&(e.txt+=t.txt),Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach((i=>{const n={at:(0|i.at)+s,len:0|i.len};-1==i.at&&(n.at=-1,n.len=0),i.tp?n.tp=i.tp:(n.key=e.ent.length,e.ent.push(t.ent[i.key||0])),e.fmt.push(n)}))),e},l.insertImage=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"IM",data:{mime:s.mime,ref:s.refurl,val:s.bits||s.preview,width:s.width,height:s.height,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},l.insertVideo=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"VD",data:{mime:s.mime,ref:s.refurl,val:s.bits,preref:s.preref,preview:s.preview,width:s.width,height:s.height,duration:0|s.duration,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e[0],i.data.preref=e[1],i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},l.insertAudio=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"AU",data:{mime:s.mime,val:s.bits,duration:0|s.duration,preview:s.preview,name:s.filename,size:0|s.size,ref:s.refurl}};return s.urlPromise&&(i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},l.videoCall=function(e){return{txt:" ",fmt:[{at:0,len:1,key:0}],ent:[{tp:"VC",data:{aonly:e}}]}},l.updateVideoCall=function(e,t){const s=((e||{}).fmt||[])[0];if(!s)return e;let i;if("VC"==s.tp)delete s.tp,s.key=0,i={tp:"VC"},e.ent=[i];else if(i=(e.ent||[])[0|s.key],!i||"VC"!=i.tp)return e;return i.data=i.data||{},Object.assign(i.data,t),e},l.quote=function(e,t,s){const i=l.append(l.appendLineBreak(l.mention(e,t)),s);return i.fmt.push({at:0,len:i.txt.length,tp:"QQ"}),i},l.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:(e||"").length,key:0}],ent:[{tp:"MN",data:{val:t}}]}},l.appendLink=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:t.txt.length,key:e.ent.length}),e.txt+=t.txt;const s={tp:"LN",data:{url:t.url}};return e.ent.push(s),e},l.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",l.insertImage(e,e.txt.length-1,t)},l.appendAudio=function(e,t){return(e=e||{txt:""}).txt+=" ",l.insertAudio(e,e.txt.length-1,t)},l.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 s={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(s.data._processing=!0,t.urlPromise.then((e=>{s.data.ref=e,s.data._processing=void 0}),(e=>{s.data._processing=void 0}))),e.ent.push(s),e},l.wrapInto=function(e,t,s,i){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:s||0,len:i||e.txt.length,tp:t}),e},l.wrapAsForm=function(e,t,s){return l.wrapInto(e,"FM",t,s)},l.insertButton=function(e,t,s,i,n,r,a){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length{switch(e.type){case"IM":return["val"];case"VD":return["preview"]}return null})),_({},s,[])):e},l.preview=function(e,t,s){let i=g(e);if(i=x(i,3),i=b(i,(function(e){return"MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children):"QQ"==e.type?(e.text=" ",delete e.children):"BR"==e.type&&(e.text=" ",delete e.children,delete e.type),e})),i=v(i,t,"…"),s){const e={IM:["val"],VD:["preview"]};i=y(i,(t=>e[t.type]))}else i=y(i);return _({},i,[])},l.toPlainText=function(e){return"string"==typeof e?e:e.txt},l.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},l.toMarkdown=function(e){return w(g(e),(function(e,t,s){const i=o[e];let n=s?s.join(""):"";return i&&(i.isVoid?n=i.md_tag||"":i.md_tag&&(n=i.md_tag+n+i.md_tag)),n}),0)},l.isValid=function(e){if(!e)return!1;const{txt:t,fmt:s,ent:i}=e;if(!t&&""!==t&&!s&&!i)return!1;const n=typeof t;return!("string"!=n&&"undefined"!=n&&null!==t||void 0!==s&&!Array.isArray(s)&&null!==s||void 0!==i&&!Array.isArray(i)&&null!==i)},l.hasAttachments=function(e){if(!Array.isArray(e.fmt))return!1;for(let t in e.fmt){const s=e.fmt[t];if(s&&s.at<0){const t=e.ent[0|s.key];return t&&"EX"==t.tp&&t.data}}return!1},l.attachments=function(e,t,s){if(!Array.isArray(e.fmt))return;let i=0;for(let n in e.ent){let r=e.fmt[n];if(r&&r.at<0){const n=e.ent[0|r.key];if(n&&"EX"==n.tp&&n.data&&t.call(s,n.data,i++,"EX"))break}}},l.hasEntities=function(e){return e.ent&&e.ent.length>0},l.entities=function(e,t,s){if(e.ent&&e.ent.length>0)for(let i in e.ent)if(e.ent[i]&&t.call(s,e.ent[i].data,i,e.ent[i].tp))break},l.styles=function(e,t,s){if(e.fmt&&e.fmt.length>0)for(let i in e.fmt){const n=e.fmt[i];if(n&&t.call(s,n.tp,n.at,n.len,n.key,i))break}},l.sanitizeEntities=function(e){if(e&&e.ent&&e.ent.length>0)for(let t in e.ent){const s=e.ent[t];if(s&&s.data){const i=P(s.data);i?e.ent[t].data=i:delete e.ent[t].data}}return e},l.getDownloadUrl=function(e){let t=null;return e.mime!=s&&e.val?t=h(e.val,e.mime,l.logger):"string"==typeof e.ref&&(t=e.ref),t},l.isProcessing=function(e){return!!e._processing},l.getPreviewUrl=function(e){return e.val?h(e.val,e.mime,l.logger):null},l.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},l.getEntityMimeType=function(e){return e.mime||"text/plain"},l.tagName=function(e){return o[e]&&o[e].html_tag},l.attrValue=function(e,t){if(t&&d[e])return d[e].props(t)},l.getContentType=function(){return"text/x-drafty"},e.exports=l}},t={};function s(i){var n=t[i];if(void 0!==n)return n.exports;var r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{s.r(i),s.d(i,{AccessMode:()=>e,Drafty:()=>N(),Tinode:()=>K});class e{constructor(t){t&&(this.given="number"==typeof t.given?t.given:e.decode(t.given),this.want="number"==typeof t.want?t.want:e.decode(t.want),this.mode=t.mode?"number"==typeof t.mode?t.mode:e.decode(t.mode):this.given&this.want)}static#e(e,t,s){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&s);throw new Error(`Invalid AccessMode component '${t}'`)}static decode(t){if(!t)return null;if("number"==typeof t)return t&e._BITMASK;if("N"===t||"n"===t)return e._NONE;const s={J:e._JOIN,R:e._READ,W:e._WRITE,P:e._PRES,A:e._APPROVE,S:e._SHARE,D:e._DELETE,O:e._OWNER};let i=e._NONE;for(let e=0;e=20&&s.length<=24&&["ts","touched","updated","created","when","deleted","expires"].includes(t)){const e=new Date(s);if(!isNaN(e))return e}else if("acs"===t&&"object"==typeof s)return new e(s);return s}function g(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function m(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function f(t,s,i){if("object"!=typeof s){if(void 0===s)return t;if(s===l)return;return s}if(null===s)return s;if(s instanceof Date&&!isNaN(s))return!t||!(t instanceof Date)||isNaN(t)||t{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?m(e[t])||delete e[t]:"object"==typeof e[t]&&(b(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]})),e}function w(e,t){return Array.isArray(e)?(e.sort(((e,t)=>e.low=t.hi))),e.reduce(((e,s)=>(s.low0&&(!s.hi||s.hie-t)),e.reduce(((e,t)=>{if(0==e.length)e.push({low:t});else{let s=e[e.length-1];!s.hi&&t!=s.low+1||t>s.hi?e.push({low:t}):s.hi=s.hi?Math.max(s.hi,t+1):t+1}return e}),[])}let y,M;const x="Connection failed",T=418,P="Disconnected by client";function S(e,t,s,i){let n=null;return["http","https","ws","wss"].includes(t)&&(n=`${t}://${e}`,"/"!==n.charAt(n.length-1)&&(n+="/"),n+="v"+s+"/channels",["http","https"].includes(t)&&(n+="/lp"),n+="?apikey="+i),n}class A{static#t=e=>{};#s=null;#i=0;#n=!1;#r=null;host;secure;apiKey;version;autoreconnect;initialized;constructor(e,t,s){if(this.host=e.host,this.secure=e.secure,this.apiKey=e.apiKey,this.version=t,this.autoreconnect=s,"lp"===e.transport?(this.#a(),this.initialized="lp"):"ws"===e.transport&&(this.#o(),this.initialized="ws"),!this.initialized)throw A.#t("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}static setNetworkProviders(e,t){y=e,M=t}static set logger(e){A.#t=e}connect(e,t){return Promise.reject(null)}reconnect(e){}disconnect(){}sendText(e){}isConnected(){return!1}transport(){return this.initialized}probe(){this.sendText("1")}backoffReset(){this.#h()}#c(){clearTimeout(this.#s);const e=Math.pow(2,this.#i)*(1+.3*Math.random())*2e3;this.#i=this.#i>=10?this.#i:this.#i+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),this.#s=setTimeout((t=>{if(A.#t(`Reconnecting, iter=${this.#i}, timeout=${e}`),this.#n)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((e=>{}))}}),e)}#d(){clearTimeout(this.#s),this.#s=null}#h(){this.#i=0}#a(){let e=null,t=null,s=null,i=(t,s,n)=>{let r=new M,a=!1;return r.onreadystatechange=o=>{if(4==r.readyState)if(201==r.status){let n=JSON.parse(r.responseText,p);e=t+"&sid="+n.ctrl.params.sid,r=i(e),r.send(null),this.onOpen&&this.onOpen(),s&&(a=!0,s()),this.autoreconnect&&this.#d()}else if(r.status>0&&r.status<400)this.onMessage&&this.onMessage(r.responseText),r=i(e),r.send(null);else{if(n&&!a&&(a=!0,n(r.responseText)),this.onMessage&&r.responseText&&this.onMessage(r.responseText),this.onDisconnect){const e=r.status||(this.#n?T:503),t=r.responseText||(this.#n?P:x);this.onDisconnect(new u(t,e),e)}r=null,!this.#n&&this.autoreconnect&&this.#c()}},r.open("POST",t,!0),r};this.connect=(e,s)=>{if(this.#n=!1,t){if(!s)return Promise.resolve();t.onreadystatechange=void 0,t.abort(),t=null}return e&&(this.host=e),new Promise(((e,s)=>{const n=S(this.host,this.secure?"https":"http",this.version,this.apiKey);A.#t("LP connecting to:",n),t=i(n,e,s),t.send(null)})).catch((e=>{A.#t("LP connection failed:",e)}))},this.reconnect=e=>{this.#d(),this.connect(null,e)},this.disconnect=i=>{this.#n=!0,this.#d(),s&&(s.onreadystatechange=void 0,s.abort(),s=null),t&&(t.onreadystatechange=void 0,t.abort(),t=null),this.onDisconnect&&this.onDisconnect(new u(P,T),T),e=null},this.sendText=t=>{if(s=(e=>{const t=new M;return t.onreadystatechange=e=>{if(4==t.readyState&&t.status>=400)throw new u("LP sender failed",t.status)},t.open("POST",e,!0),t})(e),!s||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(t)},this.isConnected=e=>t&&!0}#o(){this.connect=(e,t)=>{if(this.#n=!1,this.#r){if(!t&&this.#r.readyState==this.#r.OPEN)return Promise.resolve();this.#r.close(),this.#r=null}return e&&(this.host=e),new Promise(((e,t)=>{const s=S(this.host,this.secure?"wss":"ws",this.version,this.apiKey);A.#t("WS connecting to: ",s);const i=new y(s);i.onerror=e=>{t(e)},i.onopen=t=>{this.autoreconnect&&this.#d(),this.onOpen&&this.onOpen(),e()},i.onclose=e=>{if(this.#r=null,this.onDisconnect){const e=this.#n?T:503;this.onDisconnect(new u(this.#n?P:x,e),e)}!this.#n&&this.autoreconnect&&this.#c()},i.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},this.#r=i}))},this.reconnect=e=>{this.#d(),this.connect(null,e)},this.disconnect=e=>{this.#n=!0,this.#d(),this.#r&&(this.#r.close(),this.#r=null)},this.sendText=e=>{if(!this.#r||this.#r.readyState!=this.#r.OPEN)throw new Error("Websocket is not connected");this.#r.send(e)},this.isConnected=e=>this.#r&&this.#r.readyState==this.#r.OPEN}onMessage=void 0;onDisconnect=void 0;onOpen=void 0;onAutoreconnectIteration=void 0}A.NETWORK_ERROR=503,A.NETWORK_ERROR_TEXT=x,A.NETWORK_USER=T,A.NETWORK_USER_TEXT=P;const E="tinode-web";let D;class R{#l=e=>{};#u=e=>{};db=null;disabled=!1;constructor(e,t){this.#l=e||this.#l,this.#u=t||this.#u}#p(e,t,s){return this.db?new Promise(((i,n)=>{const r=this.db.transaction([e]);r.onerror=t=>{this.#u("PCache","mapObjects",e,t.target.error),n(t.target.error)},r.objectStore(e).getAll().onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}initDatabase(){return new Promise(((e,t)=>{const s=D.open(E,3);s.onsuccess=t=>{this.db=t.target.result,this.disabled=!1,e(this.db)},s.onerror=e=>{this.#u("PCache","failed to initialize",e),t(e.target.error),this.#l(e.target.error)},s.onupgradeneeded=e=>{this.db=e.target.result,this.db.onerror=e=>{this.#u("PCache","failed to create storage",e),this.#l(e.target.error)},this.db.createObjectStore("topic",{keyPath:"name"}),this.db.createObjectStore("user",{keyPath:"uid"}),this.db.createObjectStore("subscription",{keyPath:["topic","uid"]}),this.db.createObjectStore("message",{keyPath:["topic","seq"]}),this.db.createObjectStore("dellog",{keyPath:["topic","low","hi"]}).createIndex("topic_clear",["topic","clear"],{unique:!1})}}))}deleteDatabase(){return this.db&&(this.db.close(),this.db=null),new Promise(((e,t)=>{const s=D.deleteDatabase(E);s.onblocked=e=>{this.db&&this.db.close();const s=new Error("blocked");this.#u("PCache","deleteDatabase",s),t(s)},s.onsuccess=t=>{this.db=null,this.disabled=!0,e(!0)},s.onerror=e=>{this.#u("PCache","deleteDatabase",e.target.error),t(e.target.error)}}))}isReady(){return!!this.db}updTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","updTopic",e.target.error),s(e.target.error)};const n=i.objectStore("topic").get(e.name);n.onsuccess=t=>{i.objectStore("topic").put(R.#g(n.result,e)),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}markTopicAsDeleted(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","markTopicAsDeleted",e.target.error),s(e.target.error)},i.objectStore("topic").get(e).onsuccess=e=>{const t=e.target.result;t._deleted=!0,i.objectStore("topic").put(t),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic","subscription","message"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","remTopic",e.target.error),s(e.target.error)},i.objectStore("topic").delete(IDBKeyRange.only(e)),i.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),i.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapTopics(e,t){return this.#p("topic",e,t)}deserializeTopic(e,t){R.#m(e,t)}updUser(e,t){if(!(arguments.length<2||void 0===t))return this.isReady()?new Promise(((s,i)=>{const n=this.db.transaction(["user"],"readwrite");n.oncomplete=e=>{s(e.target.result)},n.onerror=e=>{this.#u("PCache","updUser",e.target.error),i(e.target.error)},n.objectStore("user").put({uid:e,public:t}),n.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","remUser",e.target.error),s(e.target.error)},i.objectStore("user").delete(IDBKeyRange.only(e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapUsers(e,t){return this.#p("user",e,t)}getUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"]);i.oncomplete=e=>{const s=e.target.result;t({user:s.uid,public:s.public})},i.onerror=e=>{this.#u("PCache","getUser",e.target.error),s(e.target.error)},i.objectStore("user").get(e)})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updSubscription(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"],"readwrite");r.oncomplete=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","updSubscription",e.target.error),n(e.target.error)},r.objectStore("subscription").get([e,t]).onsuccess=i=>{r.objectStore("subscription").put(R.#f(i.target.result,e,t,s)),r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapSubscriptions(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"]);r.onerror=e=>{this.#u("PCache","mapSubscriptions",e.target.error),n(e.target.error)},r.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}addMessage(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["message"],"readwrite");i.onsuccess=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","addMessage",e.target.error),s(e.target.error)},i.objectStore("message").add(R.#_(null,e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updMessageStatus(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["message"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","updMessageStatus",e.target.error),n(e.target.error)};const a=r.objectStore("message").get(IDBKeyRange.only([e,t]));a.onsuccess=i=>{const n=a.result||i.target.result;n&&n._status!=s?(r.objectStore("message").put(R.#_(n,{topic:e,seq:t,_status:s})),r.commit()):r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remMessages(e,t,s){return this.isReady()?new Promise(((i,n)=>{t||s||(t=0,s=Number.MAX_SAFE_INTEGER);const r=s>0?IDBKeyRange.bound([e,t],[e,s],!1,!0):IDBKeyRange.only([e,t]),a=this.db.transaction(["message"],"readwrite");a.onsuccess=e=>{i(e.target.result)},a.onerror=e=>{this.#u("PCache","remMessages",e.target.error),n(e.target.error)},a.objectStore("message").delete(r),a.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readMessages(e,t,s,i){if(!this.isReady())return this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"));const n=this.db.transaction(["message"]);let r=[];return Array.isArray(t.ranges)?new Promise(((a,o)=>{n.onerror=e=>{this.#u("PCache","readMessages",e.target.error),o(e.target.error)};let h=0;t.ranges.forEach((o=>{const c=o.hi?IDBKeyRange.bound([e,o.low],[e,o.hi],!1,!0):IDBKeyRange.only([e,o.low]);n.objectStore("message").getAll(c).onsuccess=e=>{const n=e.target.result;n&&(s&&s.call(i,n),Array.isArray(n)?r=r.concat(n):r.push(n)),h++,h==t.ranges.length&&a(r)}}))})):new Promise(((a,o)=>{const h=(t=t||{}).since>0?t.since:0,c=t.before>0?t.before:Number.MAX_SAFE_INTEGER,d=0|t.limit;n.onerror=e=>{this.#u("PCache","readMessages",e.target.error),o(e.target.error)};const l=IDBKeyRange.bound([e,h],[e,c],!1,!0);n.objectStore("message").openCursor(l,"prev").onsuccess=e=>{const t=e.target.result;t?(s&&s.call(i,t.value),r.push(t.value),d<=0||r.length{const r=this.db.transaction(["dellog"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","addDelLog",e.target.error),n(e.target.error)},s.forEach((s=>r.objectStore("dellog").add({topic:e,clear:t,low:s.low,hi:s.hi||s.low+1}))),r.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readDelLog(e,t){const s=(t=t||{}).since>0?t.since:0,i=t.before>0?t.before:Number.MAX_SAFE_INTEGER,n=0|t.limit;return this.isReady()?new Promise(((t,r)=>{const a=this.db.transaction(["dellog"]);a.onerror=e=>{this.#u("PCache","readDelLog",e.target.error),r(e.target.error)};let o=0;const h=[],c=IDBKeyRange.bound([e,0,s],[e,i,Number.MAX_SAFE_INTEGER],!1,!0);a.objectStore("dellog").openCursor(c,"prev").onsuccess=e=>{const s=e.target.result;s?(h.push({low:s.value.low,hi:s.value.hi}),o+=s.value.hi-s.value.low,n<=0||o{const i=this.db.transaction(["dellog"]);i.onerror=e=>{this.#u("PCache","maxDelId",e.target.error),s(e.target.error)},i.objectStore("dellog").index("topic_clear").openCursor(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER]),"prev").onsuccess=e=>{e.target.result&&t(e.target.result.value)}})):this.disabled?Promise.resolve(0):Promise.reject(new Error("not initialized"))}static#b=["created","updated","deleted","touched","read","recv","seq","clear","defacs","creds","public","trusted","private","_aux","_deleted"];static#m(e,t){R.#b.forEach((s=>{t.hasOwnProperty(s)&&(e[s]=t[s])})),Array.isArray(t.tags)&&(e._tags=t.tags),t.acs&&e.setAccessMode(t.acs),e.seq|=0,e.read|=0,e.unread=Math.max(0,e.seq-e.read)}static#g(e,t){const s=e||{name:t.name};return R.#b.forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),Array.isArray(t._tags)&&(s.tags=t._tags),t.acs&&(s.acs=t.getAccessMode().jsonHelper()),s}static#f(e,t,s,i){const n=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{i.hasOwnProperty(e)&&(n[e]=i[e])})),n}static#_(e,t){const s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),s}static setDatabaseProvider(e){D=e}}var k=s(577),N=s.n(k);let q,C,I,U;class O{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this.xhr=[]}uploadWithBaseUrl(e,t,s,i,n,r){let a=`/v${this._version}/file/u/`;if(e){let t=e;if(t.endsWith("/")&&(t=t.slice(0,-1)),!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid base URL '${e}'`);a=t+a}const o=this,h=new q;this.xhr.push(h),h.open("POST",a,!0),h.setRequestHeader("X-Tinode-APIKey",this._apiKey),this._authToken&&h.setRequestHeader("X-Tinode-Auth",`Token ${this._authToken.token}`);let c=null,d=null;const l=new Promise(((e,t)=>{c=e,d=t}));h.upload.onprogress=e=>{e.lengthComputable&&(i&&i(e.loaded/e.total),this.onProgress&&this.onProgress(e.loaded/e.total))},h.onload=function(){let e;try{e=JSON.parse(this.response,p)}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?(c&&c(e.ctrl.params.url),n&&n(e.ctrl)):this.status>=400?(d&&d(new u(e.ctrl.text,e.ctrl.code)),r&&r(e.ctrl)):o._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},h.onerror=function(e){d&&d(e||new Error("failed")),r&&r(null)},h.onabort=function(e){d&&d(new Error("upload cancelled by user")),r&&r(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._tinode.getNextUniqueId()),s&&e.set("topic",s),h.send(e)}catch(e){d&&d(e),r&&r(null)}return l}upload(e,t,s,i,n){const r=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(r,e,t,s,i,n)}download(e,t,s,i,n){if(!g(e))return void(n&&n(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(n&&n("Must authenticate first"));const r=this,a=new q;this.xhr.push(a),e=function(e,t,s){const i=new URL(e,window.location.origin);return i.searchParams.append("asatt","1"),i.toString().substring(window.location.origin.length)}(e),a.open("GET",e,!0),a.setRequestHeader("X-Tinode-APIKey",this._apiKey),a.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),a.responseType="blob",a.onprogress=function(e){i&&i(e.loaded)};let o=null,h=null;const c=new Promise(((e,t)=>{o=e,h=t}));a.onload=function(){if(200==this.status){const e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:s})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),o&&o()}else if(this.status>=400&&h){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,p);h(new u(e.ctrl.text,e.ctrl.code))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),h(e)}},e.readAsText(this.response)}},a.onerror=function(e){h&&h(new Error("failed")),n&&n(e)},a.onabort=function(){h&&h(null)};try{a.send()}catch(e){h&&h(e),n&&n(e)}return c}cancel(){this.xhr.forEach((e=>{e.readyState<4&&e.abort()}))}static setNetworkProvider(e){q=e}}class j{constructor(e){this.topic=e,this.what={}}#w(){return this.topic.updated}#v(){return this.topic.isP2PType()?this.#w():this.topic._lastSubsUpdate}withData(e,t,s){return this.what.data={since:e,before:t,limit:s},this}withLaterData(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)}withDataRanges(e,t){return this.what.data={ranges:w(e,this.topic._maxSeq),limit:t},this}withDataList(e){return this.withDataRanges(v(e))}withEarlierData(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)}withDesc(e){return this.what.desc={ims:e},this}withLaterDesc(){return this.withDesc(this.#w())}withSub(e,t,s){const i={ims:e,limit:t};return"me"==this.topic.getType()?i.topic=s:i.user=s,this.what.sub=i,this}withOneSub(e,t){return this.withSub(e,void 0,t)}withLaterOneSub(e){return this.withOneSub(this.topic._lastSubsUpdate,e)}withLaterSub(e){return this.withSub(this.#v(),e)}withTags(){return this.what.tags=!0,this}withCred(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),this}withAux(){return this.what.aux=!0,this}withDel(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this}withLaterDel(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)}extract(e){return this.what[e]}build(){const e=[];let t={};return["data","sub","desc","tags","cred","aux","del"].forEach((s=>{this.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(this.what[s]).length>0&&(t[s]=this.what[s]))})),e.length>0?t.what=e.join(" "):t=void 0,t}}class L{#y=void 0;#M=!1;buffer=[];constructor(e,t){this.#y=e||((e,t)=>e===t?0:e0)){o=!0;break}n=r-1}return o?{idx:r,exact:!0}:s?{idx:-1}:{idx:a<0?r+1:r}}#T(e,t){const s=this.#x(e,t,!1),i=s.exact&&this.#M?1:0;return t.splice(s.idx,i,e),t}getAt(e){return this.buffer[e]}getLast(e){return e|=0,this.buffer.length>e?this.buffer[this.buffer.length-1-e]:void 0}put(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)this.#T(e[t],this.buffer)}delAt(e){e|=0;let t=this.buffer.splice(e,1);if(t&&t.length>0)return t[0]}delRange(e,t){return this.buffer.splice(e,t-e)}length(){return this.buffer.length}reset(){this.buffer=[]}forEach(e,t,s,i){t=Math.max(0,0|t),s=Math.min(s||this.buffer.length,this.buffer.length);for(let n=t;nt?this.buffer[n-1]:void 0,ne.seq-t.seq),!0),this._attached=!1,this._lastSubsUpdate=new Date(0),this._new=!0,this._deleted=!1,this._delayedLeaveTimer=null,s&&(this.onData=s.onData,this.onMeta=s.onMeta,this.onPres=s.onPres,this.onInfo=s.onInfo,this.onMetaDesc=s.onMetaDesc,this.onMetaSub=s.onMetaSub,this.onSubsUpdated=s.onSubsUpdated,this.onTagsUpdated=s.onTagsUpdated,this.onCredsUpdated=s.onCredsUpdated,this.onAuxUpdated=s.onAuxUpdated,this.onDeleteTopic=s.onDeleteTopic,this.onAllMessagesReceived=s.onAllMessagesReceived)}static topicType(e){return{me:o,fnd:h,grp:c,new:c,nch:c,chn:c,usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]}static isMeTopicName(e){return V.topicType(e)==o}static isGroupTopicName(e){return V.topicType(e)==c}static isP2PTopicName(e){return"p2p"==V.topicType(e)}static isCommTopicName(e){return V.isP2PTopicName(e)||V.isGroupTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&(e.substring(0,3)==r||e.substring(0,3)==a)}static isChannelTopicName(e){return"string"==typeof e&&("chn"==e.substring(0,3)||e.substring(0,3)==a)}static#P(e){return e.head&&e.head.replace}isSubscribed(){return this._attached}subscribe(e,t){return clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=null,this._attached?Promise.resolve(this):this._deleted?Promise.reject(new Error("Conversation deleted")):this._tinode.subscribe(this.name||r,e,t).then((e=>{if(e.code>=300)return e;if(this._attached=!0,this._deleted=!1,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(delete this._new,this.name!=e.topic&&(this._cacheDelSelf(),this.name=e.topic),this._cachePutSelf(),this.created=e.ts,this.updated=e.ts,this.name!=o&&this.name!=h){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(e,t){return this._tinode.createMessage(this.name,e,t)}publish(e,t){return this.publishMessage(this.createMessage(e,t))}publishMessage(e){if(!this._attached)return Promise.reject(new Error("Cannot publish on inactive topic"));if(this._sending)return Promise.reject(new Error("The message is already being sent"));e._sending=!0,e._failed=!1;let t=null;return N().hasEntities(e.content)&&(t=[],N().entities(e.content,(e=>{e&&(e.ref&&t.push(e.ref),e.preref&&t.push(e.preref))})),0==t.length&&(t=null)),this._tinode.publishMessage(e,t).then((t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),this._maybeUpdateMessageVersionsCache(e),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(e,t){const s=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=s,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((t=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e))).catch((t=>{throw this._tinode.logger("WARNING: Message draft rejected",t),e._sending=!1,e._failed=!0,e._fatal=t instanceof u&&t.code>=400&&t.code<500,this.onData&&this.onData(),t}))}leave(e){return this._attached||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&this._gone(),t))):Promise.reject(new Error("Cannot leave inactive topic"))}leaveDelayed(e,t){clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=setTimeout((t=>{this._delayedLeaveTimer=null,this.leave(e)}),t)}getMeta(e){return this._tinode.getMeta(this.name,e)}getMessagesPage(e,t,s,i,n){let r=t?this.startMetaQuery().withDataRanges(t,e):n?this.startMetaQuery().withData(s,void 0,e):this.startMetaQuery().withData(void 0,i,e);return this._loadMessages(this._tinode._db,r.extract("data")).then((a=>0==(t=this.msgHasMoreMessages(s,i,n)).length?Promise.resolve({topic:this.name,code:200,params:{count:a}}):(e-=a,r=this.startMetaQuery().withDataRanges(t,e),this.getMeta(r.build()))))}getPinnedMessages(){const e=this.aux("pins");if(!Array.isArray(e))return Promise.resolve(0);const t=[];return this._tinode._db.readMessages(this.name,{ranges:v(e)}).then((e=>(e.forEach((e=>{e&&(t.push(e.seq),this._messages.put(e),this._maybeUpdateMessageVersionsCache(e))})),t.length))).then((s=>{if(s==e.length)return Promise.resolve({topic:this.name,code:200,params:{count:s}});const i=e.filter((e=>!t.includes(e)));return this.getMeta(this.startMetaQuery().withDataList(i).build())}))}setMeta(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let s=0,i=e.length;s1&&t.push(i))}t.sort().filter(((e,t,s)=>!t||e!=s[t-1]))}return 0==t.length&&t.push(l),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),e.aux&&this._processMetaAux(e.aux)),t)))}updateMode(e,t){const s=e?this.subscriber(e):null,i=s?s.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:i}})}invite(e,t){return this.setMeta({sub:{user:e,mode:t}})}archive(e){return this.private&&!this.private.arch==!e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||l}}})}pinMessage(e,t){let s=this.aux("pins");Array.isArray(s)||(s=[]);let i=!1;return t?s.includes(e)||(i=!0,5==s.length&&s.shift(),s.push(e)):s.includes(e)&&(i=!0,s=s.filter((t=>t!=e)),0==s.length&&(s=l)),i?this.setMeta({aux:{pins:s}}):Promise.resolve()}delMessages(e,t){if(!this._attached)return Promise.reject(new Error("Cannot delete messages in inactive topic"));const s=w(e,this._maxSeq);let i;return i=s.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}}),i.then((t=>(t.params.del>this._maxDel&&(this._maxDel=Math.max(t.params.del,this._maxDel),this.clear=Math.max(t.params.del,this.clear)),e.forEach((e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low),this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})})),this._tinode._db.addDelLog(this.name,t.params.del,e),this.onData&&this.onData(),t)))}delMessagesAll(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)}delMessagesList(e,t){return this.delMessages(v(e),t)}delMessagesEdits(e,t){const s=[e];return this.messageVersions(e,(e=>s.push(e.seq))),this.delMessagesList(s,t)}delTopic(e){return this._deleted?(this._gone(),Promise.resolve(null)):this._tinode.delTopic(this.name,e).then((e=>(this._deleted=!0,this._resetSub(),this._gone(),e)))}delSubscription(e){return this._attached?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(e,t){if(!this._attached)return;const s=this._users[this._tinode.getCurrentUserID()];let i=!1;s?(!s[e]||s[e]0&&this.note("read",e)}noteKeyPress(){this._attached?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")}noteRecording(e){this._attached?this._tinode.noteKeyPress(this.name,e?"kpa":"kpv"):this._tinode.logger("INFO: Cannot send notification in inactive topic")}videoCall(e,t,s){if(this._attached||["ringing","hang-up"].includes(e))return this._tinode.videoCall(this.name,t,e,s)}_updateReadRecv(e,t,s){let i,n=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":i=this.recv,this.recv=Math.max(this.recv,t),n=i!=this.recv;break;case"read":i=this.read,this.read=Math.max(this.read,t),n=i!=this.read;break;case"msg":i=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched{if(V.#P(e))return;if(e._deleted)return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})}),e,r,{}),t.forEach(((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s=0)return this._messages.getAt(t)}latestMessage(){return this._messages.getLast()}latestMsgVersion(e){const t=this._messageVersions[e];return t?t.getLast():null}maxMsgSeq(){return this._maxSeq}minMsgSeq(){return this._minSeq}maxClearId(){return this._maxDel}messageCount(){return this._messages.length()}queuedMessages(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,d,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){const i=this._tinode.getCurrentUserID();for(let n in this._users){const r=this._users[n];r.user!==i&&r[e]>=t&&s++}}return s}msgReadCount(e){return this.msgReceiptCount("read",e)}msgRecvCount(e){return this.msgReceiptCount("recv",e)}msgHasMoreMessages(e,t,s){const i=[];let n,r=0;return this._messages.forEach(((a,o)=>{const h=o||{seq:0},c=h._deleted?h.hi:h.seq+1;n=a.seq>c?{low:c,hi:a.seq}:null,n&&(s?n.hi>=e:n.low=e:n.low=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)}flushMessageRange(e,t){this._tinode._db.remMessages(this.name,e,t);for(let s=e;s=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}swapMessageId(e,t){const s=this._messages.find(e),i=this._messages.length();0<=s&&s=0){const s=this._messages.getAt(t),i=this.msgStatus(s);if(10==i||30==i||40==i)return this._tinode._db.remMessages(this.name,e),s._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1}getType(){return V.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(t){return this.acs=new e(t)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new j(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return V.isMeTopicName(this.name)}isChannelType(){return V.isChannelTopicName(this.name)}isGroupType(){return V.isGroupTopicName(this.name)}isP2PType(){return V.isP2PTopicName(this.name)}isCommType(){return V.isCommTopicName(this.name)}msgStatus(e,t){let s=0;return this._tinode.isMe(e.from)?e._sending?s=20:e._fatal||e._cancelled?s=40:e._failed?s=30:e.seq>=d?s=10:this.msgReadCount(e.seq)>0?s=70:this.msgRecvCount(e.seq)>0?s=60:e.seq>0&&(s=50):s=80,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_maybeUpdateMessageVersionsCache(e){if(!V.#P(e))return void(this._messageVersions[e.seq]&&(this._messageVersions[e.seq].filter((t=>t.from==e.from)),this._messageVersions[e.seq].isEmpty()&&delete this._messageVersions[e.seq]));const t=parseInt(e.head.replace.split(":")[1]);if(t>e.seq)return;const s=this.findMessage(t);if(s&&s.from!=e.from)return;const i=this._messageVersions[t]||new L(((e,t)=>e.seq-t.seq),!0);i.put(e),this._messageVersions[t]=i}_routeData(e){e.content&&(!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq,this.msgStatus(e,!0),clearTimeout(this._recvNotificationTimer),this._recvNotificationTimer=setTimeout((e=>{this._recvNotificationTimer=null,this.noteRecv(this._maxSeq)}),100)),(e.seq0&&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),e.aux&&this._processMetaAux(e.aux),this.onMeta&&this.onMeta(e)}_routePres(t){let s,i;switch(t.what){case"del":this._processDelMessages(t.clear,t.delseq);break;case"on":case"off":s=this._users[t.src],s?s.online="on"==t.what:this._tinode.logger("WARNING: Presence update for an unknown user",this.name,t.src);break;case"term":this._resetSub();break;case"upd":t.src&&!this._tinode.isTopicCached(t.src)&&this.getMeta(this.startMetaQuery().withLaterOneSub(t.src).build());break;case"aux":this.getMeta(this.startMetaQuery().withAux().build());break;case"acs":if(i=t.src||this._tinode.getCurrentUserID(),s=this._users[i],s)s.acs.updateAll(t.dacs),this._processMetaSub([{user:i,updated:new Date,acs:s.acs}]);else{const n=(new e).updateAll(t.dacs);n&&n.mode!=e._NONE&&(s=this._cacheGetUser(i),s?s.acs=n:(s={user:i,acs:n},this.getMeta(this.startMetaQuery().withOneSub(void 0,i).build())),s.updated=new Date,this._processMetaSub([s]))}break;default:this._tinode.logger("INFO: Ignored presence update",t.what)}this.onPres&&this.onPres(t)}_routeInfo(e){switch(e.what){case"recv":case"read":const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv{e.hi?(s+=e.hi-e.low,this.flushMessageRange(e.low,e.hi)):(s++,this.flushMessage(e.low)),this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})})),this._tinode._db.addDelLog(this.name,e,t)),s>0&&this.onData&&this.onData()}_allMessagesReceived(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)}_resetSub(){this._attached=!1}_gone(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new e(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._attached=!1;const t=this._tinode.getMeTopic();t&&t._routePres({_noForwarding:!0,what:"gone",topic:o,src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=f(s||{},t),this._cachePutUser(e,s),_(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_loadMessages(e,t){(t=t||{}).limit=t.limit||24;let s=0;return e.readMessages(this.name,t).then((e=>{e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seqe.readDelLog(this.name,t))).then((e=>e.forEach((e=>{this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})})))).then((e=>s))}_updateReceived(e,t){this.touched=new Date,this.seq=0|e,t&&!this._tinode.isMe(t)||(this.read=this.read?Math.max(this.read,this.seq):this.seq,this.recv=this.recv?Math.max(this.read,this.recv):this.read),this.unread=this.seq-(0|this.read),this._tinode._db.updTopic(this)}}class W extends V{_contacts={};constructor(e){super(h,e)}_processMetaSub(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let s in e){let i=e[s];const n=i.topic?i.topic:i.user;i=_(this._contacts,n,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))}publish(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))}setMeta(e){return Object.getPrototypeOf(W.prototype).setMeta.call(this,e).then((e=>{Object.keys(this._contacts).length>0&&(this._contacts={},this.onSubsUpdated&&this.onSubsUpdated([]))}))}contacts(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)}}class G extends V{onContactUpdate;constructor(e){super(o,e),e&&(this.onContactUpdate=e.onContactUpdate)}_processMetaDesc(e){const t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();f(this,e),this._tinode._db.updTopic(this),this._updateCachedUser(this._tinode._myUID,e),t&&this._tinode.mapTopics((e=>{e.online&&(e.online=!1,e.seen=Object.assign(e.seen||{},{when:new Date}),this._refreshContact("off",e))})),this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSub(e){let t=0;if(e.forEach((e=>{const s=e.topic;if(s==h||s==o)return;e.online=!!e.online;let i=null;if(e.deleted)i=e,this._tinode.cacheRemTopic(s),this._tinode._db.remTopic(s);else{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);const t=this._tinode.getTopic(s);t._new&&delete t._new,i=f(t,e),this._tinode._db.updTopic(i),V.isP2PTopicName(s)&&(this._cachePutUser(s,i),this._tinode._db.updUser(s,i.public)),!e._noForwarding&&t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(i)})),this.onSubsUpdated&&t>0){const s=[];e.forEach((e=>{s.push(e.topic)})),this.onSubsUpdated(s,t)}}_processMetaCreds(e,t){1==e.length&&e[0]==l&&(e=[]),t?e.forEach((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)),t>=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)}_routePres(t){if("term"==t.what)return void this._resetSub();if("upd"==t.what&&t.src==o)return void this.getMeta(this.startMetaQuery().withDesc().build());const s=this._tinode.cacheGetTopic(t.src);if(s){switch(t.what){case"on":s.online=!0;break;case"off":s.online&&(s.online=!1,s.seen=Object.assign(s.seen||{},{when:new Date}));break;case"msg":s._updateReceived(t.seq,t.act);break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(t.src).build());break;case"acs":s.acs?s.acs.updateAll(t.dacs):s.acs=(new e).updateAll(t.dacs),s.touched=new Date;break;case"ua":s.seen={when:new Date,ua:t.ua};break;case"recv":t.seq=0|t.seq,s.recv=s.recv?Math.max(s.recv,t.seq):t.seq;break;case"read":t.seq=0|t.seq,s.read=s.read?Math.max(s.read,t.seq):t.seq,s.recv=s.recv?Math.max(s.read,s.recv):s.recv,s.unread=s.seq-s.read;break;case"gone":s._deleted?this._tinode._db.remTopic(t.src):(s._deleted=!0,s._attached=!1,this._tinode._db.markTopicAsDeleted(t.src));break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",t.what)}this._refreshContact(t.what,s)}else if("acs"==t.what){const s=new e(t.dacs);if(!s||s.mode==e._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",t.src,t.dacs);if(s.mode==e._NONE)return void this._tinode.logger("WARNING: Removing non-existent subscription",t.src,t.dacs);{this.getMeta(this.startMetaQuery().withOneSub(void 0,t.src).build());const e=this._tinode.getTopic(t.src);e.topic=t.src,e.online=!1,e.acs=s,this._tinode._db.updTopic(e)}}else"tags"==t.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(t)}_refreshContact(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)}publish(){return Promise.reject(new Error("Publishing to 'me' is not supported"))}delCredential(e,t){return this._attached?this._tinode.delCredential(e,t).then((s=>{const i=this._credentials.findIndex((s=>s.meth==e&&s.val==t));return i>-1&&this._credentials.splice(i,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),s})):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))}contacts(e,t,s){this._tinode.mapTopics(((i,n)=>{!i.isCommType()||t&&!t(i)||e.call(s,i,n)}))}getContact(e){return this._tinode.cacheGetTopic(e)}getAccessMode(e){if(e){const t=this._tinode.cacheGetTopic(e);return t?t.acs:null}return this.acs}isArchived(e){const t=this._tinode.cacheGetTopic(e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}}function z(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function B(t,s){if(s instanceof Date)s=function(e){if(!m(e))return;const t=function(e,t){return"0".repeat((t=t||2)-(""+e).length)+e},s=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+(s?"."+t(s,3):"")+"Z"}(s);else if(s instanceof e)s=s.jsonHelper();else if(null==s||!1===s||Array.isArray(s)&&0==s.length||"object"==typeof s&&0==Object.keys(s).length)return;return s}function F(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":B(0,t)}"undefined"!=typeof WebSocket&&(C=WebSocket),"undefined"!=typeof XMLHttpRequest&&(I=XMLHttpRequest),"undefined"!=typeof indexedDB&&(U=indexedDB),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(s.g.btoa=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s="";for(let i,n=0,r=0,a=e;t.charAt(0|r)||(a="=",r%1);s+=a.charAt(63&n>>8-r%1*8)){if(i=t.charCodeAt(r+=3/4),i>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|i}return s}),"undefined"==typeof atob&&(s.g.atob=function(){let t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/=+$/,""),s="";if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let i,n=0,r=0,a=0;i=t.charAt(a++);~i&&(r=n%4?64*r+i:i,n++%4)?s+=String.fromCharCode(255&r>>(-2*n&6)):0)i=e.indexOf(i);return s}),"undefined"==typeof window&&(s.g.window={WebSocket:C,XMLHttpRequest:I,indexedDB:U,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),A.setNetworkProviders(C,I),O.setNetworkProvider(I),R.setDatabaseProvider(U)}();class K{_host;_secure;_appName;_apiKey;_browser="";_platform;_hwos="undefined";_humanLanguage="xx";_loggingEnabled=!1;_trimLongStrings=!1;_myUID=null;_authenticated=!1;_login=null;_authToken=null;_inPacketCount=0;_messageId=Math.floor(65535*Math.random()+65535);_serverInfo=null;_deviceToken=null;_pendingPromises={};_expirePromises=null;_connection=null;_persist=!1;_db=null;_cache={};constructor(e,t){if(this._host=e.host,this._secure=e.secure,this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._platform=e.platform||"web","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let s,i="";/reactnative/i.test(t)&&(i="ReactNative; ");let n=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){const t=["edg","chrome","safari","mobile","version"];let i,r=e.substr(n.index+n[0].length).split(" "),a=[];for(let e=0;es[1].toLowerCase().startsWith(e)))]),"Version"==s[1]&&(i=s[2]))}a.sort(((e,t)=>e[2]-t[2])),a.length>0?(a[0][0].toLowerCase().startsWith("edg")?a[0][0]="Edge":"OPR"==a[0][0]?a[0][0]="Opera":"Safari"==a[0][0]&&i&&(a[0][1]=i),s=a[0][0]+"/"+a[0][1]):s=n[1]}else/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e),s=n?"Firefox/"+n[1]:"Firefox/?"):(n=/([\w.]+)\/([.\d]+)/.exec(e),n?s=n[1]+"/"+n[2]:(n=e.split(" "),s=n[0]));if(n=s.split("/"),n.length>1){const e=n[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s=`${n[0]}/${e[0]}${t}`}return i+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),A.logger=this.logger,N().logger=this.logger,"lp"!=e.transport&&"ws"!=e.transport&&(e.transport=function(){if("object"==typeof window){if(window.WebSocket)return"ws";if(window.XMLHttpRequest)return"lp"}return null}()),this._connection=new A(e,"0",!0),this._connection.onMessage=e=>{this.#S(e)},this._connection.onOpen=e=>this.#A(),this._connection.onDisconnect=(e,t)=>this.#E(e,t),this._connection.onAutoreconnectIteration=(e,t)=>{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._persist=e.persist,this._db=new R(this.logger,this.logger),this._persist){const e=[];this._db.initDatabase().then((t=>this._db.mapTopics((t=>{let s=this.#D("topic",t.name);s||(s=t.name==o?new G:t.name==h?new W:new V(t.name),this._db.deserializeTopic(s,t),this.#R(s),s._cachePutSelf(),this._db.maxDelId(s.name).then((e=>{s._maxDel=Math.max(s._maxDel,e||0)})),delete s._new,e.push(s._loadMessages(this._db)))})))).then((e=>this._db.mapUsers((e=>{this.#k("user",e.uid,f({},e.public))})))).then((t=>Promise.all(e))).then((e=>{t&&t(),this.logger("Persistent cache initialized.")})).catch((e=>{t&&t(e),this.logger("Failed to initialize persistent cache:",e)}))}else this._db.deleteDatabase().then((e=>{t&&t()}))}logger(e){if(this._loggingEnabled){const n=new Date,r=("0"+n.getUTCHours()).slice(-2)+":"+("0"+n.getUTCMinutes()).slice(-2)+":"+("0"+n.getUTCSeconds()).slice(-2)+"."+("00"+n.getUTCMilliseconds()).slice(-3);for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}}))),t}#q(e,t,s,i){const n=this._pendingPromises[e];n&&(delete this._pendingPromises[e],t>=200&&t<400?n.resolve&&n.resolve(s):n.reject&&n.reject(new u(i,t)))}#C(e,t){let s;t&&(s=this.#N(t)),e=b(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,F):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;this.#q(t,A.NETWORK_ERROR,null,e.message)}return s}#S(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,p);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,F):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&this.#q(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout((e=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=this.#D("topic",t.ctrl.topic);e&&(e._resetSub(),t.ctrl.params&&t.ctrl.params.unsub&&e._gone())}else if(t.ctrl.code<300&&t.ctrl.params)if("data"==t.ctrl.params.what){const e=this.#D("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=this.#D("topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((e=>{if(t.meta){const e=this.#D("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&this.#q(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=this.#D("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=this.#D("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=this.#D("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"))}#A(){this._expirePromises||(this._expirePromises=setInterval((e=>{const t=new u("timeout",504),s=new Date((new Date).getTime()-5e3);for(let e in this._pendingPromises){let i=this._pendingPromises[e];i&&i.ts{e._resetSub()}));for(let t in this._pendingPromises){const s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}#U(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+n}#O(e,s){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:t,ua:this.#U(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:s,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:s,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:s,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:s,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:s,desc:{},sub:{},tags:[],aux:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:s,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:s,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}#k(e,t,s){this._cache[e+":"+t]=s}#D(e,t){return this._cache[e+":"+t]}#j(e,t){delete this._cache[e+":"+t]}#I(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}#R(e){e._tinode=this,e._cacheGetUser=e=>{const t=this.#D("user",e);if(t)return{user:e,public:f({},t)}},e._cachePutUser=(e,t)=>{this.#k("user",e,f({},t.public))},e._cacheDelUser=e=>{this.#j("user",e)},e._cachePutSelf=t=>{this.#k("topic",e.name,e)},e._cacheDelSelf=t=>{this.#j("topic",e.name)}}#L(e){return 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:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}static credential(e,t,s,i){return"object"==typeof e&&({val:t,params:s,resp:i,meth:e}=e),e&&(t||i)?[{meth:e,val:t,resp:i,params:s}]:null}static topicType(e){return V.topicType(e)}static isMeTopicName(e){return V.isMeTopicName(e)}static isGroupTopicName(e){return V.isGroupTopicName(e)}static isP2PTopicName(e){return V.isP2PTopicName(e)}static isCommTopicName(e){return V.isCommTopicName(e)}static isNewGroupTopicName(e){return V.isNewGroupTopicName(e)}static isChannelTopicName(e){return V.isChannelTopicName(e)}static getVersion(){return t}static setNetworkProviders(e,t){C=e,I=t,A.setNetworkProviders(C,I),O.setNetworkProvider(I)}static setDatabaseProvider(e){U=e,R.setDatabaseProvider(U)}static getLibrary(){return n}static isNullValue(e){return e===l}getNextUniqueId(){return 0!=this._messageId?""+this._messageId++:void 0}connect(e){return this._connection.connect(e)}reconnect(e){this._connection.reconnect(e)}disconnect(){this._connection.disconnect()}clearStorage(){return this._db.isReady()?this._db.deleteDatabase():Promise.resolve()}initStorage(){return this._db.isReady()?Promise.resolve():this._db.initDatabase()}networkProbe(){this._connection.probe()}isConnected(){return this._connection.isConnected()}isAuthenticated(){return this._authenticated}authorizeURL(e){if("string"!=typeof e)return e;if(g(e)){const t="scheme://host/",s=new URL(e,t);this._apiKey&&s.searchParams.append("apikey",this._apiKey),this._authToken&&this._authToken.token&&(s.searchParams.append("auth","token"),s.searchParams.append("secret",this._authToken.token)),e=s.toString().substring(t.length-1)}return e}account(e,t,s,i,n){const r=this.#O("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=s,r.acc.login=i,n&&(r.acc.desc.defacs=n.defacs,r.acc.desc.public=n.public,r.acc.desc.private=n.private,r.acc.desc.trusted=n.trusted,r.acc.tags=n.tags,r.acc.cred=n.cred,r.acc.tmpscheme=n.scheme,r.acc.tmpsecret=n.secret,Array.isArray(n.attachments)&&n.attachments.length>0&&(r.extra={attachments:n.attachments.filter((e=>g(e)))})),this.#C(r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then((e=>this.#L(e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",z(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",z(t+":"+s),!1,i)}hello(){const e=this.#O("hi");return this.#C(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(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(this.#C({hi:{dev:e||K.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=this.#O("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,this.#C(i,i.login.id).then((e=>this.#L(e)))}loginBasic(e,t,s){return this.login("basic",z(e+":"+t),s).then((t=>(this._login=e,t)))}loginToken(e,t){return this.login("token",e,t)}requestResetAuthSecret(e,t,s){return this.login("reset",z(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}subscribe(e,t,s){const i=this.#O("sub",e);if(e||(e=r),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;K.isNewGroupTopicName(e)?i.sub.set.desc=t:K.isP2PTopicName(e)&&t.defacs&&(i.sub.set.desc={defacs:t.defacs})}Array.isArray(s.attachments)&&s.attachments.length>0&&(i.extra={attachments:s.attachments.filter((e=>g(e)))}),s.tags&&(i.sub.set.tags=s.tags),s.aux&&(i.sub.set.aux=s.aux)}return this.#C(i,i.sub.id)}leave(e,t){const s=this.#O("leave",e);return s.leave.unsub=t,this.#C(s,s.leave.id)}createMessage(e,t,s){const i=this.#O("pub",e);let n="string"==typeof t?N().parse(t):t;return n&&!N().isPlainText(n)&&(i.pub.head={mime:N().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter((e=>g(e)))}),this.#C(s,e.id)}oobNotification(t){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(t,F):t)),t.what){case"msg":if(!t.seq||t.seq<1||!t.topic)break;if(!this.isConnected())break;const s=this.#D("topic",t.topic);if(!s)break;if(s.isSubscribed())break;s.maxMsgSeq(){this.logger("Failed to get the name of a new sender",e)})),s.subscribe(null).then((e=>s.getMeta(new j(s).withLaterData(24).withLaterDel(24).build()))).then((e=>{s.leaveDelayed(!1,1e3)})).catch((e=>{this.logger("On push data fetch failed",e)})).finally((e=>{this.getMeTopic()._refreshContact("msg",s)})));break;case"read":this.getMeTopic()._routePres({what:"read",seq:t.seq});break;case"sub":if(!this.isMe(t.xfrom))break;const i={given:t.modeGiven,want:t.modeWant},n=new e(i),r=n.mode&&n.mode!=e._NONE?{what:"acs",src:t.topic,dacs:i}:{what:"gone",src:t.topic};this.getMeTopic()._routePres(r);break;default:this.logger("Unknown push type ignored",t.what)}}getMeta(e,t){const s=this.#O("get",e);return s.get=f(s.get,t),this.#C(s,s.get.id)}setMeta(e,t){const s=this.#O("set",e),i=[];return t&&(["desc","sub","tags","cred","aux"].forEach((e=>{t.hasOwnProperty(e)&&(i.push(e),s.set[e]=t[e])})),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter((e=>g(e)))})),0==i.length?Promise.reject(new Error("Invalid {set} parameters")):this.#C(s,s.set.id)}delMessages(e,t,s){const i=this.#O("del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,this.#C(i,i.del.id)}delTopic(e,t){const s=this.#O("del",e);return s.del.what="topic",s.del.hard=t,this.#C(s,s.del.id)}delSubscription(e,t){const s=this.#O("del",e);return s.del.what="sub",s.del.user=t,this.#C(s,s.del.id)}delCredential(e,t){const s=this.#O("del",o);return s.del.what="cred",s.del.cred={meth:e,val:t},this.#C(s,s.del.id)}delCurrentUser(e){const t=this.#O("del",null);return t.del.what="user",t.del.hard=e,this.#C(t,t.del.id).then((e=>{this._myUID=null}))}note(e,t,s){if(s<=0||s>=d)throw new Error(`Invalid message id ${s}`);const i=this.#O("note",e);i.note.what=t,i.note.seq=s,this.#C(i)}noteKeyPress(e,t){const s=this.#O("note",e);s.note.what=t||"kp",this.#C(s)}videoCall(e,t,s,i){const n=this.#O("note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,this.#C(n,n.note.id)}getTopic(e){let t=this.#D("topic",e);return!t&&e&&(t=e==o?new G:e==h?new W:new V(e),this.#R(t),t._cachePutSelf()),t}cacheGetTopic(e){return this.#D("topic",e)}cacheRemTopic(e){this.#j("topic",e)}mapTopics(e,t){this.#I("topic",e,t)}isTopicCached(e){return!!this.#D("topic",e)}newGroupTopicName(e){return(e?a:r)+this.getNextUniqueId()}getMeTopic(){return this.getTopic(o)}getFndTopic(){return this.getTopic(h)}getLargeFileHelper(){return new O(this,"0")}getCurrentUserID(){return this._myUID}isMe(e){return this._myUID===e}getCurrentLogin(){return this._login}getServerInfo(){return this._serverInfo}report(e,t){return this.publish("sys",N().attachJSON(null,{action:e,target:t}))}getServerParam(e,t){return this._serverInfo&&this._serverInfo[e]||t}enableLogging(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t}setHumanLanguage(e){e&&(this._humanLanguage=e)}isTopicOnline(e){const t=this.#D("topic",e);return t&&t.online}getTopicAccessMode(e){const t=this.#D("topic",e);return t?t.acs:null}wantAkn(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}K.MESSAGE_STATUS_NONE=0,K.MESSAGE_STATUS_QUEUED=10,K.MESSAGE_STATUS_SENDING=20,K.MESSAGE_STATUS_FAILED=30,K.MESSAGE_STATUS_FATAL=40,K.MESSAGE_STATUS_SENT=50,K.MESSAGE_STATUS_RECEIVED=60,K.MESSAGE_STATUS_READ=70,K.MESSAGE_STATUS_TO_ME=80,K.DEL_CHAR=l,K.MAX_MESSAGE_SIZE="maxMessageSize",K.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",K.MAX_TAG_COUNT="maxTagCount",K.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",K.REQ_CRED_VALIDATORS="reqCred"})(),i})()));