@veltdev/sdk 4.5.0-beta.17 → 4.5.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '4.5.0-beta.17';
1
+ var SNIPPYLY_VERSION = '4.5.0-beta.18';
2
2
  (function(m,w){"use strict";function rt(){var e=K.splice(0,K.length);for(ie=0;e.length;)e.shift().call(null,e.shift())}function me(e,t){for(var n=0,r=e.length;n<r;n++)Te(e[n],t)}function ot(e){for(var t,n=0,r=e.length;n<r;n++)t=e[n],U(t,q[pe(t)])}function fe(e){return function(t){Lt(t)&&(Te(t,e),L.length&&me(t.querySelectorAll(L),e))}}function pe(e){var t=le.call(e,"is"),n=e.nodeName.toUpperCase(),r=v.call(D,t?Y+t.toUpperCase():x+n);return t&&-1<r&&!De(n,t)?-1:r}function De(e,t){return-1<L.indexOf(e+'[is="'+t+'"]')}function Ie(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,o=e.target,l=e[W]||2,a=e[He]||3;!ce||o&&o!==t||!t[y]||r==="style"||e.prevValue===e.newValue&&(e.newValue!==""||n!==l&&n!==a)||t[y](r,n===l?null:e.prevValue,n===a?null:e.newValue)}function Fe(e){var t=fe(e);return function(n){K.push(t,n.target),ie&&clearTimeout(ie),ie=setTimeout(rt,1)}}function de(e){nt&&(nt=!1,e.currentTarget.removeEventListener(Ze,de)),L.length&&me((e.target||u).querySelectorAll(L),e.detail===E?E:b),R&&at()}function lt(e,t){var n=this;Ye.call(n,e,t),Me.call(n,{target:n})}function Se(e,t,n){var r=t.apply(e,n),o=pe(r);return-1<o&&U(r,q[o]),n.pop()&&L.length&&ot(r.querySelectorAll(L)),r}function he(e,t){Tt(e,t),$?$.observe(e,gt):(ue&&(e.setAttribute=lt,e[H]=Ee(e),e[g](st,Me)),e[g](N,Ie)),e[k]&&ce&&(e.created=!0,e[k](),e.created=!1)}function at(){for(var e,t=0,n=G.length;t<n;t++)e=G[t],V.contains(e)||(n--,G.splice(t--,1),Te(e,E))}function Ve(e){throw new Error("A "+e+" type is already registered")}function Te(e,t){var n,r,o=pe(e);-1<o&&!Mt.call(e,"TEMPLATE")&&(Q(e,q[o]),o=0,t!==b||e[b]?t!==E||e[E]||(e[b]=!1,e[E]=!0,r="disconnected",o=1):(e[E]=!1,e[b]=!0,r="connected",o=1,R&&v.call(G,e)<0&&G.push(e)),o&&(n=e[t+O]||e[r+O])&&n.call(e))}function z(){}function Pe(e,t,n){var r=n&&n[_]||"",o=t.prototype,l=Ce(o),a=t.observedAttributes||ye,s={prototype:l};oe(l,k,{value:function(){if(te)te=!1;else if(!this[B]){this[B]=!0,new t(this),o[k]&&o[k].call(this);var i=j[ne.get(t)];(!Z||i.create.length>1)&&_e(this)}}}),oe(l,y,{value:function(i){-1<v.call(a,i)&&o[y]&&o[y].apply(this,arguments)}}),o[qe]&&oe(l,ut,{value:o[qe]}),o[Be]&&oe(l,ct,{value:o[Be]}),r&&(s[_]=r),e=e.toUpperCase(),j[e]={constructor:t,create:r?[r,re(e)]:[e]},ne.set(t,e),u[S](e.toLowerCase(),s),Le(e),P[e].r()}function Re(e){var t=j[e.toUpperCase()];return t&&t.constructor}function Ue(e){return typeof e=="string"?e:e&&e.is||""}function _e(e){for(var t,n=e[y],r=n?e.attributes:ye,o=r.length;o--;)t=r[o],n.call(e,t.name||t.nodeName,null,t.value||t.nodeValue)}function Le(e){return e=e.toUpperCase(),e in P||(P[e]={},P[e].p=new Xe(function(t){P[e].r=t})),P[e].p}function ke(){C&&delete m.customElements,I(m,"customElements",{configurable:!0,value:new z}),I(m,"CustomElementRegistry",{configurable:!0,value:z});for(var e=it.get(/^HTML[A-Z]*[a-z]/),t=e.length;t--;function(n){var r=m[n];if(r){m[n]=function(o){var l,a;return o||(o=this),o[B]||(te=!0,l=j[ne.get(o.constructor)],a=Z&&l.create.length===1,o=a?Reflect.construct(r,ye,l.constructor):u.createElement.apply(u,l.create),o[B]=!0,te=!1,a||_e(o)),o},m[n].prototype=r.prototype;try{r.prototype.constructor=m[n]}catch{dt=!0,I(r,B,{value:m[n]})}}}(e[t]));u.createElement=function(n,r){var o=Ue(r);return o?Ae.call(this,n,re(o)):Ae.call(this,n)},et||(Oe=!0,u[S](""))}var u=m.document,T=m.Object,it=function(e){var t,n,r,o,l=/^[A-Z]+[a-z]/,a=function(p){var f,h=[];for(f in i)p.test(f)&&h.push(f);return h},s=function(p,f){(f=f.toLowerCase())in i||(i[p]=(i[p]||[]).concat(f),i[f]=i[f.toUpperCase()]=p)},i=(T.create||T)(null),c={};for(n in e)for(o in e[n])for(r=e[n][o],i[o]=r,t=0;t<r.length;t++)i[r[t].toLowerCase()]=i[r[t].toUpperCase()]=o;return c.get=function(p){return typeof p=="string"?i[p]||(l.test(p)?[]:""):a(p)},c.set=function(p,f){return l.test(p)?s(p,f):s(f,p),c},c}({collections:{HTMLAllCollection:["all"],HTMLCollection:["forms"],HTMLFormControlsCollection:["elements"],HTMLOptionsCollection:["options"]},elements:{Element:["element"],HTMLAnchorElement:["a"],HTMLAppletElement:["applet"],HTMLAreaElement:["area"],HTMLAttachmentElement:["attachment"],HTMLAudioElement:["audio"],HTMLBRElement:["br"],HTMLBaseElement:["base"],HTMLBodyElement:["body"],HTMLButtonElement:["button"],HTMLCanvasElement:["canvas"],HTMLContentElement:["content"],HTMLDListElement:["dl"],HTMLDataElement:["data"],HTMLDataListElement:["datalist"],HTMLDetailsElement:["details"],HTMLDialogElement:["dialog"],HTMLDirectoryElement:["dir"],HTMLDivElement:["div"],HTMLDocument:["document"],HTMLElement:["element","abbr","address","article","aside","b","bdi","bdo","cite","code","command","dd","dfn","dt","em","figcaption","figure","footer","header","i","kbd","mark","nav","noscript","rp","rt","ruby","s","samp","section","small","strong","sub","summary","sup","u","var","wbr"],HTMLEmbedElement:["embed"],HTMLFieldSetElement:["fieldset"],HTMLFontElement:["font"],HTMLFormElement:["form"],HTMLFrameElement:["frame"],HTMLFrameSetElement:["frameset"],HTMLHRElement:["hr"],HTMLHeadElement:["head"],HTMLHeadingElement:["h1","h2","h3","h4","h5","h6"],HTMLHtmlElement:["html"],HTMLIFrameElement:["iframe"],HTMLImageElement:["img"],HTMLInputElement:["input"],HTMLKeygenElement:["keygen"],HTMLLIElement:["li"],HTMLLabelElement:["label"],HTMLLegendElement:["legend"],HTMLLinkElement:["link"],HTMLMapElement:["map"],HTMLMarqueeElement:["marquee"],HTMLMediaElement:["media"],HTMLMenuElement:["menu"],HTMLMenuItemElement:["menuitem"],HTMLMetaElement:["meta"],HTMLMeterElement:["meter"],HTMLModElement:["del","ins"],HTMLOListElement:["ol"],HTMLObjectElement:["object"],HTMLOptGroupElement:["optgroup"],HTMLOptionElement:["option"],HTMLOutputElement:["output"],HTMLParagraphElement:["p"],HTMLParamElement:["param"],HTMLPictureElement:["picture"],HTMLPreElement:["pre"],HTMLProgressElement:["progress"],HTMLQuoteElement:["blockquote","q","quote"],HTMLScriptElement:["script"],HTMLSelectElement:["select"],HTMLShadowElement:["shadow"],HTMLSlotElement:["slot"],HTMLSourceElement:["source"],HTMLSpanElement:["span"],HTMLStyleElement:["style"],HTMLTableCaptionElement:["caption"],HTMLTableCellElement:["td","th"],HTMLTableColElement:["col","colgroup"],HTMLTableElement:["table"],HTMLTableRowElement:["tr"],HTMLTableSectionElement:["thead","tbody","tfoot"],HTMLTemplateElement:["template"],HTMLTextAreaElement:["textarea"],HTMLTimeElement:["time"],HTMLTitleElement:["title"],HTMLTrackElement:["track"],HTMLUListElement:["ul"],HTMLUnknownElement:["unknown","vhgroupv","vkeygen"],HTMLVideoElement:["video"]},nodes:{Attr:["node"],Audio:["audio"],CDATASection:["node"],CharacterData:["node"],Comment:["#comment"],Document:["#document"],DocumentFragment:["#document-fragment"],DocumentType:["node"],HTMLDocument:["#document"],Image:["img"],Option:["option"],ProcessingInstruction:["node"],ShadowRoot:["#shadow-root"],Text:["#text"],XMLDocument:["xml"]}});typeof w!="object"&&(w={type:w||"auto"});var K,Me,X,Ee,$,ve,Q,U,A,S="registerElement",xe=1e5*m.Math.random()>>0,H="__"+S+xe,g="addEventListener",b="attached",O="Callback",E="detached",_="extends",y="attributeChanged"+O,ut=b+O,qe="connected"+O,Be="disconnected"+O,k="created"+O,ct=E+O,W="ADDITION",He="REMOVAL",N="DOMAttrModified",Ze="DOMContentLoaded",st="DOMSubtreeModified",x="<",Y="=",mt=/^[A-Z][._A-Z0-9]*-[-._A-Z0-9]*$/,ft=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],D=[],q=[],L="",V=u.documentElement,v=D.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},ge=T.prototype,be=ge.hasOwnProperty,J=ge.isPrototypeOf,I=T.defineProperty,ye=[],ee=T.getOwnPropertyDescriptor,je=T.getOwnPropertyNames,pt=T.getPrototypeOf,Ge=T.setPrototypeOf,ze=!!T.__proto__,dt=!1,B="__dreCEv1",C=m.customElements,Z=!/^force/.test(w.type)&&!!(C&&C.define&&C.get&&C.whenDefined),Ke=T.create||T,ht=m.Map||function(){var e,t=[],n=[];return{get:function(r){return n[v.call(t,r)]},set:function(r,o){e=v.call(t,r),e<0?n[t.push(r)-1]=o:n[e]=o}}},Xe=m.Promise||function(e){function t(l){for(r=!0;n.length;)n.shift()(l)}var n=[],r=!1,o={catch:function(){return o},then:function(l){return n.push(l),r&&setTimeout(t,1),o}};return e(t),o},te=!1,j=Ke(null),P=Ke(null),ne=new ht,re=function(e){return e.toLowerCase()},Ce=T.create||function e(t){return t?(e.prototype=t,new e):this},Tt=Ge||(ze?function(e,t){return e.__proto__=t,e}:je&&ee?function(){function e(t,n){for(var r,o=je(n),l=0,a=o.length;l<a;l++)r=o[l],be.call(t,r)||I(t,r,ee(n,r))}return function(t,n){do e(t,n);while((n=pt(n))&&!J.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),F=m.MutationObserver||m.WebKitMutationObserver,$e=m.HTMLAnchorElement,d=(m.HTMLElement||m.Element||m.Node).prototype,R=!J.call(d,V),oe=R?function(e,t,n){return e[t]=n.value,e}:I,Lt=R?function(e){return e.nodeType===1}:function(e){return J.call(d,e)},G=R&&[],Qe=d.attachShadow,We=d.cloneNode,Mt=d.closest||function(e){for(var t=this;t&&t.nodeName!==e;)t=t.parentNode;return t},we=d.dispatchEvent,le=d.getAttribute,Et=d.hasAttribute,vt=d.removeAttribute,Ye=d.setAttribute,ae=u.createElement,Ht=u.importNode,Ae=ae,gt=F&&{attributes:!0,characterData:!0,attributeOldValue:!0},Je=F||function(e){ue=!1,V.removeEventListener(N,Je)},ie=0,et=S in u&&!/^force-all/.test(w.type),tt=!0,Oe=!1,ue=!0,nt=!0,ce=!0;if(F&&(A=u.createElement("div"),A.innerHTML="<div><div></div></div>",new F(function(e,t){if(e[0]&&e[0].type=="childList"&&!e[0].removedNodes[0].childNodes.length){A=ee(d,"innerHTML");var n=A&&A.set;n&&I(d,"innerHTML",{set:function(r){for(;this.lastChild;)this.removeChild(this.lastChild);n.call(this,r)}})}t.disconnect(),A=null}).observe(A,{childList:!0,subtree:!0}),A.innerHTML=""),et||(Ge||ze?(Q=function(e,t){J.call(t,e)||he(e,t)},U=he):(Q=function(e,t){e[H]||(e[H]=T(!0),he(e,t))},U=Q),R?(ue=!1,function(){var e=ee(d,g),t=e.value,n=function(l){var a=new CustomEvent(N,{bubbles:!0});a.attrName=l,a.prevValue=le.call(this,l),a.newValue=null,a[He]=a.attrChange=2,vt.call(this,l),we.call(this,a)},r=function(l,a){var s=Et.call(this,l),i=s&&le.call(this,l),c=new CustomEvent(N,{bubbles:!0});Ye.call(this,l,a),c.attrName=l,c.prevValue=s?i:null,c.newValue=a,s?c.MODIFICATION=c.attrChange=1:c[W]=c.attrChange=0,we.call(this,c)},o=function(l){var a,s=l.currentTarget,i=s[H],c=l.propertyName;i.hasOwnProperty(c)&&(i=i[c],a=new CustomEvent(N,{bubbles:!0}),a.attrName=i.name,a.prevValue=i.value||null,a.newValue=i.value=s[c]||null,a.prevValue==null?a[W]=a.attrChange=0:a.MODIFICATION=a.attrChange=1,we.call(s,a))};e.value=function(l,a,s){l===N&&this[y]&&this.setAttribute!==r&&(this[H]={className:{name:"class",value:this.className}},this.setAttribute=r,this.removeAttribute=n,t.call(this,"propertychange",o)),t.call(this,l,a,s)},I(d,g,e)}()):F||(V[g](N,Je),V.setAttribute(H,1),V.removeAttribute(H),ue&&(Me=function(e){var t,n,r,o=this;if(o===e.target){t=o[H],o[H]=n=Ee(o);for(r in n){if(!(r in t))return X(0,o,r,t[r],n[r],W);if(n[r]!==t[r])return X(1,o,r,t[r],n[r],"MODIFICATION")}for(r in t)if(!(r in n))return X(2,o,r,t[r],n[r],He)}},X=function(e,t,n,r,o,l){var a={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:o};a[l]=e,Ie(a)},Ee=function(e){for(var t,n,r={},o=e.attributes,l=0,a=o.length;l<a;l++)t=o[l],(n=t.name)!=="setAttribute"&&(r[n]=t.value);return r})),u[S]=function(e,t){if(n=e.toUpperCase(),tt&&(tt=!1,F?($=function(i,c){function p(f,h){for(var M=0,se=f.length;M<se;h(f[M++]));}return new F(function(f){for(var h,M,se,Ne=0,bt=f.length;Ne<bt;Ne++)h=f[Ne],h.type==="childList"?(p(h.addedNodes,i),p(h.removedNodes,c)):(M=h.target,ce&&M[y]&&h.attributeName!=="style"&&(se=le.call(M,h.attributeName))!==h.oldValue&&M[y](h.attributeName,h.oldValue,se))})}(fe(b),fe(E)),ve=function(i){return $.observe(i,{childList:!0,subtree:!0}),i},ve(u),Qe&&(d.attachShadow=function(){return ve(Qe.apply(this,arguments))})):(K=[],u[g]("DOMNodeInserted",Fe(b)),u[g]("DOMNodeRemoved",Fe(E))),u[g](Ze,de),u[g]("readystatechange",de),u.importNode=function(i,c){switch(i.nodeType){case 1:return Se(u,Ht,[i,!!c]);case 11:for(var p=u.createDocumentFragment(),f=i.childNodes,h=f.length,M=0;M<h;M++)p.appendChild(u.importNode(f[M],!!c));return p;default:return We.call(i,!!c)}},d.cloneNode=function(i){return Se(this,We,[!!i])}),Oe)return Oe=!1;if(-2<v.call(D,Y+n)+v.call(D,x+n)&&Ve(e),!mt.test(n)||-1<v.call(ft,n))throw new Error("The type "+e+" is invalid");var n,r,o=function(){return a?u.createElement(s,n):u.createElement(s)},l=t||ge,a=be.call(l,_),s=a?t[_].toUpperCase():n;return a&&-1<v.call(D,x+s)&&Ve(s),r=D.push((a?Y:x)+n)-1,L=L.concat(L.length?",":"",a?s+'[is="'+e.toLowerCase()+'"]':s),o.prototype=q[r]=be.call(l,"prototype")?l.prototype:Ce(d),L.length&&me(u.querySelectorAll(L),b),o},u.createElement=Ae=function(e,t){var n=Ue(t),r=n?ae.call(u,e,re(n)):ae.call(u,e),o=""+e,l=v.call(D,(n?Y:x)+(n||o).toUpperCase()),a=-1<l;return n&&(r.setAttribute("is",n=n.toLowerCase()),a&&(a=De(o.toUpperCase(),n))),ce=!u.createElement.innerHTMLHelper,a&&U(r,q[l]),r}),addEventListener("beforeunload",function(){delete u.createElement,delete u.importNode,delete u[S]},!1),z.prototype={constructor:z,define:Z?function(e,t,n){if(n)Pe(e,t,n);else{var r=e.toUpperCase();j[r]={constructor:t,create:[r]},ne.set(t,r),C.define(e,t)}}:Pe,get:Z?function(e){return C.get(e)||Re(e)}:Re,whenDefined:Z?function(e){return Xe.race([C.whenDefined(e),Le(e)])}:Le},!C||/^force/.test(w.type))ke();else if(!w.noBuiltIn)try{(function(e,t,n){var r=new RegExp(`^<a\\s+is=('|")`+n+"\\1></a>$");if(t[_]="a",e.prototype=Ce($e.prototype),e.prototype.constructor=e,m.customElements.define(n,e,t),!r.test(u.createElement("a",{is:n}).outerHTML)||!r.test(new e().outerHTML))throw t})(function e(){return Reflect.construct($e,[],e)},{},"document-register-element-a"+xe)}catch{ke()}if(!w.noBuiltIn)try{if(ae.call(u,"a","a").outerHTML.indexOf("is")<0)throw{}}catch{re=function(t){return{is:t.toLowerCase()}}}})(window);
3
3
 
4
4
  var R0e=Object.create;var Tw=Object.defineProperty,N0e=Object.defineProperties,F0e=Object.getOwnPropertyDescriptor,L0e=Object.getOwnPropertyDescriptors,B0e=Object.getOwnPropertyNames,xw=Object.getOwnPropertySymbols,EG=Object.getPrototypeOf,y7=Object.prototype.hasOwnProperty,xG=Object.prototype.propertyIsEnumerable,V0e=Reflect.get;var IG=(n,o,t)=>o in n?Tw(n,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[o]=t,I=(n,o)=>{for(var t in o||={})y7.call(o,t)&&IG(n,t,o[t]);if(xw)for(var t of xw(o))xG.call(o,t)&&IG(n,t,o[t]);return n},T=(n,o)=>N0e(n,L0e(o));var S7=(n,o)=>{var t={};for(var e in n)y7.call(n,e)&&o.indexOf(e)<0&&(t[e]=n[e]);if(n!=null&&xw)for(var e of xw(n))o.indexOf(e)<0&&xG.call(n,e)&&(t[e]=n[e]);return t};var U0e=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),Dw=(n,o)=>{for(var t in o)Tw(n,t,{get:o[t],enumerable:!0})},j0e=(n,o,t,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of B0e(o))!y7.call(n,i)&&i!==t&&Tw(n,i,{get:()=>o[i],enumerable:!(e=F0e(o,i))||e.enumerable});return n};var TG=(n,o,t)=>(t=n!=null?R0e(EG(n)):{},j0e(o||!n||!n.__esModule?Tw(t,"default",{value:n,enumerable:!0}):t,n));var jd=(n,o,t)=>V0e(EG(n),t,o);var te=(n,o,t)=>new Promise((e,i)=>{var r=m=>{try{s(t.next(m))}catch(p){i(p)}},a=m=>{try{s(t.throw(m))}catch(p){i(p)}},s=m=>m.done?e(m.value):Promise.resolve(m.value).then(r,a);s((t=t.apply(n,o)).next())});var $z=U0e((hro,jz)=>{"use strict";var yt={};yt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};yt.localCName=yt.generateIdentifier();yt.splitLines=function(n){return n.trim().split(`
@@ -192,7 +192,7 @@ This typically indicates that your device does not have a healthy Internet conne
192
192
  <img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
193
193
  </a>
194
194
  `}};var Hp=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Qi}};var hM=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Qi}};var ob=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var zp=class{constructor(){this.pageInfo=new Qi}},rb=function(n){return n.Start="start",n.End="end",n}(rb||{}),Xv=function(n){return n.Avatar="avatar",n.Label="label",n}(Xv||{});var fM=class{constructor(){this.sources=[],this.playerState=new ab}},ab=class{constructor(){this.volume=1}};var sb=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Qi}};var Gp=class{constructor(){this.visibility="private"}};var vM=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new Qi,this.isReactionResolverUsed=!1}};var CM=class{};var jt=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.config$=new Ce(null),this.disableLogsConfig$=new Ce({warnings:!0,suppressAll:!1}),this.apiKey$=new Ce(""),this.baseFeatureAllowList=[],this.sf$=new Ce(!1),this.sdkType$=new Ce("core"),this.logsEnabled$=new Ce(!0);try{this.analyticsService.setConfigService(this),this.sdkType$.subscribe(r=>{this.analyticsService.updateDefaultProperties({sdkType:r})},r=>{this.loggingService.catch("Error in ConfigService sdkType$: ",r)}),this.logsEnabled$.subscribe(r=>{r?this.loggingService.enableLogs():this.loggingService.disableLogs(),dt.logsEnabled=r},r=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",r)})}catch(r){this.loggingService.catch("Error in ConfigService constructor: ",r)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(Re)),this.baseFeatureAllowList=e.featureAllowList?.slice(),this.config$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService initConfig: ",i)}}setApiKey(e){this.apiKey$.next(e)}getApiKey(){return this.apiKey$.value}getApiKey$(){return this.apiKey$.asObservable()}getConfig(){return this.config$.value}getConfig$(){return this.config$.asObservable()}disableFeatures(e){try{let i=this.config$.value;i&&(e?.length?i.featureAllowList=this.baseFeatureAllowList.filter(r=>!e.includes(r)):i.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(i)}catch(i){this.loggingService.catch("Error in ConfigService disableFeatures: ",i)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(i){this.loggingService.catch("Error in ConfigService setSF: ",i)}}getSF(){try{return this.sf$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSF: ",e),!1}}getSF$(){try{return this.sf$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),se(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService setSdkType: ",i)}}getSdkType(){try{return this.sdkType$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType: ",e),"core"}}getSdkType$(){try{return this.sdkType$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType$: ",e),se("core")}}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableLogs: ",e)}}disableLogs(e){try{e&&this.disableLogsConfig$.next({warnings:e.warnings??!0,suppressAll:e.suppressAll??!1}),e?.warnings!==!1&&this.logsEnabled$.next(!1)}catch(i){this.loggingService.catch("Error in ConfigService disableLogs: ",i)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getApiProxyDomain(){try{return this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiProxyDomain: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var rle=(()=>{let o=class o{constructor(e){this.loggingService=e,this.initLocalStorageData()}initLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: initLocalStorageData","color: green;"),this.getLocalStorageData(),this.getSessionStorageData()}getLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStorageData","color: green;");try{let e=localStorage?.getItem(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new ih;return this.setLocalStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new ih}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let i=JSON.stringify(e);localStorage?.setItem(j.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setLocalStorageData:",i)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new ih;return this.setSessionStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new ih}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let i=JSON.stringify(e);sessionStorage?.setItem(j.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setSessionStorageData:",i)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tm=(()=>{let o=class o{constructor(e,i){this.localStorageService=e,this.loggingService=i,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let e=new Do,i=this.localStorageService.getSessionStorageData();if(i.snippylyAvatar)e=i.snippylyAvatar;else{let r=this.generateUserAvatar();i.snippylyAvatar=r,this.localStorageService.setSessionStorageData(i)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new Do}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),i=this.avatarList[e];return i.color=this.generateUserColor(),i}catch(e){return this.loggingService.catch("Error in generateUserAvatar:",e),this.avatarList[0]}}generateUserColor(e){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(e)return j.AVATAR_COLOR_LIST[e%j.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*j.AVATAR_COLOR_LIST.length);return j.AVATAR_COLOR_LIST[i]}catch(i){return this.loggingService.catch("Error in generateUserColor:",i),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(e){return this.loggingService.catch("Error in generateUserImage:",e),""}}};o.\u0275fac=function(i){return new(i||o)(Q(rle),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Wp=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new Ke),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new Ke),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),se(null)}}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:hle,setPrototypeOf:ale,isFrozen:u7e,getPrototypeOf:h7e,getOwnPropertyDescriptor:f7e}=Object,{freeze:Za,seal:Ol,create:fle}=Object,{apply:pH,construct:gH}=typeof Reflect<"u"&&Reflect;Za||(Za=function(o){return o});Ol||(Ol=function(o){return o});pH||(pH=function(o,t,e){return o.apply(t,e)});gH||(gH=function(o,t){return new o(...t)});var _M=Xa(Array.prototype.forEach),v7e=Xa(Array.prototype.lastIndexOf),sle=Xa(Array.prototype.pop),cb=Xa(Array.prototype.push),C7e=Xa(Array.prototype.splice),SM=Xa(String.prototype.toLowerCase),sH=Xa(String.prototype.toString),lle=Xa(String.prototype.match),mb=Xa(String.prototype.replace),_7e=Xa(String.prototype.indexOf),y7e=Xa(String.prototype.trim),xc=Xa(Object.prototype.hasOwnProperty),Ka=Xa(RegExp.prototype.test),db=S7e(TypeError);function Xa(n){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var t=arguments.length,e=new Array(t>1?t-1:0),i=1;i<t;i++)e[i-1]=arguments[i];return pH(n,o,e)}}function S7e(n){return function(){for(var o=arguments.length,t=new Array(o),e=0;e<o;e++)t[e]=arguments[e];return gH(n,t)}}function ni(n,o){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:SM;ale&&ale(n,null);let e=o.length;for(;e--;){let i=o[e];if(typeof i=="string"){let r=t(i);r!==i&&(u7e(o)||(o[e]=r),i=r)}n[i]=!0}return n}function b7e(n){for(let o=0;o<n.length;o++)xc(n,o)||(n[o]=null);return n}function oh(n){let o=fle(null);for(let[t,e]of hle(n))xc(n,t)&&(Array.isArray(e)?o[t]=b7e(e):e&&typeof e=="object"&&e.constructor===Object?o[t]=oh(e):o[t]=e);return o}function pb(n,o){for(;n!==null;){let e=f7e(n,o);if(e){if(e.get)return Xa(e.get);if(typeof e.value=="function")return Xa(e.value)}n=h7e(n)}function t(){return null}return t}var cle=Za(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),lH=Za(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),cH=Za(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),I7e=Za(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mH=Za(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),E7e=Za(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),mle=Za(["#text"]),dle=Za(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),dH=Za(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ple=Za(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),yM=Za(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),x7e=Ol(/\{\{[\w\W]*|[\w\W]*\}\}/gm),T7e=Ol(/<%[\w\W]*|[\w\W]*%>/gm),D7e=Ol(/\$\{[\w\W]*/gm),w7e=Ol(/^data-[\-\w.\u00B7-\uFFFF]+$/),O7e=Ol(/^aria-[\-\w]+$/),vle=Ol(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),A7e=Ol(/^(?:\w+script|data):/i),P7e=Ol(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Cle=Ol(/^html$/i),M7e=Ol(/^[a-z][.\w]*(-[.\w]+)+$/i),gle=Object.freeze({__proto__:null,ARIA_ATTR:O7e,ATTR_WHITESPACE:P7e,CUSTOM_ELEMENT:M7e,DATA_ATTR:w7e,DOCTYPE_NAME:Cle,ERB_EXPR:T7e,IS_ALLOWED_URI:vle,IS_SCRIPT_OR_DATA:A7e,MUSTACHE_EXPR:x7e,TMPLIT_EXPR:D7e}),gb={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},k7e=function(){return typeof window>"u"?null:window},R7e=function(o,t){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(e=t.getAttribute(i));let r="dompurify"+(e?"#"+e:"");try{return o.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},ule=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function _le(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:k7e(),o=Yt=>_le(Yt);if(o.version="3.2.5",o.removed=[],!n||!n.document||n.document.nodeType!==gb.document||!n.Element)return o.isSupported=!1,o;let{document:t}=n,e=t,i=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:m,NodeFilter:p,NamedNodeMap:h=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:C,DOMParser:E,trustedTypes:w}=n,V=m.prototype,z=pb(V,"cloneNode"),Z=pb(V,"remove"),ae=pb(V,"nextSibling"),he=pb(V,"childNodes"),be=pb(V,"parentNode");if(typeof a=="function"){let Yt=t.createElement("template");Yt.content&&Yt.content.ownerDocument&&(t=Yt.content.ownerDocument)}let Le,qe="",{implementation:ke,createNodeIterator:_e,createDocumentFragment:Ee,getElementsByTagName:Pe}=t,{importNode:ye}=e,fe=ule();o.isSupported=typeof hle=="function"&&typeof be=="function"&&ke&&ke.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Be,ERB_EXPR:xe,TMPLIT_EXPR:wn,DATA_ATTR:$t,ARIA_ATTR:ft,IS_SCRIPT_OR_DATA:Ot,ATTR_WHITESPACE:Mt,CUSTOM_ELEMENT:ln}=gle,{IS_ALLOWED_URI:to}=gle,oi=null,Ri=ni({},[...cle,...lH,...cH,...mH,...mle]),pn=null,_i=ni({},[...dle,...dH,...ple,...yM]),Ni=Object.seal(fle(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),$m=null,fo=null,il=!0,jr=!0,ol=!1,Fl=!0,Mc=!1,fg=!0,Ll=!1,vg=!1,fh=!1,Hm=!1,vh=!1,Cg=!1,g_=!0,Ch=!1,cw="user-content-",u_=!0,zm=!1,kc={},Rc=null,Dr=ni({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),$r=null,_g=ni({},["audio","video","img","source","image","track"]),_h=null,h_=ni({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),yh="http://www.w3.org/1998/Math/MathML",Nc="http://www.w3.org/2000/svg",rl="http://www.w3.org/1999/xhtml",Gm=rl,yg=!1,f_=null,p7=ni({},[yh,Nc,rl],sH),Bd=ni({},["mi","mo","mn","ms","mtext"]),Sg=ni({},["annotation-xml"]),mw=ni({},["title","style","font","a","script"]),Bl=null,v_=["application/xhtml+xml","text/html"],C_="text/html",vo=null,Wm=null,Sh=t.createElement("form"),__=function(Ve){return Ve instanceof RegExp||Ve instanceof Function},qm=function(){let Ve=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Wm&&Wm===Ve)){if((!Ve||typeof Ve!="object")&&(Ve={}),Ve=oh(Ve),Bl=v_.indexOf(Ve.PARSER_MEDIA_TYPE)===-1?C_:Ve.PARSER_MEDIA_TYPE,vo=Bl==="application/xhtml+xml"?sH:SM,oi=xc(Ve,"ALLOWED_TAGS")?ni({},Ve.ALLOWED_TAGS,vo):Ri,pn=xc(Ve,"ALLOWED_ATTR")?ni({},Ve.ALLOWED_ATTR,vo):_i,f_=xc(Ve,"ALLOWED_NAMESPACES")?ni({},Ve.ALLOWED_NAMESPACES,sH):p7,_h=xc(Ve,"ADD_URI_SAFE_ATTR")?ni(oh(h_),Ve.ADD_URI_SAFE_ATTR,vo):h_,$r=xc(Ve,"ADD_DATA_URI_TAGS")?ni(oh(_g),Ve.ADD_DATA_URI_TAGS,vo):_g,Rc=xc(Ve,"FORBID_CONTENTS")?ni({},Ve.FORBID_CONTENTS,vo):Dr,$m=xc(Ve,"FORBID_TAGS")?ni({},Ve.FORBID_TAGS,vo):{},fo=xc(Ve,"FORBID_ATTR")?ni({},Ve.FORBID_ATTR,vo):{},kc=xc(Ve,"USE_PROFILES")?Ve.USE_PROFILES:!1,il=Ve.ALLOW_ARIA_ATTR!==!1,jr=Ve.ALLOW_DATA_ATTR!==!1,ol=Ve.ALLOW_UNKNOWN_PROTOCOLS||!1,Fl=Ve.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Mc=Ve.SAFE_FOR_TEMPLATES||!1,fg=Ve.SAFE_FOR_XML!==!1,Ll=Ve.WHOLE_DOCUMENT||!1,Hm=Ve.RETURN_DOM||!1,vh=Ve.RETURN_DOM_FRAGMENT||!1,Cg=Ve.RETURN_TRUSTED_TYPE||!1,fh=Ve.FORCE_BODY||!1,g_=Ve.SANITIZE_DOM!==!1,Ch=Ve.SANITIZE_NAMED_PROPS||!1,u_=Ve.KEEP_CONTENT!==!1,zm=Ve.IN_PLACE||!1,to=Ve.ALLOWED_URI_REGEXP||vle,Gm=Ve.NAMESPACE||rl,Bd=Ve.MATHML_TEXT_INTEGRATION_POINTS||Bd,Sg=Ve.HTML_INTEGRATION_POINTS||Sg,Ni=Ve.CUSTOM_ELEMENT_HANDLING||{},Ve.CUSTOM_ELEMENT_HANDLING&&__(Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ni.tagNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&__(Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ni.attributeNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&typeof Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ni.allowCustomizedBuiltInElements=Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Mc&&(jr=!1),vh&&(Hm=!0),kc&&(oi=ni({},mle),pn=[],kc.html===!0&&(ni(oi,cle),ni(pn,dle)),kc.svg===!0&&(ni(oi,lH),ni(pn,dH),ni(pn,yM)),kc.svgFilters===!0&&(ni(oi,cH),ni(pn,dH),ni(pn,yM)),kc.mathMl===!0&&(ni(oi,mH),ni(pn,ple),ni(pn,yM))),Ve.ADD_TAGS&&(oi===Ri&&(oi=oh(oi)),ni(oi,Ve.ADD_TAGS,vo)),Ve.ADD_ATTR&&(pn===_i&&(pn=oh(pn)),ni(pn,Ve.ADD_ATTR,vo)),Ve.ADD_URI_SAFE_ATTR&&ni(_h,Ve.ADD_URI_SAFE_ATTR,vo),Ve.FORBID_CONTENTS&&(Rc===Dr&&(Rc=oh(Rc)),ni(Rc,Ve.FORBID_CONTENTS,vo)),u_&&(oi["#text"]=!0),Ll&&ni(oi,["html","head","body"]),oi.table&&(ni(oi,["tbody"]),delete $m.tbody),Ve.TRUSTED_TYPES_POLICY){if(typeof Ve.TRUSTED_TYPES_POLICY.createHTML!="function")throw db('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ve.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw db('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Le=Ve.TRUSTED_TYPES_POLICY,qe=Le.createHTML("")}else Le===void 0&&(Le=R7e(w,i)),Le!==null&&typeof qe=="string"&&(qe=Le.createHTML(""));Za&&Za(Ve),Wm=Ve}},y_=ni({},[...lH,...cH,...I7e]),Hr=ni({},[...mH,...E7e]),dw=function(Ve){let It=be(Ve);(!It||!It.tagName)&&(It={namespaceURI:Gm,tagName:"template"});let Gt=SM(Ve.tagName),no=SM(It.tagName);return f_[Ve.namespaceURI]?Ve.namespaceURI===Nc?It.namespaceURI===rl?Gt==="svg":It.namespaceURI===yh?Gt==="svg"&&(no==="annotation-xml"||Bd[no]):!!y_[Gt]:Ve.namespaceURI===yh?It.namespaceURI===rl?Gt==="math":It.namespaceURI===Nc?Gt==="math"&&Sg[no]:!!Hr[Gt]:Ve.namespaceURI===rl?It.namespaceURI===Nc&&!Sg[no]||It.namespaceURI===yh&&!Bd[no]?!1:!Hr[Gt]&&(mw[Gt]||!y_[Gt]):!!(Bl==="application/xhtml+xml"&&f_[Ve.namespaceURI]):!1},va=function(Ve){cb(o.removed,{element:Ve});try{be(Ve).removeChild(Ve)}catch{Z(Ve)}},Fc=function(Ve,It){try{cb(o.removed,{attribute:It.getAttributeNode(Ve),from:It})}catch{cb(o.removed,{attribute:null,from:It})}if(It.removeAttribute(Ve),Ve==="is")if(Hm||vh)try{va(It)}catch{}else try{It.setAttribute(Ve,"")}catch{}},pw=function(Ve){let It=null,Gt=null;if(fh)Ve="<remove></remove>"+Ve;else{let Or=lle(Ve,/^[\r\n\t ]+/);Gt=Or&&Or[0]}Bl==="application/xhtml+xml"&&Gm===rl&&(Ve='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ve+"</body></html>");let no=Le?Le.createHTML(Ve):Ve;if(Gm===rl)try{It=new E().parseFromString(no,Bl)}catch{}if(!It||!It.documentElement){It=ke.createDocument(Gm,"template",null);try{It.documentElement.innerHTML=yg?qe:no}catch{}}let wr=It.body||It.documentElement;return Ve&&Gt&&wr.insertBefore(t.createTextNode(Gt),wr.childNodes[0]||null),Gm===rl?Pe.call(It,Ll?"html":"body")[0]:Ll?It.documentElement:wr},gw=function(Ve){return _e.call(Ve.ownerDocument||Ve,Ve,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Lc=function(Ve){return Ve instanceof C&&(typeof Ve.nodeName!="string"||typeof Ve.textContent!="string"||typeof Ve.removeChild!="function"||!(Ve.attributes instanceof h)||typeof Ve.removeAttribute!="function"||typeof Ve.setAttribute!="function"||typeof Ve.namespaceURI!="string"||typeof Ve.insertBefore!="function"||typeof Ve.hasChildNodes!="function")},uw=function(Ve){return typeof s=="function"&&Ve instanceof s};function Vl(Yt,Ve,It){_M(Yt,Gt=>{Gt.call(o,Ve,It,Wm)})}let bg=function(Ve){let It=null;if(Vl(fe.beforeSanitizeElements,Ve,null),Lc(Ve))return va(Ve),!0;let Gt=vo(Ve.nodeName);if(Vl(fe.uponSanitizeElement,Ve,{tagName:Gt,allowedTags:oi}),Ve.hasChildNodes()&&!uw(Ve.firstElementChild)&&Ka(/<[/\w!]/g,Ve.innerHTML)&&Ka(/<[/\w!]/g,Ve.textContent)||Ve.nodeType===gb.progressingInstruction||fg&&Ve.nodeType===gb.comment&&Ka(/<[/\w]/g,Ve.data))return va(Ve),!0;if(!oi[Gt]||$m[Gt]){if(!$m[Gt]&&bh(Gt)&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Gt)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Gt)))return!1;if(u_&&!Rc[Gt]){let no=be(Ve)||Ve.parentNode,wr=he(Ve)||Ve.childNodes;if(wr&&no){let Or=wr.length;for(let Ar=Or-1;Ar>=0;--Ar){let ws=z(wr[Ar],!0);ws.__removalCount=(Ve.__removalCount||0)+1,no.insertBefore(ws,ae(Ve))}}}return va(Ve),!0}return Ve instanceof m&&!dw(Ve)||(Gt==="noscript"||Gt==="noembed"||Gt==="noframes")&&Ka(/<\/no(script|embed|frames)/i,Ve.innerHTML)?(va(Ve),!0):(Mc&&Ve.nodeType===gb.text&&(It=Ve.textContent,_M([Be,xe,wn],no=>{It=mb(It,no," ")}),Ve.textContent!==It&&(cb(o.removed,{element:Ve.cloneNode()}),Ve.textContent=It)),Vl(fe.afterSanitizeElements,Ve,null),!1)},S_=function(Ve,It,Gt){if(g_&&(It==="id"||It==="name")&&(Gt in t||Gt in Sh))return!1;if(!(jr&&!fo[It]&&Ka($t,It))){if(!(il&&Ka(ft,It))){if(!pn[It]||fo[It]){if(!(bh(Ve)&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Ve)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Ve))&&(Ni.attributeNameCheck instanceof RegExp&&Ka(Ni.attributeNameCheck,It)||Ni.attributeNameCheck instanceof Function&&Ni.attributeNameCheck(It))||It==="is"&&Ni.allowCustomizedBuiltInElements&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Gt)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Gt))))return!1}else if(!_h[It]){if(!Ka(to,mb(Gt,Mt,""))){if(!((It==="src"||It==="xlink:href"||It==="href")&&Ve!=="script"&&_7e(Gt,"data:")===0&&$r[Ve])){if(!(ol&&!Ka(Ot,mb(Gt,Mt,"")))){if(Gt)return!1}}}}}}return!0},bh=function(Ve){return Ve!=="annotation-xml"&&lle(Ve,ln)},Ig=function(Ve){Vl(fe.beforeSanitizeAttributes,Ve,null);let{attributes:It}=Ve;if(!It||Lc(Ve))return;let Gt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pn,forceKeepAttr:void 0},no=It.length;for(;no--;){let wr=It[no],{name:Or,namespaceURI:Ar,value:ws}=wr,Ym=vo(Or),ir=Or==="value"?ws:y7e(ws);if(Gt.attrName=Ym,Gt.attrValue=ir,Gt.keepAttr=!0,Gt.forceKeepAttr=void 0,Vl(fe.uponSanitizeAttribute,Ve,Gt),ir=Gt.attrValue,Ch&&(Ym==="id"||Ym==="name")&&(Fc(Or,Ve),ir=cw+ir),fg&&Ka(/((--!?|])>)|<\/(style|title)/i,ir)){Fc(Or,Ve);continue}if(Gt.forceKeepAttr||(Fc(Or,Ve),!Gt.keepAttr))continue;if(!Fl&&Ka(/\/>/i,ir)){Fc(Or,Ve);continue}Mc&&_M([Be,xe,wn],Ih=>{ir=mb(ir,Ih," ")});let Vc=vo(Ve.nodeName);if(S_(Vc,Ym,ir)){if(Le&&typeof w=="object"&&typeof w.getAttributeType=="function"&&!Ar)switch(w.getAttributeType(Vc,Ym)){case"TrustedHTML":{ir=Le.createHTML(ir);break}case"TrustedScriptURL":{ir=Le.createScriptURL(ir);break}}try{Ar?Ve.setAttributeNS(Ar,Or,ir):Ve.setAttribute(Or,ir),Lc(Ve)?va(Ve):sle(o.removed)}catch{}}}Vl(fe.afterSanitizeAttributes,Ve,null)},Bc=function Yt(Ve){let It=null,Gt=gw(Ve);for(Vl(fe.beforeSanitizeShadowDOM,Ve,null);It=Gt.nextNode();)Vl(fe.uponSanitizeShadowNode,It,null),bg(It),Ig(It),It.content instanceof r&&Yt(It.content);Vl(fe.afterSanitizeShadowDOM,Ve,null)};return o.sanitize=function(Yt){let Ve=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},It=null,Gt=null,no=null,wr=null;if(yg=!Yt,yg&&(Yt="<!-->"),typeof Yt!="string"&&!uw(Yt))if(typeof Yt.toString=="function"){if(Yt=Yt.toString(),typeof Yt!="string")throw db("dirty is not a string, aborting")}else throw db("toString is not a function");if(!o.isSupported)return Yt;if(vg||qm(Ve),o.removed=[],typeof Yt=="string"&&(zm=!1),zm){if(Yt.nodeName){let ws=vo(Yt.nodeName);if(!oi[ws]||$m[ws])throw db("root node is forbidden and cannot be sanitized in-place")}}else if(Yt instanceof s)It=pw("<!---->"),Gt=It.ownerDocument.importNode(Yt,!0),Gt.nodeType===gb.element&&Gt.nodeName==="BODY"||Gt.nodeName==="HTML"?It=Gt:It.appendChild(Gt);else{if(!Hm&&!Mc&&!Ll&&Yt.indexOf("<")===-1)return Le&&Cg?Le.createHTML(Yt):Yt;if(It=pw(Yt),!It)return Hm?null:Cg?qe:""}It&&fh&&va(It.firstChild);let Or=gw(zm?Yt:It);for(;no=Or.nextNode();)bg(no),Ig(no),no.content instanceof r&&Bc(no.content);if(zm)return Yt;if(Hm){if(vh)for(wr=Ee.call(It.ownerDocument);It.firstChild;)wr.appendChild(It.firstChild);else wr=It;return(pn.shadowroot||pn.shadowrootmode)&&(wr=ye.call(e,wr,!0)),wr}let Ar=Ll?It.outerHTML:It.innerHTML;return Ll&&oi["!doctype"]&&It.ownerDocument&&It.ownerDocument.doctype&&It.ownerDocument.doctype.name&&Ka(Cle,It.ownerDocument.doctype.name)&&(Ar="<!DOCTYPE "+It.ownerDocument.doctype.name+`>
195
- `+Ar),Mc&&_M([Be,xe,wn],ws=>{Ar=mb(Ar,ws," ")}),Le&&Cg?Le.createHTML(Ar):Ar},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};qm(Yt),vg=!0},o.clearConfig=function(){Wm=null,vg=!1},o.isValidAttribute=function(Yt,Ve,It){Wm||qm({});let Gt=vo(Yt),no=vo(Ve);return S_(Gt,no,It)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&cb(fe[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let It=v7e(fe[Yt],Ve);return It===-1?void 0:C7e(fe[Yt],It,1)[0]}return sle(fe[Yt])},o.removeHooks=function(Yt){fe[Yt]=[]},o.removeAllHooks=function(){fe=ule()},o}var uH=_le();var yle={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Ne=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Ce(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Ce([]),this.mousedown=!1,this.windowMouseDown$=new Ke,this.windowPointerMove$=new Ce(null),this.windowPointerUp$=new Ce(null),this.documentSelectionChange$=new Ce(null),this.windowClick$=new Ce(null),this.windowScroll$=new Ce(null),this.windowResize$=new Ce(null),this.windowKeyupBackspace$=new Ce(null),this.windowKeyupDelete$=new Ce(null),this.windowKeyupEsc$=new Ce(null),this.windowPopState$=new Ce(null),this.documentClick$=new Ce(null),this.documentClickSubject$=new Ke,this.documentFocus$=new Ce(null),this.windowKeydownShift$=new Ce(null),this.windowKeyupShift$=new Ce(null),this.mutation$=new Ce(null),this.childListMutation$=new Ce(null),this.networkStatus$=new Ce(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Ce({}),this.selectedAnnotationsLocationMap$=new Ce({}),this.recordingInProgress$=new Ce({}),this.deleteAnnotations$=new Ce([]),this.pinHighlighterClass$=new Ce(null),this.dialogOpenedInSidebar$=new Ce(!1),this.textHighlighterClass$=new Ce(null),this.commentPinHighlighter$=new Ce(!1),this.deviceInfo$=new Ce(new ei),this.customCss$=new Ce(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.filterSnippylyNodes=a=>{try{let s=[];return a.forEach(m=>{if(!zi(m))if(m instanceof HTMLElement){if(m.className.includes("cdk-overlay-container")||m.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(m.className.includes("cdk-overlay")){let p=!1;m.childNodes.forEach(h=>{zi(h)&&(p=!0)}),p||s.push(m)}else s.push(m)}else s.push(m)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new Ce(a),this.currentMousePosition$=new Ce(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Pi(),gn(([s,m])=>{try{let p=m.filter(C=>!s.includes(C)),h=s.filter(C=>!m.includes(C));h.length&&h.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",w=>{let V=this.calculateScreenSize();this.currentScreenSize$.next(V)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?Qoe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):Joe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===j.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(m=>{let p=m;if(typeof p.getAttribute=="function"){let h=p.getAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let C=this.xpathCacheId.get(h);C!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(C))}}}),zi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!zi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(j.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(j.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(m=>{a.target?.closest(m)&&(s=!1)}),s}),r=r.filter(a=>a.target&&To(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{oo(ri(window,"offline").pipe(ce(()=>!1)),ri(window,"online").pipe(ce(()=>!0)),new Lt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new ei),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==j.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return ri(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Pg}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let C=this.getXPath(i);C&&(r=C.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,m=e.clientY-a.y,p=s*100/(a.width||1),h=m*100/(a.height||1);this.currentMousePosition.element={xpath:i,topPercentage:h,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let m=e,p=m?.touches?.length?m.touches[0]?.clientX:m.clientX,h=m?.touches?.length?m.touches[0]?.clientY:m.clientY,C=this.getBackgroundElement(p,h,i,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),w=this.getXPath(C,!0),V=C.getBoundingClientRect(),z=p-V.x,Z=h-V.y,ae=z*100/(V.width||1),he=Z*100/(V.height||1),be={xpath:E,fXpath:w,leftPercentage:ae,topPercentage:he};if(a){let Le=this.getXPath(C,!0,!0);be.cfXpath=Le}return be}else return null}catch(m){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",m),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),m=[];s.forEach(h=>{zi(h)?m=[]:To(h)&&m.push(h)}),a&&(m=m.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||m?.forEach((h,C)=>{h.tagName.toLowerCase()==="svg"&&(p=C)}),m[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{zi(s)&&To(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,j.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),m=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(j.ATTRIBUTES.DEFAULT_CURSOR,m?JSON.stringify(m):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(j.VELT_SELECTION_COLOR)&&e.style.setProperty(j.VELT_SELECTION_COLOR,i),r&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(j.VELT_SELECTION_COLOR),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(j.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let m=s.split("/"),p=!1;m.forEach((h,C)=>{h.includes("svg")&&(p=!0),p&&(m[C]="svg:"+h)}),s=m.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let m=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(m){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(w=>w?.includes("snippyly")||w?.includes("velt")||["show-pin-cursor"].includes(w))[0]===m:!1);if(h.length>1){let C=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${m} ')][${C}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${m} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(m){return m.tagName==e.tagName});return this.calculateXPath(e.parentNode,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=Pn();a.setAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new ob;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new ob}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(E=>{E.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(E=>{E.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(E=>{E?.parentNode?.insertBefore(document.createTextNode(E?.textContent),E),E.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),h;for(;h=p.nextNode();)h?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(C=>C.classList.contains("velt-annotation-draft-checked")?(C.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(C,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(C,"velt-comment-dialog-shake"),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(C=>C),m=Object.keys(this.getRecordingInProgress()||{});s=[...s,...m];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let C=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let w=p[E];w?.to?.length||s.includes(E)||C.push(w)}else p[E]?.comments?.length||s.includes(E)||C.push(p[E])}),this.deleteAnnotations$.next(C),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(C=>{if(s.includes(C)&&(h[C]=p[C]),i)switch(i){case"comment":["comment","videoPin"].includes(p[C]?.type)||(h[C]=p[C]);break;default:p[C]?.type!==i&&(h[C]=p[C]);break}}),Object.keys(h).forEach(C=>{let E=h[C]?.multiThreadAnnotationId;E&&!h[E]&&(h[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(h)&&this.selectedAnnotationsMap$.next(h),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${j.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${j.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),m=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,m[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},m[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(m).forEach(p=>{s[p]||delete m[p]}),this.selectedAnnotationsLocationMap$.next(m)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),se([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let m=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),C=a.getBoundingClientRect();r.offsetLeft+=C.left-h.left,r.offsetTop+=C.top-h.top}}else m.position==="static"?m.transformStyle!="preserve-3d"&&m.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let m=window.getComputedStyle(a);m.position==="static"?m.transformStyle!="preserve-3d"&&m.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Lt(e=>{let i=ri(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=ri(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=ri(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),m=i.pipe(ue(p=>r.pipe(Pi(),ce(([h,C])=>({startPoint:p,prevPoint:h,curPoint:C})),ro(a)))).subscribe(e);return()=>m.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(j.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),m=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${m}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let m=this.getTextXPath(r);this.isXpathWithId(m)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let m=this.getElementFromXPath(i.commonAncestorContainer);m&&(i.commonAncestorContainerFXpath=this.getXPath(m,!0),i.commonAncestorContainerCFXpath=this.getXPath(m,!0,!0))}return i.text=e.toString(),i.occurrence=ju(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(j.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let m=document.getElementById(e[s]);m&&a.push(m)}if(i?.length)for(let s=0;s<i.length;s++){let m=document.getElementsByClassName(i[s]);for(let p=0;p<m.length;p++){let h=m[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let m=document.querySelectorAll(r[s]);for(let p=0;p<m.length;p++){let h=m[p];h&&h instanceof HTMLElement&&a.push(h)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${j.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),uH.sanitize(e,yle)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return uH.sanitize(e,yle)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ei;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),se(new ei)}}getTabId(){try{let e=sessionStorage.getItem(j.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=Pn(),sessionStorage.setItem(j.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new ei}}isMobileDevice(){try{return new ei().getDeviceType()===Xo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ei().getDeviceType()===Xo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ei().getDeviceType()===Xo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(m=>{s.setAttribute(m.name,m.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new ei().getDeviceType()===Xo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(i){return new(i||o)(Q(Yo),Q(y),Q(Fs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var He=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=m,this.analyticsService=p,this.loggingService=h,this.user$=new Ce(null),this.userOptions$=new Ce(null),this.userContacts$=new Ce(null),this.userOrganization$=new Ce(null),this.providedUser=new Do,this.firebaseConfig$=new Ce(null),this.advancedQueries$=new Ce(null),this.planDetails$=new Ce(null),this.signOutPreviousUser$=new Ce(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(C=>{this.config=C}),this.forceReLoggedIn=localStorage.getItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=qn(this.afAuth).pipe(Wo(this.afAuth.currentUser),Pi(),ue(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Fe(w=>w),tt(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(w=>te(this,[w],function*({previousUser:C,currentUser:E}){if(!E&&C){let V=C?.stsTokenManager?.expirationTime,z=new Date().getTime(),Z=V-z;z>V&&(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&C?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserWithoutContacts(this.lastLoggedInUserData.user),timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),C=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",C)}),this.getUser$().pipe(qt(Vi)).subscribe(C=>{let E=ua(C);this.coreActionsService.triggerAction(Td.USER_UPDATE,E)})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new iM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||qn(this.afAuth).pipe(tt(1)).subscribe(r=>te(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield _d(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return te(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=_m(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let m=yield qn(this.afAuth).pipe(tt(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),m){let h=yield _d(m,!0).catch(w=>null);if(!h)return;let{user:C,firebaseConfig:E}=h.claims;if(m?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let w=yield _d(m,!0).catch(ae=>null);if(!w)return;let{firebaseConfig:V,user:z,advancedQueries:Z}=w.claims;this.validateOrganizationId(e),this.setFirebaseConfig(V),this.setAdvancedQueries(Z),z&&(this.providedUser.isAdmin=!!z.isAdmin),this.initializeSignedInUser(m,a),p=!1,this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s})}}if(p){this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId);let h=_r(this.functions,Sr({url:Xn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=pa(),E=(yield h({apiKey:this.apiKey,user:e,version:C,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let w={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(Td.ERROR,w)}else{let w={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(Td.ERROR,w),this.analyticsService.trackEvent(X.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId,e.userId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let w=yield _d(this.afAuth.currentUser,!0).catch(Z=>null);if(!w)return;let{user:V,advancedQueries:z}=w.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!V?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(m){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",m),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=pa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Xn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Rn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),jn(()=>se(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),qn(this.afAuth).pipe(ue(e=>e?this.user$.asObservable():se(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return SJ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Do;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers([e.userId]);a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(yn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return te(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield _r(this.functions,Sr({url:Xn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:pa(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(X.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Fe(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ue(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):se(null)))}signOutUser(e="internal"){return te(this,null,function*(){try{yield this.analyticsService.trackEvent(X.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield qn(this.afAuth).pipe(tt(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),bJ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Ji(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return ua(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(bi),Q(jt),Q(Tm),Q(Wp),Q(Ne),Q(Uo),Q(Ze),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dm=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=vc(i)),r&&(this.organizationId=Cc(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var bM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=vc(i)),r&&(this.organizationId=Cc(r)),a&&(this.folderId=a,this.veltFolderId=xl(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${j.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var IM=class{};var hn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new Ce(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(jf(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Es=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new Ce(null),this.commentAnnotationById$=new Ce({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((m,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),m({});let C={},E=[...new Set(e.commentAnnotationIds||[])],w=T(I({},e),{commentAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=yc(()=>h?.get(w)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(Z=>r?{}:(s(),Z&&Z.statusCode!==200?(this.loggingService.catch(Z?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):Z?.data)).catch(Z=>{throw s(),Z});try{C=(yield z)||{},this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let Z={};Object.entries(C).forEach(([ae,he])=>{let be=this.commentAnnotationById$.value?.[ae];be?be&&JSON.stringify(be)!==JSON.stringify(he)&&(Z[ae]=he):Z[ae]=he}),Object.keys(Z).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),Z)),m(Z)}catch(Z){r||p(Z),m(C)}}else s(),m({})}catch(z){s(),p(z)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield yc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=I({},a);delete s?.[e],this.commentAnnotationById$._value=s;let m=yield yc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:qa.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return m&&m.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(m?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wm=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new Ce(null),this.reactionAnnotationById$=new Ce({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((m,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),m({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],w=T(I({},e),{reactionAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=yc(()=>h?.get(w)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(Z=>r?{}:(s(),Z&&Z.statusCode!==200?(this.loggingService.catch(Z?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):Z?.data)).catch(Z=>{throw s(),Z});try{C=(yield z)||{},this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let Z={};Object.entries(C).forEach(([ae,he])=>{let be=this.reactionAnnotationById$.value?.[ae];be?be&&JSON.stringify(be)!==JSON.stringify(he)&&(Z[ae]=he):Z[ae]=he}),Object.keys(Z).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),Z)),m(Z)}catch(Z){r||p(Z),m(C)}}else s(),m({})}catch(z){s(),p(z)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:qa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield yc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=I({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let m=yield yc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:qa.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return m&&m.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(m?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=m,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new Ce(null),this.documentIds$=new Ce([]),this.folderConfig$=new Ce(null),this.organizationConfig$=new Ce(null),this.firestorePaths$=new Ce(null),this.location$=new Ce(null),this.excludedLocationIds$=new Ce([]),this.organizationMetadata$=new Ce(null),this.documentMetadata$=new Ce(null),this.locationMetadata$=new Ce(null),this.customerMetadata$=new Ce(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Ce({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new Ce({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ke,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(or(this.DEBOUNCE_TIME)).subscribe({next:C=>{try{this.setDocumentIdImpl(C.documentId,C.clientOrganizationId,C.auto,C.avoidAnalytics,C.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:C=>{this.loggingService.catch("Error in setDocumentId subscription:",C),this.queueSize--}}),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C)}),this.configService.getApiKey$().subscribe(C=>{if(this.apiKey=C,this.apiKey){if(!this.isCustomDocId){let E=G6(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:C})}}),this.authService.getUser$().subscribe(C=>{C?(this.analyticsService.updateDefaultProperties({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&C?.organizationId&&this.documentPaths$.value?.organizationId!==C?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),C?.organizationId&&C?.clientOrganizationId&&this.organizationConfig$.next({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(C=>{let E={documentId:C?.documentId,clientDocumentId:C?.clientDocumentId};C?.organizationId&&(E.organizationId=C.organizationId,E.clientOrganizationId=C.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(C=>{this.analyticsService.updateDefaultProperties({folderId:C?.folderId,veltFolderId:C?.veltFolderId,allDocuments:C?.allDocuments})}),this.location$.subscribe(C=>{this.analyticsService.updateDefaultProperties({clientLocation:C?.location,locationId:C?.locationId})}),this.organizationMetadata$.subscribe(C=>{this.authService.setUserOrganization(C?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(C=>{C&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Fe(C=>!!C),tt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(C){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}},C=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(C){this.loggingService.catch("Error in DocService constructor:",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=G6(location.href);this.currentUrl!==e&&(this.currentUrl=e,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowPopstate: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let e=G6(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(m=>m.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(m=>r.includes(m.id))||!go(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,m=`${yn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:m,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let m=Date.now(),p=m-this.lastSetDocumentIdCallTime,h=m-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=m,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&h>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=m;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a,options:s??void 0})}catch(m){this.loggingService.catch("Error in setDocumentId:",m)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let m=this.authService.getUser();if(!m){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?xl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${yn(e)}`,C=m?.organizationId?i?Pt(i):m?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??m?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??m?.clientOrganizationId??""}),C&&this.documentPaths$.value?.organizationId&&C!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==C){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,w=new IM;E.clientDocumentId=e,w.clientDocumentId=e,E.documentId=h,w.documentId=h,C&&(E.organizationId=C,E.clientOrganizationId=i??m?.clientOrganizationId,w.organizationId=C,w.clientOrganizationId=i??m?.clientOrganizationId);let V=`${this.apiKey}`,z=`apiKey/${this.apiKey}`;C&&(V=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,z=`${z}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),w.organization=`apiKey/${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,w.document=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,w.comment=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,w.multiThread=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,w.area=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,w.recorder=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,w.reaction=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,w.commentViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,w.notificationViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,w.documentViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,w.locationViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,C&&(E.organizationMetadata=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${V}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),w.organizationUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,w.documentUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,w.notificationDocs=`${z}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,w.notificationUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(w),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_ID_SET,{documentId:h,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return h}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(m){this.loggingService.catch("Error in setDocumentIdImpl: ",m)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,m=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)m.push(this.fetchDocuments(p));else{let C=[];for(let w=0;w<e.length;w+=20)C.push(e.slice(w,w+20));C.forEach(w=>{let V=JSON.parse(JSON.stringify(p));V.documentIds=w.map(z=>z.clientDocumentId),m.push(this.fetchDocuments(V))})}let h={};m.length>0&&Promise.all(m).then(C=>{C?.forEach(E=>{E?.forEach(w=>{w?.metadata?.documentId&&(h[w.metadata.documentId]=w.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(C=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",C)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],m={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(m));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let w=JSON.parse(JSON.stringify(m));w.documentIds=E.map(V=>V.clientDocumentId),s.push(this.fetchLocations(w))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(C=>{C?.forEach(E=>{E?.metadata?.documentId&&(p[E.metadata.documentId]=T(I({},p?.[E.metadata.documentId]??{}),{[E.location.id]:E}))})}),Object.keys(p||{}).length>0&&this.locationMetadata$.next(p)}).catch(h=>{this.loggingService.catch("Error in getLocationMetadata: ",h)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(jn(i=>se(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${yn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Pt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Qo(e),r=yn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(X.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(X.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new CM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>te(this,null,function*(){let s=new rM;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=I(I({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=I(I({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=Ei();let m=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(m){let C=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});C?.clientDocumentId?C?.folderId&&(C?.folderId!==m?.folderId||C?.veltFolderId!==m?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):C?.folderId===m?.folderId?(m?.folderId&&(s.folderId=m.folderId),m?.veltFolderId&&(s.veltFolderId=m.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${m?.folderId??""}`),p=!1):(m?.folderId&&(s.folderId=m.folderId),m?.veltFolderId&&(s.veltFolderId=m.veltFolderId))}if(h){let C={};Object.entries(s).forEach(([E,w])=>{C[E]=w}),go(C,h)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),m=new mM;m.locationId=i?.locationId,m.veltLocationId=_U(i?.location?.id??""),m.location=i?.location,m.pageInfo=Ei(),m?.pageInfo?.deviceInfo&&delete m?.pageInfo?.deviceInfo;let p=T(I({},s),{[j.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[j.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:m})}),h=T(I({},m),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(h)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:m.veltLocationId}});let C=this.locationMetadata$.value;if(C||(C={}),i?.location?.id){let E=C?.[a.documentId],w=E?.[i?.location?.id??""];C&&(E||(C[a.documentId]={}),w||(C[a.documentId][i?.location?.id??""]={}),C[a.documentId][i?.location?.id??""]=T(I({},w),{location:i?.location})),Object.keys(C||{}).length>0&&this.locationMetadata$.next(C)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?yn(JSON.stringify(Qo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let h=a[p];h.location?.id===e.id&&(r=I(I({},h.location),e),delete a[p])});let s=this.genarateLocationId(r),m={locationId:s,location:r};i=m,this.locations$.next(T(I({},a),{[s]:m})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(X.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(s){let m=JSON.parse(s),p=this.genarateLocationId(m);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),se({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${j.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let m={id:a},p=this.genarateLocationId(m);e[a]={element:r,location:{locationId:p,location:m}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(j.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let m=e?.[s.documentId];m&&(i[s.documentId]=m)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,m=this.getDocumentMetadata(s);if(!m)return;let p=m?.folderId,h=m?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),h?{veltFolderId:h}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),m=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||m||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=xl(e?.folderId);r.push(gt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(gt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=xl(e?.folderId);r.push(gt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(gt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],m=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=vc(p.documentId),C=m?.[h];C&&(m[h]=I(I({},C),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:Cc(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(m)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(C=>C.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let m=s.map(C=>vc(C)),p=[],h=this.locationMetadata$.value;h||(h={}),m.forEach(C=>{a.forEach(E=>{let w=this.location$.value;if(E?.id===w?.location?.id&&this.location$.next({locationId:w?.locationId,location:E}),E?.id){delete E?.metadata;let V=_U(E.id),z=h?.[C],Z=z?.[E.id];h&&(z||(h[C]={}),Z||(h[C][E.id]={}),h[C][E.id]=T(I({},Z),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:Cc(r),documentId:C,id:V}}))}})}),yield Promise.all(p),Object.keys(h||{}).length>0&&this.locationMetadata$.next(h)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let m=xl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:m,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[gt("metadata.veltParentFolderId","==",m)],folderId:m,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ue(e=>e?this.documentPaths$.pipe(ue(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),qt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?pi.RESTRICTED:pi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:pi.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),pi.PUBLIC}}changeDocumentAccessType(e){return te(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case pi.PUBLIC:r.features.all.restricted=!1;break;case pi.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(hn),Q(Ne),Q(jt),Q(y),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>te(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new mn,this.userDataProvider$=new Ce(null),this.userById$=new Ce({}),this.userByIdCalled$=new Ce({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(m){this.loggingService.catch("Error in UsersService getUserById:",m);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this)}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}resolveUsers(e,i=!1){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;"),this.userDataProvider$.getValue()){let r={},a=[],s={};if(e?.forEach(m=>{let p=this.getUserById(m);p?r[m]=p:this.userByIdCalled$.getValue()[m]?i&&a.push(m):(a.push(m),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[m]:!0})))}),a.length>0){let m=this.userDataProvider$.getValue();if(m){let p={};try{let h,C=new Promise((E,w)=>{h=setTimeout(()=>{w(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([m.get(a).finally(()=>{clearTimeout(h)}),C]),this.analyticsService.trackEvent(X.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:a})}catch(h){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",h,{userIds:a})}finally{a?.forEach(h=>{p[h]||(p[h]={userId:h,name:`User ${h}`})})}Object.entries(p).forEach(([h,C])=>{C&&(r[h]=p?.[h],s[h]=p?.[h])})}}return Object.keys(s).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),s)),r}else return{}}catch(r){return this.loggingService.catch("Error in UsersService resolveUsers:",r),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(gn(e=>te(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return te(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(ct),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Sle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ble=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return dt.error("Error in isTestingDb:",t),!1}}};var Yp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new Ce(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield yc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return te(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield yc(()=>a?.delete({attachmentId:e,metadata:i,event:qa.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Jv=(()=>{let o=class o{constructor(e,i,r,a,s,m,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=m,this.attachmentResolverService=p,this.notificationActionTypeMap={[Ut.NEWLY_ADDED]:qa.COMMENT_ANNOTATION_ADD,[Ut.ADDED]:qa.COMMENT_ADD,[Ut.UPDATED]:qa.COMMENT_UPDATE,[Ut.DELETED]:qa.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,m)=>m.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(vm(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let m=s?.attachments;r&&m&&a.attachments?.forEach(p=>{let h=p?.attachmentId;m?.[h]&&(p.name=m?.[h]?.name,p.url=m?.[h]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!go(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},m=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:_v(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let w;r&&(w={},E.attachments?.forEach(V=>{w[V.attachmentId]={attachmentId:V.attachmentId,name:V.name,url:V.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),w&&{attachments:w})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let C=new ko;Object.assign(C,e),C.comments=e.comments?.map(E=>{let w=new Ec;if(Object.assign(w,E),w.isCommentResolverUsed=!0,r){let V=w.attachments?.map(z=>(z.isAttachmentResolverUsed=!0,delete z?.name,delete z?.url,z));w.attachments=V}return delete w?.commentHtml,delete w?.commentText,w})||[],m=C}return{strippedData:s,originalData:m,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(m=>m.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(vm(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let m=U6(this.authService.getFirebaseConfig()?.firebaseOptions),p=_r(this.functions,Sr({url:Xn.cloudFunction?.[m]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let w=r?.targetAnnotationData?.commentId;if(w){let V=e?.comments?.find(z=>z?.commentId===w);V&&(r.targetAnnotationData=V)}}let h=qp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),C={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Xn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:pa()},E=yield Mp(C,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(m){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",m)}})}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn),Q(He),Q(Uo),Q(jt),Q(Es),Q(Yp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ile=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ele=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers(i);for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var e0=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return te(this,null,function*(){try{return yield Mp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var TM=(()=>{let o=class o{constructor(e,i,r,a,s,m){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=m}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let m of s)i.add(m)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return te(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield Mp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Jv),Q(e0),Q(y),Q(Gn),Q(He),Q(Es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ole=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ale=(()=>{let o=class o{constructor(e,i,r,a,s,m){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=m}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=U6(this.authService.getFirebaseConfig()?.firebaseOptions),m=_r(this.functions,Sr({url:Xn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=qp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",C={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:pa()},E=yield Mp(C,h);yield m({veltData:E})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!go(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:_v(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn),Q(He),Q(Uo),Q(jt),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ple=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var t0=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E,w,V,z,Z,ae,he,be,Le,qe){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=m,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=C,this.notificationUtilsService=E,this.presenceUtilsService=w,this.reactionUtilsService=V,this.recorderUtilsService=z,this.selectionUtilsService=Z,this.tagUtilsService=ae,this.usersService=he,this.docService=be,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=qe}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:m,folderId:p}=i;m||(m=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:m?`${m}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"userConfig":return i?.userId&&i?.documentId&&h?.userConfig?`${h?.userConfig}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"comment":return i?.documentId&&i?.id&&h?.comment?`${h?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"allLastNotificationTimestamp":return h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&h?.area?`${h?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&h?.area?`${h?.area}`:void 0;case"allDocuments":return h?.document?`${h?.document}`:void 0;case"allLocations":return h?.location?`${h?.location}`:void 0;case"allFolders":return h?.folder?`${h?.folder}`:void 0;case"folder":return h?.folder&&i.folderId?`${h?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&h?.reaction?`${h?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return h?.organization?`${h?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&h?.folder?`${h?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&h?.location&&i?.id?`${h?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&h?.documentUsers?`${h?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&h?.folderUsers?`${h?.folderUsers}`:void 0;case"allOrganizationGroups":return h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return h?.organizationUsers?`${h?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&h?.commentViews?`${h?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&h?.commentViews?`${h?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&h?.notificationViews?`${h?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&h?.documentViews?`${h?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&h?.documentViews?`${h?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&h?.locationViews?`${h?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&h?.locationViews?`${h?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.docNotification?`${h?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return j.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return j.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return j.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return j.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return j.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return j.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return j.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return j.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:m,organizationId:p}=i;p||(p=r?.organizationId);let h=new Dm({apiKey:a,documentId:m?`${m}`:"",organizationId:p?`${p}`:""});switch(e){case"userConfig":return i?.userId&&i?.documentId&&h?.userConfig?`${h?.userConfig}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!s&&i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&h?.globalContacts?`${h?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&h?.globalContacts?`${h?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&h?.logins?`${h?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}`:void 0;case"customerMetadata":return h?.customerMetadata?`${h?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&h?.arrow?`${h?.arrow}`:void 0;case"arrow":return i?.documentId&&h?.arrow&&i.id?`${h?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&h?.cursor?`${h?.cursor}`:void 0;case"cursor":return i?.documentId&&h?.cursor&&i.id?`${h?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&h?.flock&&i.id?`${h?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&h?.flock&&i.id?`${h?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&h?.huddle?`${h?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&h?.huddle?`${h?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&h?.huddle?`${h?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&h?.huddle?`${h?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&h?.liveState?`${h?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&h?.liveState?`${h?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&h?.liveStateSingleEditorMode?`${h?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&h?.liveState?`${h?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&h?.presence&&i?.userId?`${h?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&h?.presence?`${h?.presence}`:void 0;case"workspaceIam":return h?.workspaceIam?`${h?.workspaceIam}`:void 0;case"selection":return i?.documentId&&h?.selection&&i?.userId?`${h?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&h?.selection?`${h?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&h?.syncVideoPlayer?`${h?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&h?.tag?`${h?.tag}`:void 0;case"tag":return i?.documentId&&h?.tag&&i?.id?`${h?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&h?.userContactUs?`${h?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&h?.userFeedback?`${h?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&h?.userReportBugs?`${h?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&h?.comment?`${h?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"allDocuments":return!s&&h?.docs&&i?.documentId?`${h?.docs}/${i?.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&h?.area?`${h?.area}`:void 0;case"area":return!s&&i?.id&&h?.area?`${h?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&h?.organizationIam?`${h?.organizationIam}users/`:void 0;case"reaction":return!s&&i?.id&&h?.reaction?`${h?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"organizationMetadata":return!s&&h?.organizationMetadata?`${h?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentIam":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&h?.views?`${h?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&h?.views?`${h?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&h?.views?`${h?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&h?.views?`${h?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(m){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",m);return}}resolveAnnotations(r){return te(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(m){return te(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers(p,a):this.usersService.resolveUsers(p,a))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,m])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(m,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,m])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(m,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),se(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let m=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,m);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",m),i}}modifyAndSetData(s){return te(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let m=yield this.modifyData({feature:e,data:i});r.next({data:m,operation:a})}catch(m){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",m)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return te(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return te(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:m=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=i?.metadata?.documentId,w=i?.metadata?.veltFolderId;return Object.keys(r).filter(V=>V.includes(C)&&(!E||V.includes(E)||w&&V.includes(w))).forEach(V=>{let z=r[V]?.subject?.getValue()??{};a==="DELETE"?s&&z?.data?.[s]&&(delete z?.data?.[s],r[V]?.subject&&r[V].subject.next({data:z?.data,operation:m})):r[V]?.subject?.next({data:T(I({},z?.data),{[i?.annotationId]:i}),operation:m})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",m),e}})}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Sle),Q(ble),Q(Jv),Q(Ile),Q(Ele),Q(xM),Q(Tle),Q(y),Q(Dle),Q(TM),Q(Ole),Q(Ale),Q(e0),Q(Ple),Q(Mle),Q(Gn),Q(ct),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kle=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new Ce(null);try{Rn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Fe(([a,s])=>!!a&&!!s),tt(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(XP(qp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||XP("DocumentIdDb");if(e){let i=nb(e,"generateDocumentId");return Wv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(jt),Q(He),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=m,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=C,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(w=>{if(w){this.db=w;let V=rn(w,".info/serverTimeOffset");this.offsetListener=Eu(V,z=>{let Z=z.val();this.offset=Z})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(w=>{w&&(this.firestore=w)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Rn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([i,r])=>!!i),tt(1),gn(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,m){return te(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>te(this,[C],function*({db:p,firestore:h}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let w=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let V,z;try{w&&(V=rn(p,`${w}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(z=Wv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:V,firestoreRef:z,data:a,firestorePath:E}),m&&m({firestoreAvailable:!!h})}catch(V){this.loggingService.catch(`Error in ${e} operation: `,V),s&&s(V)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:m}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>te(this,null,function*(){if(h.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Hf(h.dbRef,JSON.parse(JSON.stringify(C)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:w,eventType:V}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:m?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:V,commentId:m?.targetAnnotationData?.commentId})),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:w,firestorePath:h.firestorePath??"",extraData:m}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:w,firestorePath:h.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield nle(this.firestore,z=>te(this,null,function*(){z.set(h.firestoreRef,C)}))):yield rH(h.firestoreRef,C)}}catch(C){this.loggingService.catch(`Error in setData for ${e}`,C)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:m}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>te(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield V5(h.dbRef,JSON.parse(JSON.stringify(C)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:w,eventType:V}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:m?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:V,commentId:m?.targetAnnotationData?.commentId})),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:w,firestorePath:h.firestorePath??"",extraData:m}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:w,firestorePath:h.firestorePath??""}))}else yield rH(h.firestoreRef,C,{merge:!0})}}catch(C){this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return te(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,m=>te(this,null,function*(){m.dbRef&&(yield L5(m.dbRef));try{if(m.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:m.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:m.firestorePath??"",eventType:"DELETE"}))}else yield Xse(m.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(m){this.loggingService.catch(`Error in deleteData for ${e}`,m)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=Pn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),Pn()||"noDocumentId"}}queryData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return te(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=nb(this.firestore,r);i?.useCollectionGroup&&(a=nH(this.firestore,r));let s=i?.firestoreQuery??[],m=oH(a,...s);if(i?.getCount){let p=yield Jse(m).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield tle(m).catch(E=>(this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let h=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:h})}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,i){return te(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=rn(this.db,r),s=i?.rtdbQuery??[],m=wB(a,...s),p=yield xB(m).catch(C=>(this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let h=p.val();return h?i?.skipObjectValues?h:Object.values(h??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let m=yield ele(Wv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!m)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=m.data();return i?.field?p?.[i.field]??{}:p??{}}catch(m){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,m),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let m=yield xB(rn(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!m)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=m.val();return i?.field?p?.[i.field]??{}:p??{}}catch(m){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,m),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Rn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([s,m])=>s?r&&!m?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ue(([s,m])=>{try{if(r&&m){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Ce({}),count:0};let C=this.handleFirestoreListener(e,i,m).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Lt(h=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{C?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s)return this.handleRealtimeDbListener(e,i,s);return se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Ng(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Lt(m=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,m,i):this.setupDocumentListener(r,a,e,m,i);return()=>{m.complete(),m.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ue(m=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:m})),ue(m=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:m,feature:e}):se(m)),ue(m=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:m,feature:e}):se(m)),qt(Vi)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,i,r,a,s){let m=`${r}-${JSON.stringify(s)}`,p=nb(e,i);if(s?.useCollectionGroup&&(p=nH(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=oH(p,...E)}let h=!0,C=[];return iH(p,E=>{try{let w=JSON.parse(JSON.stringify(this.observablesCache[m]?.subject?.getValue()?.data??{})),V=null,z=!1;E?.docChanges()?.length?E.docChanges().forEach(Z=>{["allComments","allReactions"].includes(r)&&!h&&Z.type!=="removed"&&C.push(Z.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:Z,cache:this.observablesCache[m]?.subject?.getValue()?.data??{}})||(z=!0,Object.assign(w,this.handleCollectionChange(Z,w)),Z.type==="removed"&&(V||(V={type:Z.type,ids:[]}),V.ids.push(Z.doc.id)))}):z=!0,z&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:w,subscriber:a,operation:V})),h=!1}catch(w){this.handleListenerError(w,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let m=Wv(e,i);return iH(m,p=>{try{let h=p.data()||{};s?.field&&(h=h?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:h,subscriber:a,operation:null})}catch(h){this.handleListenerError(h,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let s=rn(r,a);if(i?.useQuery&&i?.rtdbQuery){let m=i?.rtdbQuery??[];s=wB(s,...m)}return $f(s).pipe(jn(m=>(this.loggingService.catch(`RTDB listener error for ${e}:`,m),se({}))),ce(m=>(m===null&&(m={}),m&&typeof m=="object"?Object.entries(m??{}).reduce((h,[C,E])=>(h[C]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(m,i))),ue(m=>this.commonDbUtilsService.modifyData({feature:e,data:m})),ue(m=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:m}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(t0),Q(y),Q(kle),Q(hn),Q(jt),Q(ct),Q(Gn),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ci=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=m,this.commonDbService=p,this.usersService=h,this.db=Ii(),this.internalUserContacts$=new Ce([]),this.userGlobalContact$=new Ce(!1),this.userGroupContact$=new Ce(null),this.users$=new Ce([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new Ce([]),this.userFolderContacts$=new Ce([]),this.userDocumentContacts$=new Ce([]),this.userOrganizationGroups$=new Ce([]),this.onContactSelectedSubject$=new Ke,this.documentAccessType=null,this.atHereEnabled$=new Ce(!1),this.atHereLabel$=new Ce("here"),this.atHereDescription$=new Ce(null),this.contactListScopeForOrganizationUsers$=new Ce([ki.ALL]),this.customUserContacts$=new Ce(null),this.customUserContactsConfig$=new Ce({merge:!1}),this.currentOrganizationUserIAM$=new Ce(null),this.userContacts$=new Ce([]),this.userSnippylyIdContacts$=new Ce(null),this.usersByOrganizationId$=new Ce({}),this.usersByOrganizationIdAndDocumentId$=new Ce({}),this.usersByOrganizationIdAndFolderId$=new Ce({}),this.userById$=new Ce({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ue(C=>this.docService.getDocumentPaths$().pipe(gn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>te(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(C),this.setLoggedInUser(C),yield this.moveGlobalContactUserFromEmailToUserIdPath(C),this.updateUserInGlobalContactsIfAvailable(C),C?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(C?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0)}),C=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",C)}),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C)},C=>{this.loggingService.catch("Error in ContactService constructor getDb: ",C)}),this.getOrganizationGroups$().subscribe(C=>{this.authService.setOrganizationUserGroups(C)}),Rn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,w])=>{E?w?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let w=E?.userSnippylyId||_m(this.configService.getApiKey(),E.userId);w&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[w]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let m=r.contacts[s];if(m?.userId){let p=Pt(m?.userId);a[p]=m}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Do;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(m=>m?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(m=>{if(m?.userId){let p=Pt(m?.userId);r[p]=m}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>te(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Pt(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return te(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(tt(1)).subscribe(i=>te(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===pi.PUBLIC)r=!0;else if(a===pi.RESTRICTED){let s=Pt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let m=Pt(this.user?.email);i?.users?.[m]&&(r=!0)}}if(r){let s=new Gp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>te(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Rn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,m,p,h,C,E,w])=>{let V={},z=!1;E&&!E?.merge&&(z=!0);let Z=qe=>w.some(ke=>qe.includes(ke)),ae=Z([ki.ALL,ki.ORGANIZATION])?Object.keys(s?.[i]||{}):[],he=a?Z([ki.ALL,ki.FOLDER])?Object.keys(m?.[i]?.[a]||{}):[]:[],be=Z([ki.ALL,ki.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...ae,...he||[],...be].forEach(qe=>{let ke=h?.[qe];ke&&(V[qe]=ke)}),C){let{merge:qe,options:ke}=E||{},{organizationId:_e,documentId:Ee,folderId:Pe}=ke||{},ye=Pe?xl(Pe):void 0;(!_e||_e===i)&&(!Ee||Ee===r)&&(!ye||ye===a)&&(qe||(V={}),C.forEach(fe=>{fe?.userId&&(V[fe.userId]=fe)}))}return Object.values(V??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),se([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Fe(e=>!!e),ue(e=>this.docService.getDocumentPaths$().pipe(Fe(i=>!!i),gn(i=>{this.documentPaths=i}),ce(()=>e))),ue(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Pt(e?.userId)}}).pipe(ce(r=>r?.data),gn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),oo(...i).pipe(ro(this.authService.getUser$().pipe(Fe(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ue(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),gn(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],se()):se():se())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ue(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):se():se()}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return se();if(!this.commonDbService.shouldUseFirestore())return se();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return se();let s=se([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(m=>m?.data)),s.pipe(ce(m=>{if(m){typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null);let p=Object.values(m??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?se(e).pipe(ue(i=>this.docService.getDocumentPaths$().pipe(Fe(r=>!!r),gn(r=>{this.documentPaths=r}),ce(()=>i))),ue(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ue(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return se();let s=this.docService.getFolderConfig(),m=se([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)m=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(gt("metadata.apiKey","==",this.configService?.getApiKey()),gt("metadata.veltFolderId","==",s?.veltFolderId),gt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let C=0;C<a.length;C+=j.LISTENER_BATCH_SIZE)h.push(a.slice(C,C+j.LISTENER_BATCH_SIZE));m=Rn(h.map(C=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(gt("metadata.apiKey","==",this.configService?.getApiKey()),gt("metadata.documentId","in",C),gt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[gt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe(zr()))).pipe(ce(C=>ga(C)?.data))}return m.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let C=Object.values(h??{});this.setUserDocumentContacts(C)}else this.setUserDocumentContacts([])}))})):se():se())),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(m=>{s[i][m.user.userId]=m,this.userById$.next(T(I({},this.userById$.value),{[m.user.userId]:m.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(ki.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>{if(this.setUserOrganizationGroups([]),!i)return se();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case pi.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return te(this,null,function*(){try{if(this.analyticsService.trackEvent(X.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers(r);let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ue(e=>e?Rn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,m])=>{let p={};p.organizationUsers=i?.map(C=>this.convertToClientUser(C)),p.folderUsers=r?.map(C=>this.convertToClientUser(C)),p.documentUsers=a?.map(C=>this.convertToClientUser(C)),p.updatedContactList=m?.map(C=>this.convertToClientUser(C));let h=[];return s?.forEach(C=>{let E=this.convertToClientUserGroup(C,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),qt(Vi)):se(null)),jn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let m=Pt(s.userId);a[m]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(jt),Q(hn),Q(ct),Q(y),Q(Tn),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rle=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){dt.catch("Error in File utils getFileName: ",o);return}},_H=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){dt.catch("Error in File utils getFileExtension: ",o);return}},Nle=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+_H(n),{type:n.type})}catch(t){dt.catch("Error in File utils updateFile: ",t);return}},Fle=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),Lle={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Kp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=qy();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=qy(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Yv;r.name=i.name;let a=Nle(i,`${r.attachmentId}_${Rle(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=_H(i),r?.type&&(r.mimeType=Lle[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=Yy(this.storage,e.bucketPath),m=tV(s,i,{cacheControl:"public,max-age=3600"});m.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{eV(m.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(m){return te(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},h=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:qa.ATTACHMENT_ADD});h&&h.data?.url?(i.url=h.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,m)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:m}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:m})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),m(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let m=`${this.apiKey}/${e}/${i.name}`,p=Yy(this.storage,m),h=tV(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{eV(h.snapshot.ref).then(C=>{a(C)}).catch(C=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,C),s(C)})})}else{let m=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",m),s(m)}}catch(m){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,m),s(m)}})}downloadAttachment(e){try{if(e.url){let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(j.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let m=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(m),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(m=>{s(m)});else{let m=Yy(this.storage,e.bucketPath);JB(m).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=Yy(this.storage,e);JB(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(jt),Q(y),Q(Yp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=m,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new Ce(null),this.workspaceIAM$=new Ce(null),this.roles$=new Ce([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C,this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(tt(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(X.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(C=>{C?.accessType&&this.contactService.setDocumentAccessType(C.accessType)})}catch(C){this.loggingService.catch("Error in IamService constructor: ",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Fe(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Fe(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new oM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(jn(e=>se(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),qt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:j.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ue(e=>this.getRole$().pipe(ce(i=>(i===po.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ue(()=>this.documentIAM$.pipe(Fe(i=>!!i),ue(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ue(()=>this.configService.getSF$()),ue(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),ue(()=>this.documentIAM$.pipe(Fe(e=>!!e))),ue(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return po.ADMIN;if(!e&&this.user?.isAdmin)return po.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?pi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||pi.PUBLIC:null){case pi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||po.COMMENTER;break;case pi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===po.ADMIN),qt())}isUserAdmin(){try{return this.getRole()===po.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Pt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Pt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Pt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Pt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(Ci),Q(hn),Q(ct),Q(jt),Q(y),Q(Tn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E,w,V,z,Z,ae,he){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=m,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=C,this.docService=E,this.domService=w,this.iamService=V,this.loggingService=z,this.notificationUtilsService=Z,this.usersService=ae,this.functions=he,this.db=Ii(),this.notificationsDb=Ii(void 0,Xn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new Ce([]),this.rawNotificationsByIdMap$=new Ce(new Map),this.processedNotifications$=new Ce([]),this.readNotificationsOnForYouTab$=new Ce(!1),this.notificationViews$=new Ce({}),this.notificationsByIdMap$=new Ce(new Map),this.historyPanelVisible$=new Ce(!1),this.notificationsForYou$=new Ce(null),this.notificationsByDocumentIdMap$=new Ce(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new Ce(null),this.maxNotificationDays$=new Ce(15),this.tabConfig$=new Ce({people:{enable:!1}}),this.settingsConfig$=new Ce({inbox:"ALL",email:"MINE"}),this.muteAllNotifications$=new Ce(!1),this.enableSettings$=new Ce(!1),this.settingsInitialConfig$=new Ce([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Fe(be=>!!be),tt(1)).subscribe(be=>{be&&(this.db=be,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},be=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",be)}),this.authService.getUser$().subscribe(be=>{be?(this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue()),this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(be=>{if(be){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(be||{}).forEach(qe=>{let ke=Le?.[qe]?.notifications;ke?.length&&ke.forEach(_e=>{this.notificationUtilsService.mergeLocationWithNotification({notification:_e},be)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(be){this.loggingService.catch("Error in NotificationService constructor: ",be)}}setDBConfigDataToInitialConfig(e){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{i[r]=a}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=Pt(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:i}});r?.notificationsConfig&&this.setDBConfigDataToInitialConfig(r?.notificationsConfig),yield this.updateSettingsConfigToDb()}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=Pt(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Fe(i=>i===!0),ue(()=>this.docService.getDocumentPaths$().pipe(Fe(i=>!!i),ue(i=>Co(this.getInitialConfigFromDB(i)).pipe(ue(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?.documentId,userId:e}}).pipe(ce(r=>{r?.data?.notificationsConfig&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next({})}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Pi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),m=a?.map(h=>({documentId:h,timestamp:i?.find(C=>C.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let C=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:C}}).filter(h=>{let C=e?.find(E=>E.documentId===h.documentId)?.timestamp;return C&&h.timestamp&&C!==h.timestamp});m?.length&&this.fetchNotificationsForDocumentIds(m),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(h=>{this.removeNotificationsForDocumentId(h)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),m=r?.organizationId||i?.organizationId;return s&&m&&(a=new Dm({apiKey:s,organizationId:m})),{user:i,documentPaths:a}}))),ue(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,m=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-m);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Ui(gt("timestamp",">=",p)),Ya("timestamp","desc"),qv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let C=[];return Object.keys(h||{}).forEach(E=>{let w=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],V=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(V&&V.id&&V?.timestamp===w){let z=V.id,Z=h[E]?.metadata?.documentId,ae=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),he=ae?.[Z]??{documentMetadata:null,notifications:[]},be=he.notifications??[],Le=be?.findIndex(qe=>qe.id===z);Le!==-1&&(be.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},ae),{[Z]:T(I({},he),{notifications:be})})))}C.push({documentId:E,timestamp:w})}),C}),jn(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),se([]))))}return se(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),se([])}}fetchNotificationsForDocumentIds(e,i=15){return te(this,null,function*(){try{if(e?.length){let r=_r(this.functions,Sr({url:Xn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),m={};e.forEach(V=>{if(V?.documentId){let z=this.getAllowedDocumentMetadataByDocumentId(V.documentId);z&&(m[V.documentId]=z)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:m},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),w=yield joe(C,E);if(w&&typeof w=="object"){let V=this.usersService.userDataProviderAvailable(),z=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Z=[],ae=[];Object.keys(w).forEach((he,be)=>{let Le=w[he].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[he]||!go(ke?.[he],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[he]:Le}))}let qe=w[he].notifications||[];qe.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(he,Le,qe),V&&Z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:qe,shouldAwait:!0,forceResolve:!0})),z&&ae.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:qe,shouldCommentAnnotationsResolverAwait:!0}))}),V&&Promise.all(Z).then(()=>{Object.keys(w).forEach(he=>{let be=w?.[he]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:w?.[he]?.notifications||[]});Le.forEach(qe=>{qe.notification=this.getClientNotificationObject(qe)}),this.setNotificationForDocumentIdInCache(he,be,Le)})}),z&&Promise.all(ae).then(()=>{Object.keys(w).forEach(he=>{let be=w?.[he]?.documentMetadata||{},Le=w?.[he]?.notifications?.reduce((qe,ke)=>(qe[ke.notificationId]=ke,qe),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(qe=>{qe.notification=this.getClientNotificationObject(qe)}),this.setNotificationForDocumentIdInCache(he,be,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",m=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),m||(m=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(z=>{let Z=z.notification;return Z.metadata&&(Z.metadata.documentName=i?.documentName||Z.metadata.documentName,Z.metadata.organizationMetadata=m||Z.metadata.organizationMetadata,Z.metadata.documentMetadata=i||Z.metadata.documentMetadata),C&&(Z=this.notificationUtilsService.mergeLocationWithNotification({notification:Z},C)?.notification),Z})?.filter(z=>!!z)||[],w=new Map(h.map(z=>[z.id,z]));E.forEach(z=>{w.set(z.id,z)});let V=Array.from(w.values()).sort((z,Z)=>(Z.timestamp||0)-(z.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:V,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ue(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ue(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let m=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;m.setDate(m.getDate()-p);let h=m.getTime();return Co(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[DB("timestamp"),OB(h),TB(i)],firestoreQuery:[Ya("timestamp","desc"),gt("timestamp",">=",h),gt("notification.actionUser.userId","!=",a.userId),qv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ue(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,w)=>w.timestamp-E.timestamp),C)),jn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),se([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return se([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),se([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ue(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ue(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ue(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Pt(r?.userId),m=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;m.setDate(m.getDate()-p);let h=m.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[DB("timestamp"),OB(h),TB(50)],firestoreQuery:[Ya("timestamp","desc"),gt("timestamp",">=",h),gt("notification.actionUser.userId","!=",r.userId),qv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ue(C=>C?.data?se(C).pipe(ce(E=>E?.data),ce(E=>{let w=Object.values(E||{});return w.forEach(z=>{z.notification=this.getClientNotificationObject(z)}),w.sort((z,Z)=>Z.timestamp-z.timestamp),w.map(z=>z.notification).filter(z=>!!z)}),ue(E=>{let w={data:E?.reduce((V,z)=>(V[z.id]={notification:z},V),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:w,feature:"allUserNotifications"}).pipe(ce(V=>Object.values(V?.data||{}).map(z=>z?.notification)))})):se(null)))}return se(null)}),ue(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ue(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=yn(e)),i&&typeof i=="object"){let s=Qo(i);r=yn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return qn(this.afAuth).pipe(Fe(s=>!!s),ue(s=>this.isFeatureAllowed({firebaseUser:s})),ue(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(m=>(s.featureAllowed=m,s))):se(s)),ue(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),se([])):se(s).pipe(ue(m=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,m.documentPaths=p,m)))),ue(m=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Fe(i=>!!i),ce(i=>T(I({},e),{config:i})),ue(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ue(i=>Ji(i.config,i.user,Re.NOTIFICATION)?se(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Fe(i=>!!i),ue(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=rn(this.db,`${e?r+"/"+j.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+j.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return $f(a).pipe(jn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),ce(s=>{let m=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(C=>{let E=s?.raw[C];E?.id&&m.push(E)}),m.forEach(C=>{C.id&&p.set(C.id,C)})),this.notifications$.next(m),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(C=>{let E=s?.processed[C];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Pt(e?.email));let a;e?.userId&&(a=Pt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let h=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(h=!0);let C={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:h,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(C.id);if(E?.metadata&&(C.metadata={apiKey:E.metadata.apiKey,organizationId:E.metadata.organizationId,clientOrganizationId:E.metadata.clientOrganizationId,documentId:E.metadata.documentId,clientDocumentId:E.metadata.clientDocumentId,location:E?.location,locationId:E?.locationId}),C?.notificationSource==="comment"&&C?.targetAnnotationId){let w=this.commentService?.getAnnotationById(C.targetAnnotationId);w||E?.annotationData&&(w=E.annotationData),w&&(C.notificationSourceData=zn(w))}s.set(p.id,C)}}),s.forEach((p,h)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.notification?.[h]?.views?.[e?.userSnippylyId],s.set(h,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:i,metadata:r,views:a,notification:s}){try{let m=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&m){let h=null;m?.email&&(h=Pt(m?.email));let C=null;m?.userId&&(C=Pt(m?.userId));let E=!1,w=!0;(h&&p.notifyUsers?.[h]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(w=!1);let V={id:p.id};if(s?V=T(I(I({},V),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:w}):V={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:w,metadata:r},V?.notificationSource==="comment"&&V?.targetAnnotationId){let z=this.commentService?.getAnnotationById(V.targetAnnotationId);z||s?.notificationSourceData&&(z=s?.notificationSourceData),z||i?.annotationData&&(z=i.annotationData),z&&(V.notificationSourceData=zn(z))}return i?.targetAnnotationData?.isCommentResolverUsed&&(V.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),V}return}catch(m){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",m);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(m=>m.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new Dm({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let m=this.docService.getLocation();m&&(e.location=m?.location,e.locationId=m?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),h=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(h))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=rn(this.notificationsDb),r=this.processNotificationData(e);M5(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ue(e=>e?e.organizationId?this.getAllNotifications$().pipe(ue(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,m)=>(m.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Fg()):se(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,m=r.replace(s,(p,h)=>(h==="actionUser"||h==="recipientUser")&&a[h]?i?.email&&a[h].email===i?.email||i?.userId&&a[h]?.userId===i?.userId?"You":a[h].name||a[h].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[h]?a[h]:p);return this.domService.sanitizeHtml(m)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let m=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(m)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let m=r?.[s]?.notifications||[],p=m.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=m}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(tt(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ue(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(e){return te(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Pt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:m,documentId:p}=a;if(s&&m&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:m,documentId:p,apiKey:s}});h?.notificationId&&(h?.views?.[r]||(h.views||(h.views={}),h.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:m,documentId:p,apiKey:s},data:h})));let C=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:m}});C?.notificationId&&(this.getReadNotificationsOnForYouTab()?C?.views?.[r]||(C.views||(C.views={}),C.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:m},data:C})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:m}}))}}}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return te(this,null,function*(){try{this.getNotifications$().pipe(tt(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(e){try{this.settingsConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(e){try{this.settingsConfig$.next(e),this.updateSettingsConfigToDb()}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let i=!1;if(e.forEach(s=>{["email","inbox"].includes(s.id)&&(i=!s.values?.every(m=>["ALL","NONE","MINE"].includes(m.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e);let r={};e.forEach(s=>{if(s.enable){let m=s?.values?.find(p=>p.id===s.default);r[s.id]=m||s?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(r).forEach(s=>{a[s]=r[s].id}),this.setSettingsConfig(a)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return te(this,null,function*(){try{let i=Pt(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&r?.documentId&&this.getEnableSettings()&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:i},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}};o.\u0275fac=function(i){return new(i||o)(Q(bi),Q(Ze),Q(He),Q(jt),Q(Tn),Q(t0),Q(Jv),Q(Es),Q(hn),Q(ct),Q(Ne),Q(fn),Q(y),Q(TM),Q(Gn),Q(Uo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ho=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new Ce(j.CommentAnnotationStatusMap),this._customPriorityMap=new Ce(j.CommentAnnotationPriorityMap),this._customCategoryMap=new Ce(j.CommentCategoryMap);try{let i=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(j.CommentAnnotationStatusMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(j.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(j.CommentAnnotationPriorityMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(j.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[j.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([m,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([m,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=j.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>j.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
195
+ `+Ar),Mc&&_M([Be,xe,wn],ws=>{Ar=mb(Ar,ws," ")}),Le&&Cg?Le.createHTML(Ar):Ar},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};qm(Yt),vg=!0},o.clearConfig=function(){Wm=null,vg=!1},o.isValidAttribute=function(Yt,Ve,It){Wm||qm({});let Gt=vo(Yt),no=vo(Ve);return S_(Gt,no,It)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&cb(fe[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let It=v7e(fe[Yt],Ve);return It===-1?void 0:C7e(fe[Yt],It,1)[0]}return sle(fe[Yt])},o.removeHooks=function(Yt){fe[Yt]=[]},o.removeAllHooks=function(){fe=ule()},o}var uH=_le();var yle={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Ne=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Ce(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Ce([]),this.mousedown=!1,this.windowMouseDown$=new Ke,this.windowPointerMove$=new Ce(null),this.windowPointerUp$=new Ce(null),this.documentSelectionChange$=new Ce(null),this.windowClick$=new Ce(null),this.windowScroll$=new Ce(null),this.windowResize$=new Ce(null),this.windowKeyupBackspace$=new Ce(null),this.windowKeyupDelete$=new Ce(null),this.windowKeyupEsc$=new Ce(null),this.windowPopState$=new Ce(null),this.documentClick$=new Ce(null),this.documentClickSubject$=new Ke,this.documentFocus$=new Ce(null),this.windowKeydownShift$=new Ce(null),this.windowKeyupShift$=new Ce(null),this.mutation$=new Ce(null),this.childListMutation$=new Ce(null),this.networkStatus$=new Ce(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Ce({}),this.selectedAnnotationsLocationMap$=new Ce({}),this.recordingInProgress$=new Ce({}),this.deleteAnnotations$=new Ce([]),this.pinHighlighterClass$=new Ce(null),this.dialogOpenedInSidebar$=new Ce(!1),this.textHighlighterClass$=new Ce(null),this.commentPinHighlighter$=new Ce(!1),this.deviceInfo$=new Ce(new ei),this.customCss$=new Ce(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.filterSnippylyNodes=a=>{try{let s=[];return a.forEach(m=>{if(!zi(m))if(m instanceof HTMLElement){if(m.className.includes("cdk-overlay-container")||m.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(m.className.includes("cdk-overlay")){let p=!1;m.childNodes.forEach(h=>{zi(h)&&(p=!0)}),p||s.push(m)}else s.push(m)}else s.push(m)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new Ce(a),this.currentMousePosition$=new Ce(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Pi(),gn(([s,m])=>{try{let p=m.filter(C=>!s.includes(C)),h=s.filter(C=>!m.includes(C));h.length&&h.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",w=>{let V=this.calculateScreenSize();this.currentScreenSize$.next(V)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?Qoe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):Joe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===j.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(m=>{let p=m;if(typeof p.getAttribute=="function"){let h=p.getAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let C=this.xpathCacheId.get(h);C!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(C))}}}),zi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!zi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(j.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(j.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(m=>{a.target?.closest(m)&&(s=!1)}),s}),r=r.filter(a=>a.target&&To(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{oo(ri(window,"offline").pipe(ce(()=>!1)),ri(window,"online").pipe(ce(()=>!0)),new Lt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new ei),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==j.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return ri(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Pg}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let C=this.getXPath(i);C&&(r=C.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,m=e.clientY-a.y,p=s*100/(a.width||1),h=m*100/(a.height||1);this.currentMousePosition.element={xpath:i,topPercentage:h,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let m=e,p=m?.touches?.length?m.touches[0]?.clientX:m.clientX,h=m?.touches?.length?m.touches[0]?.clientY:m.clientY,C=this.getBackgroundElement(p,h,i,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),w=this.getXPath(C,!0),V=C.getBoundingClientRect(),z=p-V.x,Z=h-V.y,ae=z*100/(V.width||1),he=Z*100/(V.height||1),be={xpath:E,fXpath:w,leftPercentage:ae,topPercentage:he};if(a){let Le=this.getXPath(C,!0,!0);be.cfXpath=Le}return be}else return null}catch(m){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",m),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),m=[];s.forEach(h=>{zi(h)?m=[]:To(h)&&m.push(h)}),a&&(m=m.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||m?.forEach((h,C)=>{h.tagName.toLowerCase()==="svg"&&(p=C)}),m[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{zi(s)&&To(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,j.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),m=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(j.ATTRIBUTES.DEFAULT_CURSOR,m?JSON.stringify(m):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(j.VELT_SELECTION_COLOR)&&e.style.setProperty(j.VELT_SELECTION_COLOR,i),r&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(j.VELT_SELECTION_COLOR),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(j.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let m=s.split("/"),p=!1;m.forEach((h,C)=>{h.includes("svg")&&(p=!0),p&&(m[C]="svg:"+h)}),s=m.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let m=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(m){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(w=>w?.includes("snippyly")||w?.includes("velt")||["show-pin-cursor"].includes(w))[0]===m:!1);if(h.length>1){let C=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${m} ')][${C}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${m} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(m){return m.tagName==e.tagName});return this.calculateXPath(e.parentNode,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=Pn();a.setAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new ob;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new ob}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(E=>{E.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(E=>{E.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(E=>{E?.parentNode?.insertBefore(document.createTextNode(E?.textContent),E),E.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),h;for(;h=p.nextNode();)h?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(C=>C.classList.contains("velt-annotation-draft-checked")?(C.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(C,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(C,"velt-comment-dialog-shake"),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(C=>C),m=Object.keys(this.getRecordingInProgress()||{});s=[...s,...m];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let C=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let w=p[E];w?.to?.length||s.includes(E)||C.push(w)}else p[E]?.comments?.length||s.includes(E)||C.push(p[E])}),this.deleteAnnotations$.next(C),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(C=>{if(s.includes(C)&&(h[C]=p[C]),i)switch(i){case"comment":["comment","videoPin"].includes(p[C]?.type)||(h[C]=p[C]);break;default:p[C]?.type!==i&&(h[C]=p[C]);break}}),Object.keys(h).forEach(C=>{let E=h[C]?.multiThreadAnnotationId;E&&!h[E]&&(h[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(h)&&this.selectedAnnotationsMap$.next(h),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${j.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${j.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),m=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,m[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},m[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(m).forEach(p=>{s[p]||delete m[p]}),this.selectedAnnotationsLocationMap$.next(m)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),se([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let m=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),C=a.getBoundingClientRect();r.offsetLeft+=C.left-h.left,r.offsetTop+=C.top-h.top}}else m.position==="static"?m.transformStyle!="preserve-3d"&&m.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let m=window.getComputedStyle(a);m.position==="static"?m.transformStyle!="preserve-3d"&&m.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Lt(e=>{let i=ri(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=ri(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=ri(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),m=i.pipe(ue(p=>r.pipe(Pi(),ce(([h,C])=>({startPoint:p,prevPoint:h,curPoint:C})),ro(a)))).subscribe(e);return()=>m.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(j.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),m=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${m}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let m=this.getTextXPath(r);this.isXpathWithId(m)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let m=this.getElementFromXPath(i.commonAncestorContainer);m&&(i.commonAncestorContainerFXpath=this.getXPath(m,!0),i.commonAncestorContainerCFXpath=this.getXPath(m,!0,!0))}return i.text=e.toString(),i.occurrence=ju(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(j.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let m=document.getElementById(e[s]);m&&a.push(m)}if(i?.length)for(let s=0;s<i.length;s++){let m=document.getElementsByClassName(i[s]);for(let p=0;p<m.length;p++){let h=m[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let m=document.querySelectorAll(r[s]);for(let p=0;p<m.length;p++){let h=m[p];h&&h instanceof HTMLElement&&a.push(h)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${j.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),uH.sanitize(e,yle)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return uH.sanitize(e,yle)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ei;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),se(new ei)}}getTabId(){try{let e=sessionStorage.getItem(j.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=Pn(),sessionStorage.setItem(j.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new ei}}isMobileDevice(){try{return new ei().getDeviceType()===Xo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ei().getDeviceType()===Xo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ei().getDeviceType()===Xo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(m=>{s.setAttribute(m.name,m.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new ei().getDeviceType()===Xo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(i){return new(i||o)(Q(Yo),Q(y),Q(Fs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var He=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=m,this.analyticsService=p,this.loggingService=h,this.user$=new Ce(null),this.userOptions$=new Ce(null),this.userContacts$=new Ce(null),this.userOrganization$=new Ce(null),this.providedUser=new Do,this.firebaseConfig$=new Ce(null),this.advancedQueries$=new Ce(null),this.planDetails$=new Ce(null),this.signOutPreviousUser$=new Ce(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(C=>{this.config=C}),this.forceReLoggedIn=localStorage.getItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=qn(this.afAuth).pipe(Wo(this.afAuth.currentUser),Pi(),ue(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Fe(w=>w),tt(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(w=>te(this,[w],function*({previousUser:C,currentUser:E}){if(!E&&C){let V=C?.stsTokenManager?.expirationTime,z=new Date().getTime(),Z=V-z;z>V&&(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&C?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserWithoutContacts(this.lastLoggedInUserData.user),timeLeft:Z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),C=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",C)}),this.getUser$().pipe(qt(Vi)).subscribe(C=>{let E=ua(C);this.coreActionsService.triggerAction(Td.USER_UPDATE,E)})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new iM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||qn(this.afAuth).pipe(tt(1)).subscribe(r=>te(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield _d(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return te(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=_m(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let m=yield qn(this.afAuth).pipe(tt(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),m){let h=yield _d(m,!0).catch(w=>null);if(!h)return;let{user:C,firebaseConfig:E}=h.claims;if(m?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let w=yield _d(m,!0).catch(ae=>null);if(!w)return;let{firebaseConfig:V,user:z,advancedQueries:Z}=w.claims;this.validateOrganizationId(e),this.setFirebaseConfig(V),this.setAdvancedQueries(Z),z&&(this.providedUser.isAdmin=!!z.isAdmin),this.initializeSignedInUser(m,a),p=!1,this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s})}}if(p){this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId);let h=_r(this.functions,Sr({url:Xn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=pa(),E=(yield h({apiKey:this.apiKey,user:e,version:C,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let w={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(Td.ERROR,w)}else{let w={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(Td.ERROR,w),this.analyticsService.trackEvent(X.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId,e.userId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let w=yield _d(this.afAuth.currentUser,!0).catch(Z=>null);if(!w)return;let{user:V,advancedQueries:z}=w.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!V?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(m){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",m),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=pa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Xn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Rn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),jn(()=>se(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),qn(this.afAuth).pipe(ue(e=>e?this.user$.asObservable():se(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return SJ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(X.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Do;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers({userIds:[e.userId]});a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(yn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return te(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield _r(this.functions,Sr({url:Xn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:pa(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(X.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Fe(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ue(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):se(null)))}signOutUser(e="internal"){return te(this,null,function*(){try{yield this.analyticsService.trackEvent(X.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield qn(this.afAuth).pipe(tt(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),bJ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Ji(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return ua(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(bi),Q(jt),Q(Tm),Q(Wp),Q(Ne),Q(Uo),Q(Ze),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dm=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=vc(i)),r&&(this.organizationId=Cc(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var bM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=vc(i)),r&&(this.organizationId=Cc(r)),a&&(this.folderId=a,this.veltFolderId=xl(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${j.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var IM=class{};var hn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new Ce(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(jf(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Es=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new Ce(null),this.commentAnnotationById$=new Ce({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((m,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),m({});let C={},E=[...new Set(e.commentAnnotationIds||[])],w=T(I({},e),{commentAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=yc(()=>h?.get(w)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(Z=>r?{}:(s(),Z&&Z.statusCode!==200?(this.loggingService.catch(Z?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):Z?.data)).catch(Z=>{throw s(),Z});try{C=(yield z)||{},this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let Z={};Object.entries(C).forEach(([ae,he])=>{let be=this.commentAnnotationById$.value?.[ae];be?be&&JSON.stringify(be)!==JSON.stringify(he)&&(Z[ae]=he):Z[ae]=he}),Object.keys(Z).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),Z)),m(Z)}catch(Z){r||p(Z),m(C)}}else s(),m({})}catch(z){s(),p(z)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield yc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=I({},a);delete s?.[e],this.commentAnnotationById$._value=s;let m=yield yc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:qa.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return m&&m.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(m?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wm=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new Ce(null),this.reactionAnnotationById$=new Ce({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((m,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),m({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],w=T(I({},e),{reactionAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=yc(()=>h?.get(w)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(Z=>r?{}:(s(),Z&&Z.statusCode!==200?(this.loggingService.catch(Z?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):Z?.data)).catch(Z=>{throw s(),Z});try{C=(yield z)||{},this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let Z={};Object.entries(C).forEach(([ae,he])=>{let be=this.reactionAnnotationById$.value?.[ae];be?be&&JSON.stringify(be)!==JSON.stringify(he)&&(Z[ae]=he):Z[ae]=he}),Object.keys(Z).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),Z)),m(Z)}catch(Z){r||p(Z),m(C)}}else s(),m({})}catch(z){s(),p(z)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:qa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield yc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=I({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let m=yield yc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:qa.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return m&&m.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(m?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=m,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new Ce(null),this.documentIds$=new Ce([]),this.folderConfig$=new Ce(null),this.organizationConfig$=new Ce(null),this.firestorePaths$=new Ce(null),this.location$=new Ce(null),this.excludedLocationIds$=new Ce([]),this.organizationMetadata$=new Ce(null),this.documentMetadata$=new Ce(null),this.locationMetadata$=new Ce(null),this.customerMetadata$=new Ce(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Ce({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new Ce({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ke,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(or(this.DEBOUNCE_TIME)).subscribe({next:C=>{try{this.setDocumentIdImpl(C.documentId,C.clientOrganizationId,C.auto,C.avoidAnalytics,C.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:C=>{this.loggingService.catch("Error in setDocumentId subscription:",C),this.queueSize--}}),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C)}),this.configService.getApiKey$().subscribe(C=>{if(this.apiKey=C,this.apiKey){if(!this.isCustomDocId){let E=G6(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:C})}}),this.authService.getUser$().subscribe(C=>{C?(this.analyticsService.updateDefaultProperties({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&C?.organizationId&&this.documentPaths$.value?.organizationId!==C?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),C?.organizationId&&C?.clientOrganizationId&&this.organizationConfig$.next({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(C=>{let E={documentId:C?.documentId,clientDocumentId:C?.clientDocumentId};C?.organizationId&&(E.organizationId=C.organizationId,E.clientOrganizationId=C.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(C=>{this.analyticsService.updateDefaultProperties({folderId:C?.folderId,veltFolderId:C?.veltFolderId,allDocuments:C?.allDocuments})}),this.location$.subscribe(C=>{this.analyticsService.updateDefaultProperties({clientLocation:C?.location,locationId:C?.locationId})}),this.organizationMetadata$.subscribe(C=>{this.authService.setUserOrganization(C?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(C=>{C&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Fe(C=>!!C),tt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(C){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}},C=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(C){this.loggingService.catch("Error in DocService constructor:",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=G6(location.href);this.currentUrl!==e&&(this.currentUrl=e,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowPopstate: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let e=G6(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(m=>m.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(m=>r.includes(m.id))||!go(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,m=`${yn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:m,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let m=Date.now(),p=m-this.lastSetDocumentIdCallTime,h=m-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=m,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&h>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=m;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a,options:s??void 0})}catch(m){this.loggingService.catch("Error in setDocumentId:",m)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let m=this.authService.getUser();if(!m){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?xl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${yn(e)}`,C=m?.organizationId?i?Pt(i):m?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??m?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??m?.clientOrganizationId??""}),C&&this.documentPaths$.value?.organizationId&&C!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==C){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,w=new IM;E.clientDocumentId=e,w.clientDocumentId=e,E.documentId=h,w.documentId=h,C&&(E.organizationId=C,E.clientOrganizationId=i??m?.clientOrganizationId,w.organizationId=C,w.clientOrganizationId=i??m?.clientOrganizationId);let V=`${this.apiKey}`,z=`apiKey/${this.apiKey}`;C&&(V=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,z=`${z}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),w.organization=`apiKey/${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,w.document=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,w.comment=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,w.multiThread=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,w.area=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,w.recorder=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,w.reaction=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,w.commentViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,w.notificationViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,w.documentViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,w.locationViews=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${V}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${V}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${V}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,C&&(E.organizationMetadata=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${V}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${V}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),w.organizationUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,w.documentUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,w.notificationDocs=`${z}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,w.notificationUsers=`${z}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(w),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_ID_SET,{documentId:h,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return h}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(m){this.loggingService.catch("Error in setDocumentIdImpl: ",m)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,m=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)m.push(this.fetchDocuments(p));else{let C=[];for(let w=0;w<e.length;w+=20)C.push(e.slice(w,w+20));C.forEach(w=>{let V=JSON.parse(JSON.stringify(p));V.documentIds=w.map(z=>z.clientDocumentId),m.push(this.fetchDocuments(V))})}let h={};m.length>0&&Promise.all(m).then(C=>{C?.forEach(E=>{E?.forEach(w=>{w?.metadata?.documentId&&(h[w.metadata.documentId]=w.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(C=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",C)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],m={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(m));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let w=JSON.parse(JSON.stringify(m));w.documentIds=E.map(V=>V.clientDocumentId),s.push(this.fetchLocations(w))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(C=>{C?.forEach(E=>{E?.metadata?.documentId&&(p[E.metadata.documentId]=T(I({},p?.[E.metadata.documentId]??{}),{[E.location.id]:E}))})}),Object.keys(p||{}).length>0&&this.locationMetadata$.next(p)}).catch(h=>{this.loggingService.catch("Error in getLocationMetadata: ",h)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(jn(i=>se(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${yn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Pt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Qo(e),r=yn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(X.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(X.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new CM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>te(this,null,function*(){let s=new rM;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=I(I({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=I(I({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=Ei();let m=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(m){let C=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});C?.clientDocumentId?C?.folderId&&(C?.folderId!==m?.folderId||C?.veltFolderId!==m?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):C?.folderId===m?.folderId?(m?.folderId&&(s.folderId=m.folderId),m?.veltFolderId&&(s.veltFolderId=m.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${m?.folderId??""}`),p=!1):(m?.folderId&&(s.folderId=m.folderId),m?.veltFolderId&&(s.veltFolderId=m.veltFolderId))}if(h){let C={};Object.entries(s).forEach(([E,w])=>{C[E]=w}),go(C,h)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),m=new mM;m.locationId=i?.locationId,m.veltLocationId=_U(i?.location?.id??""),m.location=i?.location,m.pageInfo=Ei(),m?.pageInfo?.deviceInfo&&delete m?.pageInfo?.deviceInfo;let p=T(I({},s),{[j.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[j.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:m})}),h=T(I({},m),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(h)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:m.veltLocationId}});let C=this.locationMetadata$.value;if(C||(C={}),i?.location?.id){let E=C?.[a.documentId],w=E?.[i?.location?.id??""];C&&(E||(C[a.documentId]={}),w||(C[a.documentId][i?.location?.id??""]={}),C[a.documentId][i?.location?.id??""]=T(I({},w),{location:i?.location})),Object.keys(C||{}).length>0&&this.locationMetadata$.next(C)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?yn(JSON.stringify(Qo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let h=a[p];h.location?.id===e.id&&(r=I(I({},h.location),e),delete a[p])});let s=this.genarateLocationId(r),m={locationId:s,location:r};i=m,this.locations$.next(T(I({},a),{[s]:m})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(X.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(s){let m=JSON.parse(s),p=this.genarateLocationId(m);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),se({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${j.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let m={id:a},p=this.genarateLocationId(m);e[a]={element:r,location:{locationId:p,location:m}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(j.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let m=e?.[s.documentId];m&&(i[s.documentId]=m)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,m=this.getDocumentMetadata(s);if(!m)return;let p=m?.folderId,h=m?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),h?{veltFolderId:h}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),m=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||m||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=xl(e?.folderId);r.push(gt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(gt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=xl(e?.folderId);r.push(gt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(gt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],m=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=vc(p.documentId),C=m?.[h];C&&(m[h]=I(I({},C),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:Cc(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(m)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(C=>C.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let m=s.map(C=>vc(C)),p=[],h=this.locationMetadata$.value;h||(h={}),m.forEach(C=>{a.forEach(E=>{let w=this.location$.value;if(E?.id===w?.location?.id&&this.location$.next({locationId:w?.locationId,location:E}),E?.id){delete E?.metadata;let V=_U(E.id),z=h?.[C],Z=z?.[E.id];h&&(z||(h[C]={}),Z||(h[C][E.id]={}),h[C][E.id]=T(I({},Z),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:Cc(r),documentId:C,id:V}}))}})}),yield Promise.all(p),Object.keys(h||{}).length>0&&this.locationMetadata$.next(h)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let m=xl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:m,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[gt("metadata.veltParentFolderId","==",m)],folderId:m,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ue(e=>e?this.documentPaths$.pipe(ue(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),qt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?pi.RESTRICTED:pi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:pi.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),pi.PUBLIC}}changeDocumentAccessType(e){return te(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case pi.PUBLIC:r.features.all.restricted=!1;break;case pi.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(hn),Q(Ne),Q(jt),Q(y),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>te(this,null,function*(){return{}})},this.resolveOrganizationUsers=!0,this.resolveFolderUsers=!0,this.resolveDocumentUsers=!0,this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new mn,this.userDataProvider$=new Ce(null),this.userById$=new Ce({}),this.userByIdCalled$=new Ce({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(m){this.loggingService.catch("Error in UsersService getUserById:",m);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this)}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){try{switch(e){case"allOrganizationUsers":return!this.resolveOrganizationUsers;case"allFolderUsers":return!this.resolveFolderUsers;case"allDocumentUsers":return!this.resolveDocumentUsers;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(a){return te(this,arguments,function*({userIds:e,forceResolve:i,feature:r}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let s=!1;if(r&&(s=this.isResolverForFeatureDisabled(r)),this.userDataProvider$.getValue()&&!s){let m={},p=[],h={};if(e?.forEach(C=>{let E=this.getUserById(C);E?m[C]=E:this.userByIdCalled$.getValue()[C]?i&&p.push(C):(p.push(C),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[C]:!0})))}),p.length>0){let C=this.userDataProvider$.getValue();if(C){let E={};try{let w,V=new Promise((z,Z)=>{w=setTimeout(()=>{Z(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});E=yield Promise.race([C.get(p).finally(()=>{clearTimeout(w)}),V]),this.analyticsService.trackEvent(X.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:p})}catch(w){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",w,{userIds:p})}finally{p?.forEach(w=>{E[w]||(E[w]={userId:w,name:`User ${w}`})})}Object.entries(E).forEach(([w,V])=>{V&&(m[w]=E?.[w],h[w]=E?.[w])})}}return Object.keys(h).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),h)),m}else return{}}catch(s){return this.loggingService.catch("Error in UsersService resolveUsers:",s),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(gn(e=>te(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers({userIds:i})})))}getUsersFromCentralDb(i){return te(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers=!1:this.resolveOrganizationUsers=!0,e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers=!1:this.resolveFolderUsers=!0,e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers=!1:this.resolveDocumentUsers=!0}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(ct),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Sle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ble=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return dt.error("Error in isTestingDb:",t),!1}}};var Yp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new Ce(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield yc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return te(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield yc(()=>a?.delete({attachmentId:e,metadata:i,event:qa.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ze))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Jv=(()=>{let o=class o{constructor(e,i,r,a,s,m,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=m,this.attachmentResolverService=p,this.notificationActionTypeMap={[Ut.NEWLY_ADDED]:qa.COMMENT_ANNOTATION_ADD,[Ut.ADDED]:qa.COMMENT_ADD,[Ut.UPDATED]:qa.COMMENT_UPDATE,[Ut.DELETED]:qa.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,m)=>m.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(vm(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let m=s?.attachments;r&&m&&a.attachments?.forEach(p=>{let h=p?.attachmentId;m?.[h]&&(p.name=m?.[h]?.name,p.url=m?.[h]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!go(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},m=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:_v(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let w;r&&(w={},E.attachments?.forEach(V=>{w[V.attachmentId]={attachmentId:V.attachmentId,name:V.name,url:V.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),w&&{attachments:w})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let C=new ko;Object.assign(C,e),C.comments=e.comments?.map(E=>{let w=new Ec;if(Object.assign(w,E),w.isCommentResolverUsed=!0,r){let V=w.attachments?.map(z=>(z.isAttachmentResolverUsed=!0,delete z?.name,delete z?.url,z));w.attachments=V}return delete w?.commentHtml,delete w?.commentText,w})||[],m=C}return{strippedData:s,originalData:m,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(m=>m.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(vm(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let m=U6(this.authService.getFirebaseConfig()?.firebaseOptions),p=_r(this.functions,Sr({url:Xn.cloudFunction?.[m]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let w=r?.targetAnnotationData?.commentId;if(w){let V=e?.comments?.find(z=>z?.commentId===w);V&&(r.targetAnnotationData=V)}}let h=qp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),C={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Xn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:pa()},E=yield Mp(C,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(m){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",m)}})}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn),Q(He),Q(Uo),Q(jt),Q(Es),Q(Yp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ile=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ele=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers({userIds:i});for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var e0=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return te(this,null,function*(){try{return yield Mp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var TM=(()=>{let o=class o{constructor(e,i,r,a,s,m){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=m}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let m of s)i.add(m)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return te(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield Mp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Jv),Q(e0),Q(y),Q(Gn),Q(He),Q(Es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ole=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ale=(()=>{let o=class o{constructor(e,i,r,a,s,m){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=m}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=U6(this.authService.getFirebaseConfig()?.firebaseOptions),m=_r(this.functions,Sr({url:Xn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=qp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",C={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:pa()},E=yield Mp(C,h);yield m({veltData:E})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!go(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:_v(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn),Q(He),Q(Uo),Q(jt),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ple=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mle=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var t0=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E,w,V,z,Z,ae,he,be,Le,qe){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=m,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=C,this.notificationUtilsService=E,this.presenceUtilsService=w,this.reactionUtilsService=V,this.recorderUtilsService=z,this.selectionUtilsService=Z,this.tagUtilsService=ae,this.usersService=he,this.docService=be,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=qe}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:m,folderId:p}=i;m||(m=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:m?`${m}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"userConfig":return i?.userId&&i?.documentId&&h?.userConfig?`${h?.userConfig}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"comment":return i?.documentId&&i?.id&&h?.comment?`${h?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"allLastNotificationTimestamp":return h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&h?.area?`${h?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&h?.area?`${h?.area}`:void 0;case"allDocuments":return h?.document?`${h?.document}`:void 0;case"allLocations":return h?.location?`${h?.location}`:void 0;case"allFolders":return h?.folder?`${h?.folder}`:void 0;case"folder":return h?.folder&&i.folderId?`${h?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&h?.reaction?`${h?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return h?.organization?`${h?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&h?.folder?`${h?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&h?.location&&i?.id?`${h?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&h?.documentUsers?`${h?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&h?.folderUsers?`${h?.folderUsers}`:void 0;case"allOrganizationGroups":return h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return h?.organizationUsers?`${h?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&h?.commentViews?`${h?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&h?.commentViews?`${h?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&h?.notificationViews?`${h?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&h?.documentViews?`${h?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&h?.documentViews?`${h?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&h?.locationViews?`${h?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&h?.locationViews?`${h?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.docNotification?`${h?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return j.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return j.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return j.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return j.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return j.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return j.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return j.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return j.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return j.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:m,organizationId:p}=i;p||(p=r?.organizationId);let h=new Dm({apiKey:a,documentId:m?`${m}`:"",organizationId:p?`${p}`:""});switch(e){case"userConfig":return i?.userId&&i?.documentId&&h?.userConfig?`${h?.userConfig}/${i?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!s&&i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&h?.globalContacts?`${h?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&h?.globalContacts?`${h?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&h?.logins?`${h?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}`:void 0;case"customerMetadata":return h?.customerMetadata?`${h?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&h?.arrow?`${h?.arrow}`:void 0;case"arrow":return i?.documentId&&h?.arrow&&i.id?`${h?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&h?.cursor?`${h?.cursor}`:void 0;case"cursor":return i?.documentId&&h?.cursor&&i.id?`${h?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&h?.flock&&i.id?`${h?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&h?.flock&&i.id?`${h?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&h?.huddle?`${h?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&h?.huddle?`${h?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&h?.huddle?`${h?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&h?.huddle?`${h?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&h?.liveState?`${h?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&h?.liveState?`${h?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&h?.liveStateSingleEditorMode?`${h?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&h?.liveState?`${h?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&h?.presence&&i?.userId?`${h?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&h?.presence?`${h?.presence}`:void 0;case"workspaceIam":return h?.workspaceIam?`${h?.workspaceIam}`:void 0;case"selection":return i?.documentId&&h?.selection&&i?.userId?`${h?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&h?.selection?`${h?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&h?.syncVideoPlayer?`${h?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&h?.tag?`${h?.tag}`:void 0;case"tag":return i?.documentId&&h?.tag&&i?.id?`${h?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&h?.userContactUs?`${h?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&h?.userFeedback?`${h?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&h?.userReportBugs?`${h?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&h?.comment?`${h?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"allDocuments":return!s&&h?.docs&&i?.documentId?`${h?.docs}/${i?.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&h?.area?`${h?.area}`:void 0;case"area":return!s&&i?.id&&h?.area?`${h?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&h?.organizationIam?`${h?.organizationIam}users/`:void 0;case"reaction":return!s&&i?.id&&h?.reaction?`${h?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"organizationMetadata":return!s&&h?.organizationMetadata?`${h?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentIam":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&h?.views?`${h?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&h?.views?`${h?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&h?.views?`${h?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&h?.views?`${h?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(m){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",m);return}}resolveAnnotations(r){return te(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(m){return te(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}):this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,m])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(m,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,m])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(m,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),se(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let m=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,m);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",m),i}}modifyAndSetData(s){return te(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let m=yield this.modifyData({feature:e,data:i});r.next({data:m,operation:a})}catch(m){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",m)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return te(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return te(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:m=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=i?.metadata?.documentId,w=i?.metadata?.veltFolderId;return Object.keys(r).filter(V=>V.includes(C)&&(!E||V.includes(E)||w&&V.includes(w))).forEach(V=>{let z=r[V]?.subject?.getValue()??{};a==="DELETE"?s&&z?.data?.[s]&&(delete z?.data?.[s],r[V]?.subject&&r[V].subject.next({data:z?.data,operation:m})):r[V]?.subject?.next({data:T(I({},z?.data),{[i?.annotationId]:i}),operation:m})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",m),e}})}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Sle),Q(ble),Q(Jv),Q(Ile),Q(Ele),Q(xM),Q(Tle),Q(y),Q(Dle),Q(TM),Q(Ole),Q(Ale),Q(e0),Q(Ple),Q(Mle),Q(Gn),Q(ct),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kle=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new Ce(null);try{Rn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Fe(([a,s])=>!!a&&!!s),tt(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(XP(qp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||XP("DocumentIdDb");if(e){let i=nb(e,"generateDocumentId");return Wv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(jt),Q(He),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=m,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=C,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(w=>{if(w){this.db=w;let V=rn(w,".info/serverTimeOffset");this.offsetListener=Eu(V,z=>{let Z=z.val();this.offset=Z})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(w=>{w&&(this.firestore=w)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Rn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([i,r])=>!!i),tt(1),gn(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,m){return te(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>te(this,[C],function*({db:p,firestore:h}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let w=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let V,z;try{w&&(V=rn(p,`${w}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(z=Wv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:V,firestoreRef:z,data:a,firestorePath:E}),m&&m({firestoreAvailable:!!h})}catch(V){this.loggingService.catch(`Error in ${e} operation: `,V),s&&s(V)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:m}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>te(this,null,function*(){if(h.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Hf(h.dbRef,JSON.parse(JSON.stringify(C)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:w,eventType:V}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:m?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:V,commentId:m?.targetAnnotationData?.commentId})),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:w,firestorePath:h.firestorePath??"",extraData:m}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:w,firestorePath:h.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield nle(this.firestore,z=>te(this,null,function*(){z.set(h.firestoreRef,C)}))):yield rH(h.firestoreRef,C)}}catch(C){this.loggingService.catch(`Error in setData for ${e}`,C)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:m}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>te(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield V5(h.dbRef,JSON.parse(JSON.stringify(C)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:w,eventType:V}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:m?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:V,commentId:m?.targetAnnotationData?.commentId})),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:w,firestorePath:h.firestorePath??"",extraData:m}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),w&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:w,firestorePath:h.firestorePath??""}))}else yield rH(h.firestoreRef,C,{merge:!0})}}catch(C){this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return te(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,m=>te(this,null,function*(){m.dbRef&&(yield L5(m.dbRef));try{if(m.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:m.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:m.firestorePath??"",eventType:"DELETE"}))}else yield Xse(m.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(m){this.loggingService.catch(`Error in deleteData for ${e}`,m)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=Pn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),Pn()||"noDocumentId"}}queryData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return te(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=nb(this.firestore,r);i?.useCollectionGroup&&(a=nH(this.firestore,r));let s=i?.firestoreQuery??[],m=oH(a,...s);if(i?.getCount){let p=yield Jse(m).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield tle(m).catch(E=>(this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let h=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:h})}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,i){return te(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=rn(this.db,r),s=i?.rtdbQuery??[],m=wB(a,...s),p=yield xB(m).catch(C=>(this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let h=p.val();return h?i?.skipObjectValues?h:Object.values(h??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let m=yield ele(Wv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!m)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=m.data();return i?.field?p?.[i.field]??{}:p??{}}catch(m){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,m),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let m=yield xB(rn(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!m)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=m.val();return i?.field?p?.[i.field]??{}:p??{}}catch(m){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,m),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Rn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([s,m])=>s?r&&!m?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ue(([s,m])=>{try{if(r&&m){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Ce({}),count:0};let C=this.handleFirestoreListener(e,i,m).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Lt(h=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{C?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s)return this.handleRealtimeDbListener(e,i,s);return se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Ng(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Lt(m=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,m,i):this.setupDocumentListener(r,a,e,m,i);return()=>{m.complete(),m.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ue(m=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:m})),ue(m=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:m,feature:e}):se(m)),ue(m=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:m,feature:e}):se(m)),qt(Vi)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,i,r,a,s){let m=`${r}-${JSON.stringify(s)}`,p=nb(e,i);if(s?.useCollectionGroup&&(p=nH(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=oH(p,...E)}let h=!0,C=[];return iH(p,E=>{try{let w=JSON.parse(JSON.stringify(this.observablesCache[m]?.subject?.getValue()?.data??{})),V=null,z=!1;E?.docChanges()?.length?E.docChanges().forEach(Z=>{["allComments","allReactions"].includes(r)&&!h&&Z.type!=="removed"&&C.push(Z.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:Z,cache:this.observablesCache[m]?.subject?.getValue()?.data??{}})||(z=!0,Object.assign(w,this.handleCollectionChange(Z,w)),Z.type==="removed"&&(V||(V={type:Z.type,ids:[]}),V.ids.push(Z.doc.id)))}):z=!0,z&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:w,subscriber:a,operation:V})),h=!1}catch(w){this.handleListenerError(w,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let m=Wv(e,i);return iH(m,p=>{try{let h=p.data()||{};s?.field&&(h=h?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:h,subscriber:a,operation:null})}catch(h){this.handleListenerError(h,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let s=rn(r,a);if(i?.useQuery&&i?.rtdbQuery){let m=i?.rtdbQuery??[];s=wB(s,...m)}return $f(s).pipe(jn(m=>(this.loggingService.catch(`RTDB listener error for ${e}:`,m),se({}))),ce(m=>(m===null&&(m={}),m&&typeof m=="object"?Object.entries(m??{}).reduce((h,[C,E])=>(h[C]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(m,i))),ue(m=>this.commonDbUtilsService.modifyData({feature:e,data:m})),ue(m=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:m}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(t0),Q(y),Q(kle),Q(hn),Q(jt),Q(ct),Q(Gn),Q(Es),Q(wm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ci=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=m,this.commonDbService=p,this.usersService=h,this.db=Ii(),this.internalUserContacts$=new Ce([]),this.userGlobalContact$=new Ce(!1),this.userGroupContact$=new Ce(null),this.users$=new Ce([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new Ce([]),this.userFolderContacts$=new Ce([]),this.userDocumentContacts$=new Ce([]),this.userOrganizationGroups$=new Ce([]),this.onContactSelectedSubject$=new Ke,this.documentAccessType=null,this.atHereEnabled$=new Ce(!1),this.atHereLabel$=new Ce("here"),this.atHereDescription$=new Ce(null),this.contactListScopeForOrganizationUsers$=new Ce([ki.ALL]),this.customUserContacts$=new Ce(null),this.customUserContactsConfig$=new Ce({merge:!1}),this.currentOrganizationUserIAM$=new Ce(null),this.userContacts$=new Ce([]),this.userSnippylyIdContacts$=new Ce(null),this.usersByOrganizationId$=new Ce({}),this.usersByOrganizationIdAndDocumentId$=new Ce({}),this.usersByOrganizationIdAndFolderId$=new Ce({}),this.userById$=new Ce({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ue(C=>this.docService.getDocumentPaths$().pipe(gn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>te(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(C),this.setLoggedInUser(C),yield this.moveGlobalContactUserFromEmailToUserIdPath(C),this.updateUserInGlobalContactsIfAvailable(C),C?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(C?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0)}),C=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",C)}),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C)},C=>{this.loggingService.catch("Error in ContactService constructor getDb: ",C)}),this.getOrganizationGroups$().subscribe(C=>{this.authService.setOrganizationUserGroups(C)}),Rn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,w])=>{E?w?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let w=E?.userSnippylyId||_m(this.configService.getApiKey(),E.userId);w&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[w]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let m=r.contacts[s];if(m?.userId){let p=Pt(m?.userId);a[p]=m}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Do;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(m=>m?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(m=>{if(m?.userId){let p=Pt(m?.userId);r[p]=m}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Pt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>te(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Pt(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return te(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(tt(1)).subscribe(i=>te(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===pi.PUBLIC)r=!0;else if(a===pi.RESTRICTED){let s=Pt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let m=Pt(this.user?.email);i?.users?.[m]&&(r=!0)}}if(r){let s=new Gp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>te(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Pt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Rn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,m,p,h,C,E,w])=>{let V={},z=!1;E&&!E?.merge&&(z=!0);let Z=qe=>w.some(ke=>qe.includes(ke)),ae=Z([ki.ALL,ki.ORGANIZATION])?Object.keys(s?.[i]||{}):[],he=a?Z([ki.ALL,ki.FOLDER])?Object.keys(m?.[i]?.[a]||{}):[]:[],be=Z([ki.ALL,ki.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...ae,...he||[],...be].forEach(qe=>{let ke=h?.[qe];ke&&(V[qe]=ke)}),C){let{merge:qe,options:ke}=E||{},{organizationId:_e,documentId:Ee,folderId:Pe}=ke||{},ye=Pe?xl(Pe):void 0;(!_e||_e===i)&&(!Ee||Ee===r)&&(!ye||ye===a)&&(qe||(V={}),C.forEach(fe=>{fe?.userId&&(V[fe.userId]=fe)}))}return Object.values(V??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),se([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Fe(e=>!!e),ue(e=>this.docService.getDocumentPaths$().pipe(Fe(i=>!!i),gn(i=>{this.documentPaths=i}),ce(()=>e))),ue(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Pt(e?.userId)}}).pipe(ce(r=>r?.data),gn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),oo(...i).pipe(ro(this.authService.getUser$().pipe(Fe(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ue(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),gn(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],se()):se():se())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ue(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):se():se()}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return se();if(!this.commonDbService.shouldUseFirestore())return se();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return se();let s=se([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(m=>m?.data)),s.pipe(ce(m=>{if(m){typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null);let p=Object.values(m??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?se(e).pipe(ue(i=>this.docService.getDocumentPaths$().pipe(Fe(r=>!!r),gn(r=>{this.documentPaths=r}),ce(()=>i))),ue(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ue(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return se();let s=this.docService.getFolderConfig(),m=se([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)m=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(gt("metadata.apiKey","==",this.configService?.getApiKey()),gt("metadata.veltFolderId","==",s?.veltFolderId),gt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let C=0;C<a.length;C+=j.LISTENER_BATCH_SIZE)h.push(a.slice(C,C+j.LISTENER_BATCH_SIZE));m=Rn(h.map(C=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(gt("metadata.apiKey","==",this.configService?.getApiKey()),gt("metadata.documentId","in",C),gt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[gt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe(zr()))).pipe(ce(C=>ga(C)?.data))}return m.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let C=Object.values(h??{});this.setUserDocumentContacts(C)}else this.setUserDocumentContacts([])}))})):se():se())),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(m=>{s[i][m.user.userId]=m,this.userById$.next(T(I({},this.userById$.value),{[m.user.userId]:m.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(ki.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(ki.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?se(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),ce(()=>i))),ue(i=>{if(this.setUserOrganizationGroups([]),!i)return se();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case pi.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([ki.ALL,ki.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return te(this,null,function*(){try{if(this.analyticsService.trackEvent(X.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers({userIds:r});let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ue(e=>e?Rn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,m])=>{let p={};p.organizationUsers=i?.map(C=>this.convertToClientUser(C)),p.folderUsers=r?.map(C=>this.convertToClientUser(C)),p.documentUsers=a?.map(C=>this.convertToClientUser(C)),p.updatedContactList=m?.map(C=>this.convertToClientUser(C));let h=[];return s?.forEach(C=>{let E=this.convertToClientUserGroup(C,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),qt(Vi)):se(null)),jn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let m=Pt(s.userId);a[m]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(jt),Q(hn),Q(ct),Q(y),Q(Tn),Q(Gn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rle=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){dt.catch("Error in File utils getFileName: ",o);return}},_H=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){dt.catch("Error in File utils getFileExtension: ",o);return}},Nle=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+_H(n),{type:n.type})}catch(t){dt.catch("Error in File utils updateFile: ",t);return}},Fle=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),Lle={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Kp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=qy();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=qy(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Yv;r.name=i.name;let a=Nle(i,`${r.attachmentId}_${Rle(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=_H(i),r?.type&&(r.mimeType=Lle[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=Yy(this.storage,e.bucketPath),m=tV(s,i,{cacheControl:"public,max-age=3600"});m.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{eV(m.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(m){return te(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},h=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:qa.ATTACHMENT_ADD});h&&h.data?.url?(i.url=h.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,m)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:m}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:m})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),m(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let m=`${this.apiKey}/${e}/${i.name}`,p=Yy(this.storage,m),h=tV(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{eV(h.snapshot.ref).then(C=>{a(C)}).catch(C=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,C),s(C)})})}else{let m=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",m),s(m)}}catch(m){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,m),s(m)}})}downloadAttachment(e){try{if(e.url){let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(j.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let m=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(m),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(m=>{s(m)});else{let m=Yy(this.storage,e.bucketPath);JB(m).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=Yy(this.storage,e);JB(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(Q(He),Q(jt),Q(y),Q(Yp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=m,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new Ce(null),this.workspaceIAM$=new Ce(null),this.roles$=new Ce([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Fe(C=>!!C),tt(1)).subscribe(C=>{C&&(this.db=C,this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(tt(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(X.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(C=>{C?.accessType&&this.contactService.setDocumentAccessType(C.accessType)})}catch(C){this.loggingService.catch("Error in IamService constructor: ",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Fe(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Fe(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new oM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(jn(e=>se(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),qt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:j.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ue(e=>this.getRole$().pipe(ce(i=>(i===po.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ue(()=>this.documentIAM$.pipe(Fe(i=>!!i),ue(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ue(()=>this.configService.getSF$()),ue(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),ue(()=>this.documentIAM$.pipe(Fe(e=>!!e))),ue(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return po.ADMIN;if(!e&&this.user?.isAdmin)return po.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?pi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||pi.PUBLIC:null){case pi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||po.COMMENTER;break;case pi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===po.ADMIN),qt())}isUserAdmin(){try{return this.getRole()===po.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Pt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Pt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Pt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Pt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(Q(Ze),Q(He),Q(Ci),Q(hn),Q(ct),Q(jt),Q(y),Q(Tn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vn=(()=>{let o=class o{constructor(e,i,r,a,s,m,p,h,C,E,w,V,z,Z,ae,he){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=m,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=C,this.docService=E,this.domService=w,this.iamService=V,this.loggingService=z,this.notificationUtilsService=Z,this.usersService=ae,this.functions=he,this.db=Ii(),this.notificationsDb=Ii(void 0,Xn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new Ce([]),this.rawNotificationsByIdMap$=new Ce(new Map),this.processedNotifications$=new Ce([]),this.readNotificationsOnForYouTab$=new Ce(!1),this.notificationViews$=new Ce({}),this.notificationsByIdMap$=new Ce(new Map),this.historyPanelVisible$=new Ce(!1),this.notificationsForYou$=new Ce(null),this.notificationsByDocumentIdMap$=new Ce(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new Ce(null),this.maxNotificationDays$=new Ce(15),this.tabConfig$=new Ce({people:{enable:!1}}),this.settingsConfig$=new Ce({inbox:"ALL",email:"MINE"}),this.muteAllNotifications$=new Ce(!1),this.enableSettings$=new Ce(!1),this.settingsInitialConfig$=new Ce([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Fe(be=>!!be),tt(1)).subscribe(be=>{be&&(this.db=be,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},be=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",be)}),this.authService.getUser$().subscribe(be=>{be?(this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue()),this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(be=>{if(be){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(be||{}).forEach(qe=>{let ke=Le?.[qe]?.notifications;ke?.length&&ke.forEach(_e=>{this.notificationUtilsService.mergeLocationWithNotification({notification:_e},be)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(be){this.loggingService.catch("Error in NotificationService constructor: ",be)}}setDBConfigDataToInitialConfig(e){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{i[r]=a}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=Pt(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:i}});r?.notificationsConfig&&this.setDBConfigDataToInitialConfig(r?.notificationsConfig),yield this.updateSettingsConfigToDb()}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=Pt(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Fe(i=>i===!0),ue(()=>this.docService.getDocumentPaths$().pipe(Fe(i=>!!i),ue(i=>Co(this.getInitialConfigFromDB(i)).pipe(ue(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?.documentId,userId:e}}).pipe(ce(r=>{r?.data?.notificationsConfig&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next({})}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Pi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),m=a?.map(h=>({documentId:h,timestamp:i?.find(C=>C.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let C=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:C}}).filter(h=>{let C=e?.find(E=>E.documentId===h.documentId)?.timestamp;return C&&h.timestamp&&C!==h.timestamp});m?.length&&this.fetchNotificationsForDocumentIds(m),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(h=>{this.removeNotificationsForDocumentId(h)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),m=r?.organizationId||i?.organizationId;return s&&m&&(a=new Dm({apiKey:s,organizationId:m})),{user:i,documentPaths:a}}))),ue(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,m=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-m);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Ui(gt("timestamp",">=",p)),Ya("timestamp","desc"),qv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let C=[];return Object.keys(h||{}).forEach(E=>{let w=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],V=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(V&&V.id&&V?.timestamp===w){let z=V.id,Z=h[E]?.metadata?.documentId,ae=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),he=ae?.[Z]??{documentMetadata:null,notifications:[]},be=he.notifications??[],Le=be?.findIndex(qe=>qe.id===z);Le!==-1&&(be.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},ae),{[Z]:T(I({},he),{notifications:be})})))}C.push({documentId:E,timestamp:w})}),C}),jn(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),se([]))))}return se(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),se([])}}fetchNotificationsForDocumentIds(e,i=15){return te(this,null,function*(){try{if(e?.length){let r=_r(this.functions,Sr({url:Xn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),m={};e.forEach(V=>{if(V?.documentId){let z=this.getAllowedDocumentMetadataByDocumentId(V.documentId);z&&(m[V.documentId]=z)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:m},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),w=yield joe(C,E);if(w&&typeof w=="object"){let V=this.usersService.userDataProviderAvailable(),z=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Z=[],ae=[];Object.keys(w).forEach((he,be)=>{let Le=w[he].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[he]||!go(ke?.[he],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[he]:Le}))}let qe=w[he].notifications||[];qe.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(he,Le,qe),V&&Z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:qe,shouldAwait:!0,forceResolve:!0})),z&&ae.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:qe,shouldCommentAnnotationsResolverAwait:!0}))}),V&&Promise.all(Z).then(()=>{Object.keys(w).forEach(he=>{let be=w?.[he]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:w?.[he]?.notifications||[]});Le.forEach(qe=>{qe.notification=this.getClientNotificationObject(qe)}),this.setNotificationForDocumentIdInCache(he,be,Le)})}),z&&Promise.all(ae).then(()=>{Object.keys(w).forEach(he=>{let be=w?.[he]?.documentMetadata||{},Le=w?.[he]?.notifications?.reduce((qe,ke)=>(qe[ke.notificationId]=ke,qe),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(qe=>{qe.notification=this.getClientNotificationObject(qe)}),this.setNotificationForDocumentIdInCache(he,be,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",m=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),m||(m=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(z=>{let Z=z.notification;return Z.metadata&&(Z.metadata.documentName=i?.documentName||Z.metadata.documentName,Z.metadata.organizationMetadata=m||Z.metadata.organizationMetadata,Z.metadata.documentMetadata=i||Z.metadata.documentMetadata),C&&(Z=this.notificationUtilsService.mergeLocationWithNotification({notification:Z},C)?.notification),Z})?.filter(z=>!!z)||[],w=new Map(h.map(z=>[z.id,z]));E.forEach(z=>{w.set(z.id,z)});let V=Array.from(w.values()).sort((z,Z)=>(Z.timestamp||0)-(z.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:V,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ue(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ue(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let m=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;m.setDate(m.getDate()-p);let h=m.getTime();return Co(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[DB("timestamp"),OB(h),TB(i)],firestoreQuery:[Ya("timestamp","desc"),gt("timestamp",">=",h),gt("notification.actionUser.userId","!=",a.userId),qv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ue(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,w)=>w.timestamp-E.timestamp),C)),jn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),se([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return se([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),se([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ue(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ue(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ue(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Pt(r?.userId),m=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;m.setDate(m.getDate()-p);let h=m.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[DB("timestamp"),OB(h),TB(50)],firestoreQuery:[Ya("timestamp","desc"),gt("timestamp",">=",h),gt("notification.actionUser.userId","!=",r.userId),qv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ue(C=>C?.data?se(C).pipe(ce(E=>E?.data),ce(E=>{let w=Object.values(E||{});return w.forEach(z=>{z.notification=this.getClientNotificationObject(z)}),w.sort((z,Z)=>Z.timestamp-z.timestamp),w.map(z=>z.notification).filter(z=>!!z)}),ue(E=>{let w={data:E?.reduce((V,z)=>(V[z.id]={notification:z},V),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:w,feature:"allUserNotifications"}).pipe(ce(V=>Object.values(V?.data||{}).map(z=>z?.notification)))})):se(null)))}return se(null)}),ue(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ue(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=yn(e)),i&&typeof i=="object"){let s=Qo(i);r=yn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return qn(this.afAuth).pipe(Fe(s=>!!s),ue(s=>this.isFeatureAllowed({firebaseUser:s})),ue(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(m=>(s.featureAllowed=m,s))):se(s)),ue(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),se([])):se(s).pipe(ue(m=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,m.documentPaths=p,m)))),ue(m=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Fe(i=>!!i),ce(i=>T(I({},e),{config:i})),ue(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ue(i=>Ji(i.config,i.user,Re.NOTIFICATION)?se(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Fe(i=>!!i),ue(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=rn(this.db,`${e?r+"/"+j.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+j.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return $f(a).pipe(jn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),ce(s=>{let m=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(C=>{let E=s?.raw[C];E?.id&&m.push(E)}),m.forEach(C=>{C.id&&p.set(C.id,C)})),this.notifications$.next(m),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(C=>{let E=s?.processed[C];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Pt(e?.email));let a;e?.userId&&(a=Pt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let h=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(h=!0);let C={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:h,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(C.id);if(E?.metadata&&(C.metadata={apiKey:E.metadata.apiKey,organizationId:E.metadata.organizationId,clientOrganizationId:E.metadata.clientOrganizationId,documentId:E.metadata.documentId,clientDocumentId:E.metadata.clientDocumentId,location:E?.location,locationId:E?.locationId}),C?.notificationSource==="comment"&&C?.targetAnnotationId){let w=this.commentService?.getAnnotationById(C.targetAnnotationId);w||E?.annotationData&&(w=E.annotationData),w&&(C.notificationSourceData=zn(w))}s.set(p.id,C)}}),s.forEach((p,h)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.notification?.[h]?.views?.[e?.userSnippylyId],s.set(h,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:i,metadata:r,views:a,notification:s}){try{let m=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&m){let h=null;m?.email&&(h=Pt(m?.email));let C=null;m?.userId&&(C=Pt(m?.userId));let E=!1,w=!0;(h&&p.notifyUsers?.[h]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(w=!1);let V={id:p.id};if(s?V=T(I(I({},V),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:w}):V={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:w,metadata:r},V?.notificationSource==="comment"&&V?.targetAnnotationId){let z=this.commentService?.getAnnotationById(V.targetAnnotationId);z||s?.notificationSourceData&&(z=s?.notificationSourceData),z||i?.annotationData&&(z=i.annotationData),z&&(V.notificationSourceData=zn(z))}return i?.targetAnnotationData?.isCommentResolverUsed&&(V.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),V}return}catch(m){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",m);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(m=>m.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new Dm({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let m=this.docService.getLocation();m&&(e.location=m?.location,e.locationId=m?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),h=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(h))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=rn(this.notificationsDb),r=this.processNotificationData(e);M5(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ue(e=>e?e.organizationId?this.getAllNotifications$().pipe(ue(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,m)=>(m.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Fg()):se(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,m=r.replace(s,(p,h)=>(h==="actionUser"||h==="recipientUser")&&a[h]?i?.email&&a[h].email===i?.email||i?.userId&&a[h]?.userId===i?.userId?"You":a[h].name||a[h].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[h]?a[h]:p);return this.domService.sanitizeHtml(m)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let m=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(m)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let m=r?.[s]?.notifications||[],p=m.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=m}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(tt(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ue(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(e){return te(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Pt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:m,documentId:p}=a;if(s&&m&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:m,documentId:p,apiKey:s}});h?.notificationId&&(h?.views?.[r]||(h.views||(h.views={}),h.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:m,documentId:p,apiKey:s},data:h})));let C=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:m}});C?.notificationId&&(this.getReadNotificationsOnForYouTab()?C?.views?.[r]||(C.views||(C.views={}),C.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:m},data:C})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:m}}))}}}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return te(this,null,function*(){try{this.getNotifications$().pipe(tt(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(e){try{this.settingsConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(e){try{this.settingsConfig$.next(e),this.updateSettingsConfigToDb()}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let i=!1;if(e.forEach(s=>{["email","inbox"].includes(s.id)&&(i=!s.values?.every(m=>["ALL","NONE","MINE"].includes(m.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e);let r={};e.forEach(s=>{if(s.enable){let m=s?.values?.find(p=>p.id===s.default);r[s.id]=m||s?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(r).forEach(s=>{a[s]=r[s].id}),this.setSettingsConfig(a)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return te(this,null,function*(){try{let i=Pt(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&r?.documentId&&this.getEnableSettings()&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:i},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}};o.\u0275fac=function(i){return new(i||o)(Q(bi),Q(Ze),Q(He),Q(jt),Q(Tn),Q(t0),Q(Jv),Q(Es),Q(hn),Q(ct),Q(Ne),Q(fn),Q(y),Q(TM),Q(Gn),Q(Uo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ho=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new Ce(j.CommentAnnotationStatusMap),this._customPriorityMap=new Ce(j.CommentAnnotationPriorityMap),this._customCategoryMap=new Ce(j.CommentCategoryMap);try{let i=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(j.CommentAnnotationStatusMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(j.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(j.CommentAnnotationPriorityMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(j.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[j.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([m,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([m,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=j.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>j.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
196
196
  <path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
197
197
  <path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
198
198
  <path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>