@veltdev/sdk 4.4.0-beta.13 → 4.4.0-beta.14
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/package.json +1 -1
- package/velt.js +2 -2
package/velt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var SNIPPYLY_VERSION = '4.4.0-beta.
|
|
1
|
+
var SNIPPYLY_VERSION = '4.4.0-beta.14';
|
|
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 kfe=Object.create;var Dw=Object.defineProperty,Rfe=Object.defineProperties,Nfe=Object.getOwnPropertyDescriptor,Ffe=Object.getOwnPropertyDescriptors,Lfe=Object.getOwnPropertyNames,ww=Object.getOwnPropertySymbols,fz=Object.getPrototypeOf,f9=Object.prototype.hasOwnProperty,vz=Object.prototype.propertyIsEnumerable,Bfe=Reflect.get;var hz=(n,o,t)=>o in n?Dw(n,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[o]=t,I=(n,o)=>{for(var t in o||={})f9.call(o,t)&&hz(n,t,o[t]);if(ww)for(var t of ww(o))vz.call(o,t)&&hz(n,t,o[t]);return n},T=(n,o)=>Rfe(n,Ffe(o));var v9=(n,o)=>{var t={};for(var e in n)f9.call(n,e)&&o.indexOf(e)<0&&(t[e]=n[e]);if(n!=null&&ww)for(var e of ww(n))o.indexOf(e)<0&&vz.call(n,e)&&(t[e]=n[e]);return t};var Vfe=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),Aw=(n,o)=>{for(var t in o)Dw(n,t,{get:o[t],enumerable:!0})},Ufe=(n,o,t,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Lfe(o))!f9.call(n,i)&&i!==t&&Dw(n,i,{get:()=>o[i],enumerable:!(e=Nfe(o,i))||e.enumerable});return n};var Cz=(n,o,t)=>(t=n!=null?kfe(fz(n)):{},Ufe(o||!n||!n.__esModule?Dw(t,"default",{value:n,enumerable:!0}):t,n));var Pd=(n,o,t)=>Bfe(fz(n),t,o);var ee=(n,o,t)=>new Promise((e,i)=>{var r=c=>{try{s(t.next(c))}catch(p){i(p)}},a=c=>{try{s(t.throw(c))}catch(p){i(p)}},s=c=>c.done?e(c.value):Promise.resolve(c.value).then(r,a);s((t=t.apply(n,o)).next())});var RH=Vfe((Xqi,kH)=>{"use strict";var Ct={};Ct.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Ct.localCName=Ct.generateIdentifier();Ct.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 Pp=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Zi}};var hM=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Zi}};var NS=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var kp=class{constructor(){this.pageInfo=new Zi}},FS=function(n){return n.Start="start",n.End="end",n}(FS||{}),Bv=function(n){return n.Avatar="avatar",n.Label="label",n}(Bv||{});var fM=class{constructor(){this.sources=[],this.playerState=new LS}},LS=class{constructor(){this.volume=1}};var BS=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Zi}};var Rp=class{constructor(){this.visibility="private"}};var vM=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new Zi,this.isReactionResolverUsed=!1}};var CM=class{};var $t=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.config$=new fe(null),this.disableLogsConfig$=new fe({warnings:!0,suppressAll:!1}),this.apiKey$=new fe(""),this.baseFeatureAllowList=[],this.sf$=new fe(!1),this.sdkType$=new fe("core"),this.logsEnabled$=new fe(!0);try{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(),pt.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),re(!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),re("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()}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zae=(()=>{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(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new zu;return this.setLocalStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new zu}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let i=JSON.stringify(e);localStorage?.setItem(U.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(U.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new zu;return this.setSessionStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new zu}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let i=JSON.stringify(e);sessionStorage?.setItem(U.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(U.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gm=(()=>{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 wo,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 wo}}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 U.AVATAR_COLOR_LIST[e%U.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*U.AVATAR_COLOR_LIST.length);return U.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)(J(zae),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Np=(()=>{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 et),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 et),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),re(null)}}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:ese,setPrototypeOf:Gae,isFrozen:fPe,getPrototypeOf:vPe,getOwnPropertyDescriptor:CPe}=Object,{freeze:qa,seal:_l,create:tse}=Object,{apply:r$,construct:a$}=typeof Reflect<"u"&&Reflect;qa||(qa=function(o){return o});_l||(_l=function(o){return o});r$||(r$=function(o,t,e){return o.apply(t,e)});a$||(a$=function(o,t){return new o(...t)});var _M=Ya(Array.prototype.forEach),_Pe=Ya(Array.prototype.lastIndexOf),Wae=Ya(Array.prototype.pop),US=Ya(Array.prototype.push),yPe=Ya(Array.prototype.splice),SM=Ya(String.prototype.toLowerCase),e$=Ya(String.prototype.toString),qae=Ya(String.prototype.match),jS=Ya(String.prototype.replace),SPe=Ya(String.prototype.indexOf),bPe=Ya(String.prototype.trim),gc=Ya(Object.prototype.hasOwnProperty),Wa=Ya(RegExp.prototype.test),$S=IPe(TypeError);function Ya(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 r$(n,o,e)}}function IPe(n){return function(){for(var o=arguments.length,t=new Array(o),e=0;e<o;e++)t[e]=arguments[e];return a$(n,t)}}function ti(n,o){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:SM;Gae&&Gae(n,null);let e=o.length;for(;e--;){let i=o[e];if(typeof i=="string"){let r=t(i);r!==i&&(fPe(o)||(o[e]=r),i=r)}n[i]=!0}return n}function EPe(n){for(let o=0;o<n.length;o++)gc(n,o)||(n[o]=null);return n}function Gu(n){let o=tse(null);for(let[t,e]of ese(n))gc(n,t)&&(Array.isArray(e)?o[t]=EPe(e):e&&typeof e=="object"&&e.constructor===Object?o[t]=Gu(e):o[t]=e);return o}function HS(n,o){for(;n!==null;){let e=CPe(n,o);if(e){if(e.get)return Ya(e.get);if(typeof e.value=="function")return Ya(e.value)}n=vPe(n)}function t(){return null}return t}var Yae=qa(["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"]),t$=qa(["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"]),n$=qa(["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"]),xPe=qa(["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"]),i$=qa(["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"]),TPe=qa(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Kae=qa(["#text"]),Zae=qa(["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"]),o$=qa(["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"]),Xae=qa(["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=qa(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),wPe=_l(/\{\{[\w\W]*|[\w\W]*\}\}/gm),DPe=_l(/<%[\w\W]*|[\w\W]*%>/gm),APe=_l(/\$\{[\w\W]*/gm),OPe=_l(/^data-[\-\w.\u00B7-\uFFFF]+$/),MPe=_l(/^aria-[\-\w]+$/),nse=_l(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),PPe=_l(/^(?:\w+script|data):/i),kPe=_l(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ise=_l(/^html$/i),RPe=_l(/^[a-z][.\w]*(-[.\w]+)+$/i),Qae=Object.freeze({__proto__:null,ARIA_ATTR:MPe,ATTR_WHITESPACE:kPe,CUSTOM_ELEMENT:RPe,DATA_ATTR:OPe,DOCTYPE_NAME:ise,ERB_EXPR:DPe,IS_ALLOWED_URI:nse,IS_SCRIPT_OR_DATA:PPe,MUSTACHE_EXPR:wPe,TMPLIT_EXPR:APe}),zS={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},NPe=function(){return typeof window>"u"?null:window},FPe=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}},Jae=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ose(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:NPe(),o=Yt=>ose(Yt);if(o.version="3.2.5",o.removed=[],!n||!n.document||n.document.nodeType!==zS.document||!n.Element)return o.isSupported=!1,o;let{document:t}=n,e=t,i=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:h=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:_,DOMParser:E,trustedTypes:D}=n,B=c.prototype,G=HS(B,"cloneNode"),X=HS(B,"remove"),he=HS(B,"nextSibling"),Ie=HS(B,"childNodes"),Me=HS(B,"parentNode");if(typeof a=="function"){let Yt=t.createElement("template");Yt.content&&Yt.content.ownerDocument&&(t=Yt.content.ownerDocument)}let Le,We="",{implementation:ke,createNodeIterator:we,createDocumentFragment:Ee,getElementsByTagName:Pe}=t,{importNode:Ce}=e,ue=Jae();o.isSupported=typeof ese=="function"&&typeof Me=="function"&&ke&&ke.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Be,ERB_EXPR:Se,TMPLIT_EXPR:Ut,DATA_ATTR:Gt,ARIA_ATTR:Dt,IS_SCRIPT_OR_DATA:It,ATTR_WHITESPACE:Nt,CUSTOM_ELEMENT:Fn}=Qae,{IS_ALLOWED_URI:eo}=Qae,ii=null,Oi=ti({},[...Yae,...t$,...n$,...i$,...Kae]),dn=null,ui=ti({},[...Zae,...o$,...Xae,...yM]),Mi=Object.seal(tse(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}})),Am=null,go=null,Ws=!0,Br=!0,qs=!1,wl=!0,_c=!1,og=!0,Dl=!1,rg=!1,oh=!1,Om=!1,rh=!1,ag=!1,WC=!0,ah=!1,dw="user-content-",qC=!0,Mm=!1,yc={},Sc=null,Er=ti({},["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"]),Vr=null,sg=ti({},["audio","video","img","source","image","track"]),sh=null,YC=ti({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),lh="http://www.w3.org/1998/Math/MathML",bc="http://www.w3.org/2000/svg",Ys="http://www.w3.org/1999/xhtml",Pm=Ys,lg=!1,KC=null,l9=ti({},[lh,bc,Ys],e$),Ad=ti({},["mi","mo","mn","ms","mtext"]),cg=ti({},["annotation-xml"]),pw=ti({},["title","style","font","a","script"]),Al=null,ZC=["application/xhtml+xml","text/html"],XC="text/html",uo=null,km=null,ch=t.createElement("form"),QC=function(Ve){return Ve instanceof RegExp||Ve instanceof Function},Rm=function(){let Ve=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(km&&km===Ve)){if((!Ve||typeof Ve!="object")&&(Ve={}),Ve=Gu(Ve),Al=ZC.indexOf(Ve.PARSER_MEDIA_TYPE)===-1?XC:Ve.PARSER_MEDIA_TYPE,uo=Al==="application/xhtml+xml"?e$:SM,ii=gc(Ve,"ALLOWED_TAGS")?ti({},Ve.ALLOWED_TAGS,uo):Oi,dn=gc(Ve,"ALLOWED_ATTR")?ti({},Ve.ALLOWED_ATTR,uo):ui,KC=gc(Ve,"ALLOWED_NAMESPACES")?ti({},Ve.ALLOWED_NAMESPACES,e$):l9,sh=gc(Ve,"ADD_URI_SAFE_ATTR")?ti(Gu(YC),Ve.ADD_URI_SAFE_ATTR,uo):YC,Vr=gc(Ve,"ADD_DATA_URI_TAGS")?ti(Gu(sg),Ve.ADD_DATA_URI_TAGS,uo):sg,Sc=gc(Ve,"FORBID_CONTENTS")?ti({},Ve.FORBID_CONTENTS,uo):Er,Am=gc(Ve,"FORBID_TAGS")?ti({},Ve.FORBID_TAGS,uo):{},go=gc(Ve,"FORBID_ATTR")?ti({},Ve.FORBID_ATTR,uo):{},yc=gc(Ve,"USE_PROFILES")?Ve.USE_PROFILES:!1,Ws=Ve.ALLOW_ARIA_ATTR!==!1,Br=Ve.ALLOW_DATA_ATTR!==!1,qs=Ve.ALLOW_UNKNOWN_PROTOCOLS||!1,wl=Ve.ALLOW_SELF_CLOSE_IN_ATTR!==!1,_c=Ve.SAFE_FOR_TEMPLATES||!1,og=Ve.SAFE_FOR_XML!==!1,Dl=Ve.WHOLE_DOCUMENT||!1,Om=Ve.RETURN_DOM||!1,rh=Ve.RETURN_DOM_FRAGMENT||!1,ag=Ve.RETURN_TRUSTED_TYPE||!1,oh=Ve.FORCE_BODY||!1,WC=Ve.SANITIZE_DOM!==!1,ah=Ve.SANITIZE_NAMED_PROPS||!1,qC=Ve.KEEP_CONTENT!==!1,Mm=Ve.IN_PLACE||!1,eo=Ve.ALLOWED_URI_REGEXP||nse,Pm=Ve.NAMESPACE||Ys,Ad=Ve.MATHML_TEXT_INTEGRATION_POINTS||Ad,cg=Ve.HTML_INTEGRATION_POINTS||cg,Mi=Ve.CUSTOM_ELEMENT_HANDLING||{},Ve.CUSTOM_ELEMENT_HANDLING&&QC(Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Mi.tagNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&QC(Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Mi.attributeNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&typeof Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Mi.allowCustomizedBuiltInElements=Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),_c&&(Br=!1),rh&&(Om=!0),yc&&(ii=ti({},Kae),dn=[],yc.html===!0&&(ti(ii,Yae),ti(dn,Zae)),yc.svg===!0&&(ti(ii,t$),ti(dn,o$),ti(dn,yM)),yc.svgFilters===!0&&(ti(ii,n$),ti(dn,o$),ti(dn,yM)),yc.mathMl===!0&&(ti(ii,i$),ti(dn,Xae),ti(dn,yM))),Ve.ADD_TAGS&&(ii===Oi&&(ii=Gu(ii)),ti(ii,Ve.ADD_TAGS,uo)),Ve.ADD_ATTR&&(dn===ui&&(dn=Gu(dn)),ti(dn,Ve.ADD_ATTR,uo)),Ve.ADD_URI_SAFE_ATTR&&ti(sh,Ve.ADD_URI_SAFE_ATTR,uo),Ve.FORBID_CONTENTS&&(Sc===Er&&(Sc=Gu(Sc)),ti(Sc,Ve.FORBID_CONTENTS,uo)),qC&&(ii["#text"]=!0),Dl&&ti(ii,["html","head","body"]),ii.table&&(ti(ii,["tbody"]),delete Am.tbody),Ve.TRUSTED_TYPES_POLICY){if(typeof Ve.TRUSTED_TYPES_POLICY.createHTML!="function")throw $S('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ve.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw $S('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Le=Ve.TRUSTED_TYPES_POLICY,We=Le.createHTML("")}else Le===void 0&&(Le=FPe(D,i)),Le!==null&&typeof We=="string"&&(We=Le.createHTML(""));qa&&qa(Ve),km=Ve}},JC=ti({},[...t$,...n$,...xPe]),Ur=ti({},[...i$,...TPe]),gw=function(Ve){let yt=Me(Ve);(!yt||!yt.tagName)&&(yt={namespaceURI:Pm,tagName:"template"});let Wt=SM(Ve.tagName),to=SM(yt.tagName);return KC[Ve.namespaceURI]?Ve.namespaceURI===bc?yt.namespaceURI===Ys?Wt==="svg":yt.namespaceURI===lh?Wt==="svg"&&(to==="annotation-xml"||Ad[to]):!!JC[Wt]:Ve.namespaceURI===lh?yt.namespaceURI===Ys?Wt==="math":yt.namespaceURI===bc?Wt==="math"&&cg[to]:!!Ur[Wt]:Ve.namespaceURI===Ys?yt.namespaceURI===bc&&!cg[to]||yt.namespaceURI===lh&&!Ad[to]?!1:!Ur[Wt]&&(pw[Wt]||!JC[Wt]):!!(Al==="application/xhtml+xml"&&KC[Ve.namespaceURI]):!1},pa=function(Ve){US(o.removed,{element:Ve});try{Me(Ve).removeChild(Ve)}catch{X(Ve)}},Ic=function(Ve,yt){try{US(o.removed,{attribute:yt.getAttributeNode(Ve),from:yt})}catch{US(o.removed,{attribute:null,from:yt})}if(yt.removeAttribute(Ve),Ve==="is")if(Om||rh)try{pa(yt)}catch{}else try{yt.setAttribute(Ve,"")}catch{}},uw=function(Ve){let yt=null,Wt=null;if(oh)Ve="<remove></remove>"+Ve;else{let Tr=qae(Ve,/^[\r\n\t ]+/);Wt=Tr&&Tr[0]}Al==="application/xhtml+xml"&&Pm===Ys&&(Ve='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ve+"</body></html>");let to=Le?Le.createHTML(Ve):Ve;if(Pm===Ys)try{yt=new E().parseFromString(to,Al)}catch{}if(!yt||!yt.documentElement){yt=ke.createDocument(Pm,"template",null);try{yt.documentElement.innerHTML=lg?We:to}catch{}}let xr=yt.body||yt.documentElement;return Ve&&Wt&&xr.insertBefore(t.createTextNode(Wt),xr.childNodes[0]||null),Pm===Ys?Pe.call(yt,Dl?"html":"body")[0]:Dl?yt.documentElement:xr},hw=function(Ve){return we.call(Ve.ownerDocument||Ve,Ve,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Ec=function(Ve){return Ve instanceof _&&(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")},fw=function(Ve){return typeof s=="function"&&Ve instanceof s};function Ol(Yt,Ve,yt){_M(Yt,Wt=>{Wt.call(o,Ve,yt,km)})}let mg=function(Ve){let yt=null;if(Ol(ue.beforeSanitizeElements,Ve,null),Ec(Ve))return pa(Ve),!0;let Wt=uo(Ve.nodeName);if(Ol(ue.uponSanitizeElement,Ve,{tagName:Wt,allowedTags:ii}),Ve.hasChildNodes()&&!fw(Ve.firstElementChild)&&Wa(/<[/\w!]/g,Ve.innerHTML)&&Wa(/<[/\w!]/g,Ve.textContent)||Ve.nodeType===zS.progressingInstruction||og&&Ve.nodeType===zS.comment&&Wa(/<[/\w]/g,Ve.data))return pa(Ve),!0;if(!ii[Wt]||Am[Wt]){if(!Am[Wt]&&mh(Wt)&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Wt)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Wt)))return!1;if(qC&&!Sc[Wt]){let to=Me(Ve)||Ve.parentNode,xr=Ie(Ve)||Ve.childNodes;if(xr&&to){let Tr=xr.length;for(let wr=Tr-1;wr>=0;--wr){let Is=G(xr[wr],!0);Is.__removalCount=(Ve.__removalCount||0)+1,to.insertBefore(Is,he(Ve))}}}return pa(Ve),!0}return Ve instanceof c&&!gw(Ve)||(Wt==="noscript"||Wt==="noembed"||Wt==="noframes")&&Wa(/<\/no(script|embed|frames)/i,Ve.innerHTML)?(pa(Ve),!0):(_c&&Ve.nodeType===zS.text&&(yt=Ve.textContent,_M([Be,Se,Ut],to=>{yt=jS(yt,to," ")}),Ve.textContent!==yt&&(US(o.removed,{element:Ve.cloneNode()}),Ve.textContent=yt)),Ol(ue.afterSanitizeElements,Ve,null),!1)},e_=function(Ve,yt,Wt){if(WC&&(yt==="id"||yt==="name")&&(Wt in t||Wt in ch))return!1;if(!(Br&&!go[yt]&&Wa(Gt,yt))){if(!(Ws&&Wa(Dt,yt))){if(!dn[yt]||go[yt]){if(!(mh(Ve)&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Ve)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Ve))&&(Mi.attributeNameCheck instanceof RegExp&&Wa(Mi.attributeNameCheck,yt)||Mi.attributeNameCheck instanceof Function&&Mi.attributeNameCheck(yt))||yt==="is"&&Mi.allowCustomizedBuiltInElements&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Wt)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Wt))))return!1}else if(!sh[yt]){if(!Wa(eo,jS(Wt,Nt,""))){if(!((yt==="src"||yt==="xlink:href"||yt==="href")&&Ve!=="script"&&SPe(Wt,"data:")===0&&Vr[Ve])){if(!(qs&&!Wa(It,jS(Wt,Nt,"")))){if(Wt)return!1}}}}}}return!0},mh=function(Ve){return Ve!=="annotation-xml"&&qae(Ve,Fn)},dg=function(Ve){Ol(ue.beforeSanitizeAttributes,Ve,null);let{attributes:yt}=Ve;if(!yt||Ec(Ve))return;let Wt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:dn,forceKeepAttr:void 0},to=yt.length;for(;to--;){let xr=yt[to],{name:Tr,namespaceURI:wr,value:Is}=xr,Nm=uo(Tr),ir=Tr==="value"?Is:bPe(Is);if(Wt.attrName=Nm,Wt.attrValue=ir,Wt.keepAttr=!0,Wt.forceKeepAttr=void 0,Ol(ue.uponSanitizeAttribute,Ve,Wt),ir=Wt.attrValue,ah&&(Nm==="id"||Nm==="name")&&(Ic(Tr,Ve),ir=dw+ir),og&&Wa(/((--!?|])>)|<\/(style|title)/i,ir)){Ic(Tr,Ve);continue}if(Wt.forceKeepAttr||(Ic(Tr,Ve),!Wt.keepAttr))continue;if(!wl&&Wa(/\/>/i,ir)){Ic(Tr,Ve);continue}_c&&_M([Be,Se,Ut],dh=>{ir=jS(ir,dh," ")});let Tc=uo(Ve.nodeName);if(e_(Tc,Nm,ir)){if(Le&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!wr)switch(D.getAttributeType(Tc,Nm)){case"TrustedHTML":{ir=Le.createHTML(ir);break}case"TrustedScriptURL":{ir=Le.createScriptURL(ir);break}}try{wr?Ve.setAttributeNS(wr,Tr,ir):Ve.setAttribute(Tr,ir),Ec(Ve)?pa(Ve):Wae(o.removed)}catch{}}}Ol(ue.afterSanitizeAttributes,Ve,null)},xc=function Yt(Ve){let yt=null,Wt=hw(Ve);for(Ol(ue.beforeSanitizeShadowDOM,Ve,null);yt=Wt.nextNode();)Ol(ue.uponSanitizeShadowNode,yt,null),mg(yt),dg(yt),yt.content instanceof r&&Yt(yt.content);Ol(ue.afterSanitizeShadowDOM,Ve,null)};return o.sanitize=function(Yt){let Ve=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},yt=null,Wt=null,to=null,xr=null;if(lg=!Yt,lg&&(Yt="<!-->"),typeof Yt!="string"&&!fw(Yt))if(typeof Yt.toString=="function"){if(Yt=Yt.toString(),typeof Yt!="string")throw $S("dirty is not a string, aborting")}else throw $S("toString is not a function");if(!o.isSupported)return Yt;if(rg||Rm(Ve),o.removed=[],typeof Yt=="string"&&(Mm=!1),Mm){if(Yt.nodeName){let Is=uo(Yt.nodeName);if(!ii[Is]||Am[Is])throw $S("root node is forbidden and cannot be sanitized in-place")}}else if(Yt instanceof s)yt=uw("<!---->"),Wt=yt.ownerDocument.importNode(Yt,!0),Wt.nodeType===zS.element&&Wt.nodeName==="BODY"||Wt.nodeName==="HTML"?yt=Wt:yt.appendChild(Wt);else{if(!Om&&!_c&&!Dl&&Yt.indexOf("<")===-1)return Le&&ag?Le.createHTML(Yt):Yt;if(yt=uw(Yt),!yt)return Om?null:ag?We:""}yt&&oh&&pa(yt.firstChild);let Tr=hw(Mm?Yt:yt);for(;to=Tr.nextNode();)mg(to),dg(to),to.content instanceof r&&xc(to.content);if(Mm)return Yt;if(Om){if(rh)for(xr=Ee.call(yt.ownerDocument);yt.firstChild;)xr.appendChild(yt.firstChild);else xr=yt;return(dn.shadowroot||dn.shadowrootmode)&&(xr=Ce.call(e,xr,!0)),xr}let wr=Dl?yt.outerHTML:yt.innerHTML;return Dl&&ii["!doctype"]&&yt.ownerDocument&&yt.ownerDocument.doctype&&yt.ownerDocument.doctype.name&&Wa(ise,yt.ownerDocument.doctype.name)&&(wr="<!DOCTYPE "+yt.ownerDocument.doctype.name+`>
|
|
195
|
-
`+wr),_c&&_M([Be,Se,Ut],Is=>{wr=jS(wr,Is," ")}),Le&&ag?Le.createHTML(wr):wr},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rm(Yt),rg=!0},o.clearConfig=function(){km=null,rg=!1},o.isValidAttribute=function(Yt,Ve,yt){km||Rm({});let Wt=uo(Yt),to=uo(Ve);return e_(Wt,to,yt)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&US(ue[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let yt=_Pe(ue[Yt],Ve);return yt===-1?void 0:yPe(ue[Yt],yt,1)[0]}return Wae(ue[Yt])},o.removeHooks=function(Yt){ue[Yt]=[]},o.removeAllHooks=function(){ue=Jae()},o}var s$=ose();var rse={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{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 fe(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new fe([]),this.mousedown=!1,this.windowMouseDown$=new et,this.windowPointerMove$=new fe(null),this.windowPointerUp$=new fe(null),this.documentSelectionChange$=new fe(null),this.windowClick$=new fe(null),this.windowScroll$=new fe(null),this.windowResize$=new fe(null),this.windowKeyupBackspace$=new fe(null),this.windowKeyupDelete$=new fe(null),this.windowKeyupEsc$=new fe(null),this.windowPopState$=new fe(null),this.documentClick$=new fe(null),this.documentClickSubject$=new et,this.documentFocus$=new fe(null),this.windowKeydownShift$=new fe(null),this.windowKeyupShift$=new fe(null),this.mutation$=new fe(null),this.childListMutation$=new fe(null),this.networkStatus$=new fe(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new fe({}),this.selectedAnnotationsLocationMap$=new fe({}),this.recordingInProgress$=new fe({}),this.deleteAnnotations$=new fe([]),this.pinHighlighterClass$=new fe(null),this.dialogOpenedInSidebar$=new fe(!1),this.textHighlighterClass$=new fe(null),this.commentPinHighlighter$=new fe(!1),this.deviceInfo$=new fe(new Jn),this.customCss$=new fe(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(c=>{if(!ji(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(h=>{ji(h)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),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 fe(a),this.currentMousePosition$=new fe(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Vi(),In(([s,c])=>{try{let p=c.filter(_=>!s.includes(_)),h=s.filter(_=>!c.includes(_));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",D=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}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?Hie("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):zie("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===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let h=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let _=this.xpathCacheId.get(h);_!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(_))}}}),ji(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=>!ji(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(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(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{io(oi(window,"offline").pipe(ce(()=>!1)),oi(window,"online").pipe(ce(()=>!0)),new Ft(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 Jn),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()!==U.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 oi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),_g}}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 _=this.getXPath(i);_&&(r=_.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),h=c*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 c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,h=c?.touches?.length?c.touches[0]?.clientY:c.clientY,_=this.getBackgroundElement(p,h,i,r);if(_&&s&&typeof s=="function"&&(_=s(_)),_){let E=this.getXPath(_),D=this.getXPath(_,!0),B=_.getBoundingClientRect(),G=p-B.x,X=h-B.y,he=G*100/(B.width||1),Ie=X*100/(B.height||1),Me={xpath:E,fXpath:D,leftPercentage:he,topPercentage:Ie};if(a){let Le=this.getXPath(_,!0,!0);Me.cfXpath=Le}return Me}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(h=>{ji(h)?c=[]:xo(h)&&c.push(h)}),a&&(c=c.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||c?.forEach((h,_)=>{h.tagName.toLowerCase()==="svg"&&(p=_)}),c[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=>{ji(s)&&xo(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,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.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 c=s.split("/"),p=!1;c.forEach((h,_)=>{h.includes("svg")&&(p=!0),p&&(c[_]="svg:"+h)}),s=c.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 c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(_=>_.nodeType===1&&_.tagName===e.tagName?_.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(h.length>1){let _=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${_}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.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=xn();a.setAttribute(U.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 NS;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 NS}}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(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(_=>_.classList.contains("velt-annotation-draft-checked")?(_.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(_,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(_,"velt-comment-dialog-shake"),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||_.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(_,"velt-annotation-draft-checked")},100),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(_=>_),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let _=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||_.push(D)}else p[E]?.comments?.length||s.includes(E)||_.push(p[E])}),this.deleteAnnotations$.next(_),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(_=>{if(s.includes(_)&&(h[_]=p[_]),i)switch(i){case"comment":["comment","videoPin"].includes(p[_]?.type)||(h[_]=p[_]);break;default:p[_]?.type!==i&&(h[_]=p[_]);break}}),Object.keys(h).forEach(_=>{let E=h[_]?.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(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.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||{})),c=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,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}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),re([])}}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),re([])}}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 c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),_=a.getBoundingClientRect();r.offsetLeft+=_.left-h.left,r.offsetTop+=_.top-h.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 Ft(e=>{let i=oi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=oi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=oi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ge(p=>r.pipe(Vi(),ce(([h,_])=>({startPoint:p,prevPoint:h,curPoint:_})),oo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=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=`${c}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 c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Au(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(U.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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.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 c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let h=c[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),re(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(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.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;"),s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return s$.sanitize(e,rse)}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 Jn;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),re(new Jn)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=xn(),sessionStorage.setItem(U.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 Jn}}isMobileDevice(){try{return new Jn().getDeviceType()===Zo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Jn().getDeviceType()===Zo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Jn().getDeviceType()===Zo.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(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Jn().getDeviceType()===Zo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(J(qo),J(y),J(Ms))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=h,this.user$=new fe(null),this.userOptions$=new fe(null),this.userContacts$=new fe(null),this.userOrganization$=new fe(null),this.providedUser=new wo,this.firebaseConfig$=new fe(null),this.advancedQueries$=new fe(null),this.planDetails$=new fe(null),this.signOutPreviousUser$=new fe(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(_=>{this.config=_}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Wn(this.afAuth).pipe(Go(this.afAuth.currentUser),Vi(),ge(([_,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(D=>D),Je(1),ce(()=>({previousUser:_,currentUser:E}))))).subscribe(D=>ee(this,[D],function*({previousUser:_,currentUser:E}){if(!E&&_){let B=_?.stsTokenManager?.expirationTime,G=new Date().getTime(),X=B-G;G>B&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&_?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Z.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:X,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"))))}}),_=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",_)}),this.getUser$().pipe(Kt(_o)).subscribe(_=>{let E=aS(_);this.coreActionsService.triggerAction(gd.USER_UPDATE,E)})}catch(_){this.loggingService.catch("Error in AuthService constructor: ",_)}}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||Wn(this.afAuth).pipe(Je(1)).subscribe(r=>ee(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ad(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(Z.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 ee(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=ov(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let h=yield ad(c,!0).catch(D=>null);if(!h)return;let{user:_,firebaseConfig:E}=h.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==_?.groupId||e?.organizationId!==_?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.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 D=yield ad(c,!0).catch(he=>null);if(!D)return;let{firebaseConfig:B,user:G,advancedQueries:X}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(X),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(Z.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(Z.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);let h=Cr(this.functions,Zn.cloudFunction.validateClient,{timeout:20*60*1e3}),_=Ta(),E=(yield h({apiKey:this.apiKey,user:e,version:_,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.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.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let D={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(gd.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(gd.ERROR,D),this.analyticsService.trackEvent(Z.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)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Z.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),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 D=yield ad(this.afAuth.currentUser,!0).catch(X=>null);if(!D)return;let{user:B,advancedQueries:G}=D.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.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(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=Ta();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(U.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({},Zn.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(U.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 Dn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Ln(()=>re(!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;"),Wn(this.afAuth).pipe(ge(e=>e?this.user$.asObservable():re(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 gQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(Z.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(Z.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 wo;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return ee(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(fn(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 ee(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 ee(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Cr(this.functions,Zn.cloudFunction.getPlanDetails,{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.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(Ne(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(ge(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return ee(this,null,function*(){try{yield this.analyticsService.trackEvent(Z.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 Wn(this.afAuth).pipe(Je(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),uQ(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 Xi(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 aS(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J($t),J(gm),J(Np),J(Fe),J(Vo),J(Qe),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xd=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=ud(i)),r&&(this.organizationId=hd(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}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}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=ud(i)),r&&(this.organizationId=hd(r)),a&&(this.folderId=a,this.veltFolderId=hl(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}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}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 pn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new fe(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Df(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)(J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vs=(()=>{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 fe(null),this.commentAnnotationById$=new fe({}),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 ee(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((c,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(),c({});let _={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.commentAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return ee(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 sc(()=>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(Z.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 ee(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 c=yield sc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Ha.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.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()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var um=(()=>{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 fe(null),this.reactionAnnotationById$=new fe({}),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 ee(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((c,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(),c({});let _={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.reactionAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return ee(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:Ha.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield sc(()=>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(Z.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 ee(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 c=yield sc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Ha.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.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()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new fe(null),this.documentIds$=new fe([]),this.folderConfig$=new fe(null),this.organizationConfig$=new fe(null),this.firestorePaths$=new fe(null),this.location$=new fe(null),this.excludedLocationIds$=new fe([]),this.organizationMetadata$=new fe(null),this.documentMetadata$=new fe(null),this.locationMetadata$=new fe(null),this.customerMetadata$=new fe(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new fe({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new fe({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new et,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(jr(this.DEBOUNCE_TIME)).subscribe({next:_=>{try{this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.auto,_.avoidAnalytics,_.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:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let E=qO(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>{_?(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.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&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.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),_?.organizationId&&_?.clientOrganizationId&&this.organizationConfig$.next({organizationId:_?.organizationId,clientOrganizationId:_?.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(_=>{let E={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId};_?.organizationId&&(E.organizationId=_.organizationId,E.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(_=>{this.analyticsService.updateDefaultProperties({folderId:_?.folderId,veltFolderId:_?.veltFolderId,allDocuments:_?.allDocuments})}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(_=>{_&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(_=>!!_),Je(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}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=qO(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=qO(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(Z.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(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!Co(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,c=`${fn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,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(Z.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 c=Date.now(),p=c-this.lastSetDocumentIdCallTime,h=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,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=c;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})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){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?hl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${fn(e)}`,_=c?.organizationId?i?Rt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),_&&this.documentPaths$.value?.organizationId&&_!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==_){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,D=new IM;E.clientDocumentId=e,D.clientDocumentId=e,E.documentId=h,D.documentId=h,_&&(E.organizationId=_,E.clientOrganizationId=i??c?.clientOrganizationId,D.organizationId=_,D.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;_&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),D.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,D.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,D.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,D.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,D.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,D.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,D.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,D.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,D.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,D.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,D.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,_&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),D.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,D.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,D.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,D.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(D),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(Z.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(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(Z.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 ee(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,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let _=[];for(let D=0;D<e.length;D+=20)_.push(e.slice(D,D+20));_.forEach(D=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=D.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let h={};c.length>0&&Promise.all(c).then(_=>{_?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(h[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(_=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",_)})}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=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(_=>{_?.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(Ln(i=>re(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`${fn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Rt(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=Xo(e),r=fn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(Z.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(Z.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),re([])}}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 ee(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 ee(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=>ee(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=_i();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(c){let _=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});_?.clientDocumentId?_?.folderId&&(_?.folderId!==c?.folderId||_?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):_?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(h){let _={};Object.entries(s).forEach(([E,D])=>{_[E]=D}),Co(_,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 ee(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"}}),c=new mM;c.locationId=i?.locationId,c.veltLocationId=uV(i?.location?.id??""),c.location=i?.location,c.pageInfo=_i(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),h=T(I({},c),{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:c.veltLocationId}});let _=this.locationMetadata$.value;if(_||(_={}),i?.location?.id){let E=_?.[a.documentId],D=E?.[i?.location?.id??""];_&&(E||(_[a.documentId]={}),D||(_[a.documentId][i?.location?.id??""]={}),_[a.documentId][i?.location?.id??""]=T(I({},D),{location:i?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?fn(JSON.stringify(Xo(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),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(Z.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(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);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),re({})}}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(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.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(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.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 c=e?.[s.documentId];c&&(i[s.documentId]=c)});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,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,h=c?.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),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}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 ee(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=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("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 ee(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=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("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 ee(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=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=ud(p.documentId),_=c?.[h];_&&(c[h]=I(I({},_),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:hd(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return ee(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(_=>_.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 c=s.map(_=>ud(_)),p=[],h=this.locationMetadata$.value;h||(h={}),c.forEach(_=>{a.forEach(E=>{let D=this.location$.value;if(E?.id===D?.location?.id&&this.location$.next({locationId:D?.locationId,location:E}),E?.id){delete E?.metadata;let B=uV(E.id),G=h?.[_],X=G?.[E.id];h&&(G||(h[_]={}),X||(h[_][E.id]={}),h[_][E.id]=T(I({},X),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:hd(r),documentId:_,id:B}}))}})}),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 ee(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 c=hl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[mt("metadata.veltParentFolderId","==",c)],folderId:c,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(ge(e=>e?this.documentPaths$.pipe(ge(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),Kt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?di.RESTRICTED:di.PUBLIC:e&&e.documentAccessType?e.documentAccessType:di.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),di.PUBLIC}}changeDocumentAccessType(e){return ee(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 di.PUBLIC:r.features.all.restricted=!1;break;case di.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||this.configService?.getApiKey()||""}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)(J(Qe),J(je),J(pn),J(Fe),J($t),J(y),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hn=(()=>{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=>ee(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new ln,this.userDataProvider$=new fe(null),this.userById$=new fe({}),this.userByIdCalled$=new fe({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);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 ee(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(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let h,_=new Promise((E,D)=>{h=setTimeout(()=>{D(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(h)}),_]),this.analyticsService.trackEvent(Z.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,_])=>{_&&(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(In(e=>ee(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return ee(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),re({})}}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)(J(Qe),J(je),J(lt),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ase=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fp=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 pt.error("Error in isTestingDb:",t),!1}}};var Lp=(()=>{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 fe(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 ee(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 sc(()=>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(Z.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 ee(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 sc(()=>a?.delete({attachmentId:e,metadata:i,event:Ha.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(Z.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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Uv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[jt.NEWLY_ADDED]:Ha.COMMENT_ANNOTATION_ADD,[jt.ADDED]:Ha.COMMENT_ADD,[jt.UPDATED]:Ha.COMMENT_UPDATE,[jt.DELETED]:Ha.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,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(im(`{{${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 c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let h=p?.attachmentId;c?.[h]&&(p.name=c?.[h]?.name,p.url=c?.[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?!Co(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={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:sv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let D;r&&(D={},E.attachments?.forEach(B=>{D[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),D&&{attachments:D})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let _=new ko;Object.assign(_,e),_.comments=e.comments?.map(E=>{let D=new pc;if(Object.assign(D,E),D.isCommentResolverUsed=!0,r){let B=D.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));D.attachments=B}return delete D?.commentHtml,delete D?.commentText,D})||[],c=_}return{strippedData:s,originalData:c,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(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(im(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 ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=$O(this.authService.getFirebaseConfig()?.firebaseOptions),p=Cr(this.functions,Zn.cloudFunction?.[c]?.setEncryptedData,{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let D=r?.targetAnnotationData?.commentId;if(D){let B=e?.comments?.find(G=>G?.commentId===D);B&&(r.targetAnnotationData=B)}}let h=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Zn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:Ta()},E=yield bp(_,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(vs),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var cse=(()=>{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)(J(y),J(Hn))},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 ee(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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var pse=(()=>{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)(J(y),J(Hn))},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){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 ee(this,null,function*(){try{return yield bp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y),J(Hn))},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,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}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 c of s)i.add(c)}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 ee(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 bp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(J(Uv),J(jv),J(y),J(Hn),J(je),J(vs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var use=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hse=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}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 ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=$O(this.authService.getFirebaseConfig()?.firebaseOptions),c=Cr(this.functions,Zn.cloudFunction?.[s]?.setEncryptedData,{timeout:20*60*1e3}),p=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",_={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:Ta()},E=yield bp(_,h);yield c({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?!Co(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:sv(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)(J(y),J(Hn),J(je),J(Vo),J($t),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $v=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=_,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=X,this.tagUtilsService=he,this.usersService=Ie,this.docService=Me,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=We}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){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}/${U.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}/${U.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 U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.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:c,organizationId:p}=i;p||(p=r?.organizationId);let h=new xd({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){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}/${U.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(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return ee(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(c){return ee(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(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}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,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,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}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(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 c=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,c);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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return ee(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}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 ee(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 ee(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let _={comment:"allComments",reaction:"allReactions"}[e];if(!_)return null;let E=i?.metadata?.documentId,D=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(_)&&(!E||B.includes(E)||D&&B.includes(D))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return ee(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(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return ee(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)(J(ase),J(sse),J(Uv),J(lse),J(cse),J(xM),J(dse),J(y),J(pse),J(TM),J(use),J(hse),J(jv),J(fse),J(vse),J(Hn),J(lt),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new fe(null);try{Dn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),Je(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(Q6(Fp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||Q6("DocumentIdDb");if(e){let i=kS(e,"generateDocumentId");return kv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(J($t),J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=_,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(D=>{if(D){this.db=D;let B=on(D,".info/serverTimeOffset");this.offsetListener=gu(B,G=>{let X=G.val();this.offset=X})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}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){Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),Je(1),In(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return ee(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(_=>ee(this,[_],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 D=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 B,G;try{D&&(B=on(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(G=kv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!h})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){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=>ee(this,null,function*(){if(h.dbRef){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Of(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_)}}catch(_){this.loggingService.catch(`Error in setData for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){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=>ee(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield jA(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_,{merge:!0})}}catch(_){this.loggingService.catch(`Error in updateDoc for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return ee(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,c=>ee(this,null,function*(){c.dbRef&&(yield VA(c.dbRef));try{if(c.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:c.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:c.firestorePath??"",eventType:"DELETE"}))}else yield Lae(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}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=xn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),xn()||"noDocumentId"}}queryData(r){return ee(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 ee(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=kS(this.firestore,r);i?.useCollectionGroup&&(a=Kj(this.firestore,r));let s=i?.firestoreQuery??[],c=Xj(a,...s);if(i?.getCount){let p=yield Vae(c).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield jae(c).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 ee(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=on(this.db,r),s=i?.rtdbQuery??[],c=xL(a,...s),p=yield bL(c).catch(_=>(this.loggingService.catch(`Error in get for ${e}`,_),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 ee(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 c=yield Uae(kv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}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 c=yield bL(on(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}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 Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ge(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new fe({}),count:0};let _=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=_}return new Ft(h=>{let _=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{_?.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 re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Ig(()=>{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 Ft(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ge(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ge(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ge(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),Kt(_o)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=kS(e,i);if(s?.useCollectionGroup&&(p=Kj(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=Xj(p,...E)}let h=!0,_=[];return Zj(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(X=>{["allComments","allReactions"].includes(r)&&!h&&X.type!=="removed"&&_.push(X.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:X,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(D,this.handleCollectionChange(X,D)),X.type==="removed"&&(B||(B={type:X.type,ids:[]}),B.ids.push(X.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&_?.length&&(this.commonDbUtilsService.resolveAnnotations({data:_,feature:r}),_=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:B})),h=!1}catch(D){this.handleListenerError(D,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 c=kv(e,i);return Zj(c,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}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=xL(s,...c)}return Af(s).pipe(Ln(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((h,[_,E])=>(h[_]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(c,i))),ge(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ge(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(J(je),J($v),J(y),J(Cse),J(pn),J($t),J(lt),J(Hn),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=h,this.db=Ci(),this.internalUserContacts$=new fe([]),this.userGlobalContact$=new fe(!1),this.userGroupContact$=new fe(null),this.users$=new fe([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new fe([]),this.userFolderContacts$=new fe([]),this.userDocumentContacts$=new fe([]),this.userOrganizationGroups$=new fe([]),this.onContactSelectedSubject$=new et,this.documentAccessType=null,this.atHereEnabled$=new fe(!1),this.atHereLabel$=new fe("here"),this.atHereDescription$=new fe(null),this.contactListScopeForOrganizationUsers$=new fe([xi.ALL]),this.customUserContacts$=new fe(null),this.customUserContactsConfig$=new fe({merge:!1}),this.currentOrganizationUserIAM$=new fe(null),this.userContacts$=new fe([]),this.userSnippylyIdContacts$=new fe(null),this.usersByOrganizationId$=new fe({}),this.usersByOrganizationIdAndDocumentId$=new fe({}),this.usersByOrganizationIdAndFolderId$=new fe({}),this.userById$=new fe({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ge(_=>this.docService.getDocumentPaths$().pipe(In(E=>{this.documentPaths=E}),ce(()=>_)))).subscribe(_=>ee(this,null,function*(){this.user=_,_&&this.documentPaths?_?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getLoggedInUsersSubscription?.unsubscribe(),this.getOrganizationContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription?.unsubscribe())}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),Dn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,E,D])=>{E?D?.merge?this.userContacts$.next([..._||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(E=>{let D=E?.userSnippylyId||ov(this.configService.getApiKey(),E.userId);D&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[D]: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 ee(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:Rt(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:Rt(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:Rt(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 ee(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:Rt(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 c=r.contacts[s];if(c?.userId){let p=Rt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(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:Rt(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:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new wo;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:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return ee(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:Rt(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:Rt(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:Rt(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(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Rt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(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:Rt(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:Rt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return ee(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=>ee(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Rt(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:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return ee(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(Je(1)).subscribe(i=>ee(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===di.PUBLIC)r=!0;else if(a===di.RESTRICTED){let s=Rt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Rt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new Rp;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=>ee(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:Rt(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:Rt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return ee(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?Dn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,h,_,E,D])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let X=We=>D.some(ke=>We.includes(ke)),he=X([xi.ALL,xi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ie=a?X([xi.ALL,xi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Me=X([xi.ALL,xi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...he,...Ie||[],...Me].forEach(We=>{let ke=h?.[We];ke&&(B[We]=ke)}),_){let{merge:We,options:ke}=E||{},{organizationId:we,documentId:Ee,folderId:Pe}=ke||{},Ce=Pe?hl(Pe):void 0;(!we||we===i)&&(!Ee||Ee===r)&&(!Ce||Ce===a)&&(We||(B={}),_.forEach(ue=>{ue?.userId&&(B[ue.userId]=ue)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),In(i=>{this.documentPaths=i}),ce(()=>e))),ge(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();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),In(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),In(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:Rt(e?.userId)}}).pipe(ce(r=>r?.data),In(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),io(...i).pipe(oo(this.authService.getUser$().pipe(Ne(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(ge(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),In(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).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(ge(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(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(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)})):re():re()}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),In(r=>{this.documentPaths=r}),ce(()=>i))),ge(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ge(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),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)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",s?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let _=0;_<a.length;_+=U.LISTENER_BATCH_SIZE)h.push(a.slice(_,_+U.LISTENER_BATCH_SIZE));c=Dn(h.map(_=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",_),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[mt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(_=>ca(_)?.data))}return c.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let _=Object.values(h??{});this.setUserDocumentContacts(_)}else this.setUserDocumentContacts([])}))})):re():re())),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).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(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(xi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.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(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{if(this.setUserOrganizationGroups([]),!i)return re();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([])})):re()})):(this.setUserOrganizationGroups([]),re()))).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 di.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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 ee(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.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(ge(e=>e?Dn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(_=>this.convertToClientUser(_)),p.folderUsers=r?.map(_=>this.convertToClientUser(_)),p.documentUsers=a?.map(_=>this.convertToClientUser(_)),p.updatedContactList=c?.map(_=>this.convertToClientUser(_));let h=[];return s?.forEach(_=>{let E=this.convertToClientUserGroup(_,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),Kt(_o)):re(null)),Ln(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(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 c=Rt(s.userId);a[c]=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)(J(Qe),J(je),J($t),J(pn),J(lt),J(y),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _se=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){pt.catch("Error in File utils getFileName: ",o);return}},p$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){pt.catch("Error in File utils getFileExtension: ",o);return}},yse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+p$(n),{type:n.type})}catch(t){pt.catch("Error in File utils updateFile: ",t);return}},Sse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),bse={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 Bp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ty();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ty(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 Nv;r.name=i.name;let a=yse(i,`${r.attachmentId}_${_se(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=p$(i),r?.type&&(r.mimeType=bse[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=wy(this.storage,e.bucketPath),c=QL(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{XL(c.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(c){return ee(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:Ha.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,c)=>{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:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=wy(this.storage,c),h=QL(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",_=>{let E=_.bytesTransferred/_.totalBytes*100},_=>{s(_)},()=>{XL(h.snapshot.ref).then(_=>{a(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,_),s(_)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}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(U.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 c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),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(c=>{s(c)});else{let c=wy(this.storage,e.bucketPath);ZL(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=wy(this.storage,e);ZL(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(J(je),J($t),J(y),J(Lp))},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,s,c,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new fe(null),this.workspaceIAM$=new fe(null),this.roles$=new fe([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_,this.getUser(),this.getDocumentPaths())},_=>{this.loggingService.catch("Error in CommentService getDb subscription: ",_)}),this.getRole$().pipe(Je(1)).subscribe(_=>{this.authService?.getUser()&&!_&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(_=>{_?.accessType&&this.contactService.setDocumentAccessType(_.accessType)})}catch(_){this.loggingService.catch("Error in IamService constructor: ",_)}}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(Ne(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(Ne(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(Ln(e=>re(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),Kt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ge(e=>this.getRole$().pipe(ce(i=>(i===mo.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(ge(()=>this.documentIAM$.pipe(Ne(i=>!!i),ge(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ge(()=>this.configService.getSF$()),ge(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ge(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ge(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return mo.ADMIN;if(!e&&this.user?.isAdmin)return mo.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?di.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||di.PUBLIC:null){case di.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||mo.COMMENTER;break;case di.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===mo.ADMIN),Kt())}isUserAdmin(){try{return this.getRole()===mo.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?.[Rt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Rt(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?.[Rt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(gi),J(pn),J(lt),J($t),J(y),J(bn))},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,c,p,h,_,E,D,B,G,X,he,Ie){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=_,this.docService=E,this.domService=D,this.iamService=B,this.loggingService=G,this.notificationUtilsService=X,this.usersService=he,this.functions=Ie,this.db=Ci(),this.notificationsDb=Ci(void 0,Zn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new fe([]),this.rawNotificationsByIdMap$=new fe(new Map),this.processedNotifications$=new fe([]),this.readNotificationsOnForYouTab$=new fe(!1),this.notificationViews$=new fe({}),this.notificationsByIdMap$=new fe(new Map),this.historyPanelVisible$=new fe(!1),this.notificationsForYou$=new fe(null),this.notificationsByDocumentIdMap$=new fe(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new fe(null),this.maxNotificationDays$=new fe(15),this.tabConfig$=new fe({people:{enable:!1}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Me=>!!Me),Je(1)).subscribe(Me=>{Me&&(this.db=Me,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Me=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Me)}),this.authService.getUser$().subscribe(Me=>{Me?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Me=>{if(Me){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Me||{}).forEach(We=>{let ke=Le?.[We]?.notifications;ke?.length&&ke.forEach(we=>{this.notificationUtilsService.mergeLocationWithNotification({notification:we},Me)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(Me){this.loggingService.catch("Error in NotificationService constructor: ",Me)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}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(Vi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),c=a?.map(h=>({documentId:h,timestamp:i?.find(_=>_.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let _=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:_}}).filter(h=>{let _=e?.find(E=>E.documentId===h.documentId)?.timestamp;return _&&h.timestamp&&_!==h.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),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(ge(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new xd({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ge(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Fi(mt("timestamp",">=",p)),Ga("timestamp","desc"),Rv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let _=[];return Object.keys(h||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],B=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===D){let G=B.id,X=h[E]?.metadata?.documentId,he=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=he?.[X]??{documentMetadata:null,notifications:[]},Me=Ie.notifications??[],Le=Me?.findIndex(We=>We.notificationId===G);Le!==-1&&(Me.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},he),{[X]:T(I({},Ie),{notifications:Me})})))}else _.push({documentId:E,timestamp:D})}),_}),Ln(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return ee(this,null,function*(){try{if(e?.length){let r=Cr(this.functions,Zn.cloudFunction.getNotificationsForDocuments,{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),_=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Pie(_,E);if(D&&typeof D=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),X=[],he=[];Object.keys(D).forEach((Ie,Me)=>{let Le=D[Ie].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ie]||!Co(ke?.[Ie],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ie]:Le}))}let We=D[Ie].notifications||[];We.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ie,Le,We),B&&X.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldAwait:!0,forceResolve:!0})),G&&he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(X).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[Ie]?.notifications||[]});Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})}),G&&Promise.all(he).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=D?.[Ie]?.notifications?.reduce((We,ke)=>(We[ke.notificationId]=ke,We),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],_=this.docService.getLocationMetadatas(),E=r?.map(G=>{let X=G.notification;return X.metadata&&(X.metadata.documentName=i?.documentName||X.metadata.documentName,X.metadata.organizationMetadata=c||X.metadata.organizationMetadata,X.metadata.documentMetadata=i||X.metadata.documentMetadata),_&&(X=this.notificationUtilsService.mergeLocationWithNotification({notification:X},_)?.notification),X})?.filter(G=>!!G)||[],D=new Map(h.map(G=>[G.id,G]));E.forEach(G=>{D.set(G.id,G)});let B=Array.from(D.values()).sort((G,X)=>(X.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,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})),ge(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ge(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[EL("timestamp"),TL(h),IL(i)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",a.userId),Rv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ge(_=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:_,operation:null}})),ce(_=>_?.data??[]),ce(_=>(_.sort((E,D)=>D.timestamp-E.timestamp),_)),Ln(_=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",_),re([]))),ce(_=>(_.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),_)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}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(ge(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ge(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ge(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Rt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[EL("timestamp"),TL(h),IL(50)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",r.userId),Rv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ge(_=>_?.data?re(_).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),D.sort((G,X)=>X.timestamp-G.timestamp),D.map(G=>G.notification).filter(G=>!!G)}),ge(E=>{let D={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ge(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ge(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([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=fn(e)),i&&typeof i=="object"){let s=Xo(i);r=fn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return Wn(this.afAuth).pipe(Ne(s=>!!s),ge(s=>this.isFeatureAllowed({firebaseUser:s})),ge(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ge(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(),re([])):re(s).pipe(ge(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ge(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(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+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Af(a).pipe(Ln(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(_=>{let E=s?.raw[_];E?.id&&c.push(E)}),c.forEach(_=>{_.id&&p.set(_.id,_)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(_=>{let E=s?.processed[_];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Rt(e?.email));let a;e?.userId&&(a=Rt(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 _={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(_.id);if(E?.metadata&&(_.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}),_?.notificationSource==="comment"&&_?.targetAnnotationId){let D=this.commentService?.getAnnotationById(_.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(_.notificationSourceData=$n(D))}s.set(p.id,_)}}),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 c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let h=null;c?.email&&(h=Rt(c?.email));let _=null;c?.userId&&(_=Rt(c?.userId));let E=!1,D=!0;(h&&p.notifyUsers?.[h]||_&&p.notifyUsersByUserId?.[_])&&(E=!0),_&&a?.[_]&&(D=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):B={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:D,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=$n(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);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(c=>c.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 xd({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 c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.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=on(this.notificationsDb),r=this.processNotificationData(e);RA(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(ge(e=>e?e.organizationId?this.getAllNotifications$().pipe(ge(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,c)=>(c.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)),Eg()):re(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,c=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(c)}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(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.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(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let c=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(c)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let c=r?.[s]?.notifications||[],p=c.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(Je(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),ge(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),re({forYou:null,all:null})}}setNotificationAsRead(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Rt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,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:c,documentId:p,apiKey:s},data:h})));let _=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});_?.notificationId&&(this.getReadNotificationsOnForYouTab()?_?.views?.[r]||(_.views||(_.views={}),_.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:_})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}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 ee(this,null,function*(){try{this.getAllNotifications$().pipe(Je(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}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(bn),J($v),J(Uv),J(vs),J(pn),J(lt),J(Fe),J(gn),J(y),J(TM),J(Hn),J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $o=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new fe(U.CommentAnnotationStatusMap),this._customPriorityMap=new fe(U.CommentAnnotationPriorityMap),this._customCategoryMap=new fe(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.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(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.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(U.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(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.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(U.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(U.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 U.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 U.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[U.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(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,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=U.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=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hc=(()=>{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
|
+
`+wr),_c&&_M([Be,Se,Ut],Is=>{wr=jS(wr,Is," ")}),Le&&ag?Le.createHTML(wr):wr},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rm(Yt),rg=!0},o.clearConfig=function(){km=null,rg=!1},o.isValidAttribute=function(Yt,Ve,yt){km||Rm({});let Wt=uo(Yt),to=uo(Ve);return e_(Wt,to,yt)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&US(ue[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let yt=_Pe(ue[Yt],Ve);return yt===-1?void 0:yPe(ue[Yt],yt,1)[0]}return Wae(ue[Yt])},o.removeHooks=function(Yt){ue[Yt]=[]},o.removeAllHooks=function(){ue=Jae()},o}var s$=ose();var rse={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{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 fe(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new fe([]),this.mousedown=!1,this.windowMouseDown$=new et,this.windowPointerMove$=new fe(null),this.windowPointerUp$=new fe(null),this.documentSelectionChange$=new fe(null),this.windowClick$=new fe(null),this.windowScroll$=new fe(null),this.windowResize$=new fe(null),this.windowKeyupBackspace$=new fe(null),this.windowKeyupDelete$=new fe(null),this.windowKeyupEsc$=new fe(null),this.windowPopState$=new fe(null),this.documentClick$=new fe(null),this.documentClickSubject$=new et,this.documentFocus$=new fe(null),this.windowKeydownShift$=new fe(null),this.windowKeyupShift$=new fe(null),this.mutation$=new fe(null),this.childListMutation$=new fe(null),this.networkStatus$=new fe(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new fe({}),this.selectedAnnotationsLocationMap$=new fe({}),this.recordingInProgress$=new fe({}),this.deleteAnnotations$=new fe([]),this.pinHighlighterClass$=new fe(null),this.dialogOpenedInSidebar$=new fe(!1),this.textHighlighterClass$=new fe(null),this.commentPinHighlighter$=new fe(!1),this.deviceInfo$=new fe(new Jn),this.customCss$=new fe(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(c=>{if(!ji(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(h=>{ji(h)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),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 fe(a),this.currentMousePosition$=new fe(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Vi(),In(([s,c])=>{try{let p=c.filter(_=>!s.includes(_)),h=s.filter(_=>!c.includes(_));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",D=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}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?Hie("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):zie("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===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let h=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let _=this.xpathCacheId.get(h);_!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(_))}}}),ji(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=>!ji(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(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(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{io(oi(window,"offline").pipe(ce(()=>!1)),oi(window,"online").pipe(ce(()=>!0)),new Ft(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 Jn),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()!==U.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 oi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),_g}}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 _=this.getXPath(i);_&&(r=_.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),h=c*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 c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,h=c?.touches?.length?c.touches[0]?.clientY:c.clientY,_=this.getBackgroundElement(p,h,i,r);if(_&&s&&typeof s=="function"&&(_=s(_)),_){let E=this.getXPath(_),D=this.getXPath(_,!0),B=_.getBoundingClientRect(),G=p-B.x,X=h-B.y,he=G*100/(B.width||1),Ie=X*100/(B.height||1),Me={xpath:E,fXpath:D,leftPercentage:he,topPercentage:Ie};if(a){let Le=this.getXPath(_,!0,!0);Me.cfXpath=Le}return Me}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(h=>{ji(h)?c=[]:xo(h)&&c.push(h)}),a&&(c=c.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||c?.forEach((h,_)=>{h.tagName.toLowerCase()==="svg"&&(p=_)}),c[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=>{ji(s)&&xo(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,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.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 c=s.split("/"),p=!1;c.forEach((h,_)=>{h.includes("svg")&&(p=!0),p&&(c[_]="svg:"+h)}),s=c.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 c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(_=>_.nodeType===1&&_.tagName===e.tagName?_.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(h.length>1){let _=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${_}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.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=xn();a.setAttribute(U.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 NS;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 NS}}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(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(_=>_.classList.contains("velt-annotation-draft-checked")?(_.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(_,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(_,"velt-comment-dialog-shake"),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||_.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(_,"velt-annotation-draft-checked")},100),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(_=>_),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let _=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||_.push(D)}else p[E]?.comments?.length||s.includes(E)||_.push(p[E])}),this.deleteAnnotations$.next(_),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(_=>{if(s.includes(_)&&(h[_]=p[_]),i)switch(i){case"comment":["comment","videoPin"].includes(p[_]?.type)||(h[_]=p[_]);break;default:p[_]?.type!==i&&(h[_]=p[_]);break}}),Object.keys(h).forEach(_=>{let E=h[_]?.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(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.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||{})),c=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,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}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),re([])}}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),re([])}}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 c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),_=a.getBoundingClientRect();r.offsetLeft+=_.left-h.left,r.offsetTop+=_.top-h.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 Ft(e=>{let i=oi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=oi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=oi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ge(p=>r.pipe(Vi(),ce(([h,_])=>({startPoint:p,prevPoint:h,curPoint:_})),oo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=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=`${c}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 c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Au(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(U.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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.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 c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let h=c[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),re(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(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.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;"),s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return s$.sanitize(e,rse)}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 Jn;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),re(new Jn)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=xn(),sessionStorage.setItem(U.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 Jn}}isMobileDevice(){try{return new Jn().getDeviceType()===Zo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Jn().getDeviceType()===Zo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Jn().getDeviceType()===Zo.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(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Jn().getDeviceType()===Zo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(J(qo),J(y),J(Ms))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=h,this.user$=new fe(null),this.userOptions$=new fe(null),this.userContacts$=new fe(null),this.userOrganization$=new fe(null),this.providedUser=new wo,this.firebaseConfig$=new fe(null),this.advancedQueries$=new fe(null),this.planDetails$=new fe(null),this.signOutPreviousUser$=new fe(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(_=>{this.config=_}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Wn(this.afAuth).pipe(Go(this.afAuth.currentUser),Vi(),ge(([_,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(D=>D),Je(1),ce(()=>({previousUser:_,currentUser:E}))))).subscribe(D=>ee(this,[D],function*({previousUser:_,currentUser:E}){if(!E&&_){let B=_?.stsTokenManager?.expirationTime,G=new Date().getTime(),X=B-G;G>B&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&_?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Z.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:X,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"))))}}),_=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",_)}),this.getUser$().pipe(Kt(_o)).subscribe(_=>{let E=aS(_);this.coreActionsService.triggerAction(gd.USER_UPDATE,E)})}catch(_){this.loggingService.catch("Error in AuthService constructor: ",_)}}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||Wn(this.afAuth).pipe(Je(1)).subscribe(r=>ee(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ad(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(Z.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 ee(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=ov(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let h=yield ad(c,!0).catch(D=>null);if(!h)return;let{user:_,firebaseConfig:E}=h.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==_?.groupId||e?.organizationId!==_?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.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 D=yield ad(c,!0).catch(he=>null);if(!D)return;let{firebaseConfig:B,user:G,advancedQueries:X}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(X),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(Z.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(Z.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);let h=Cr(this.functions,Zn.cloudFunction.validateClient,{timeout:20*60*1e3}),_=Ta(),E=(yield h({apiKey:this.apiKey,user:e,version:_,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.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.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let D={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(gd.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(gd.ERROR,D),this.analyticsService.trackEvent(Z.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)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Z.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),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 D=yield ad(this.afAuth.currentUser,!0).catch(X=>null);if(!D)return;let{user:B,advancedQueries:G}=D.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.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(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=Ta();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(U.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({},Zn.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(U.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 Dn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Ln(()=>re(!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;"),Wn(this.afAuth).pipe(ge(e=>e?this.user$.asObservable():re(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 gQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(Z.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(Z.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 wo;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return ee(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(fn(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 ee(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 ee(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Cr(this.functions,Zn.cloudFunction.getPlanDetails,{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.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(Ne(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(ge(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return ee(this,null,function*(){try{yield this.analyticsService.trackEvent(Z.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 Wn(this.afAuth).pipe(Je(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),uQ(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 Xi(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 aS(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J($t),J(gm),J(Np),J(Fe),J(Vo),J(Qe),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xd=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=ud(i)),r&&(this.organizationId=hd(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}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}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=ud(i)),r&&(this.organizationId=hd(r)),a&&(this.folderId=a,this.veltFolderId=hl(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}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}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 pn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new fe(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Df(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)(J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vs=(()=>{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 fe(null),this.commentAnnotationById$=new fe({}),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 ee(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((c,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(),c({});let _={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.commentAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return ee(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 sc(()=>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(Z.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 ee(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 c=yield sc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Ha.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.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()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var um=(()=>{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 fe(null),this.reactionAnnotationById$=new fe({}),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 ee(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((c,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(),c({});let _={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.reactionAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return ee(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:Ha.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield sc(()=>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(Z.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 ee(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 c=yield sc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Ha.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.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()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new fe(null),this.documentIds$=new fe([]),this.folderConfig$=new fe(null),this.organizationConfig$=new fe(null),this.firestorePaths$=new fe(null),this.location$=new fe(null),this.excludedLocationIds$=new fe([]),this.organizationMetadata$=new fe(null),this.documentMetadata$=new fe(null),this.locationMetadata$=new fe(null),this.customerMetadata$=new fe(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new fe({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new fe({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new et,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(jr(this.DEBOUNCE_TIME)).subscribe({next:_=>{try{this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.auto,_.avoidAnalytics,_.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:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let E=qO(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>{_?(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.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&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.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),_?.organizationId&&_?.clientOrganizationId&&this.organizationConfig$.next({organizationId:_?.organizationId,clientOrganizationId:_?.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(_=>{let E={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId};_?.organizationId&&(E.organizationId=_.organizationId,E.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(_=>{this.analyticsService.updateDefaultProperties({folderId:_?.folderId,veltFolderId:_?.veltFolderId,allDocuments:_?.allDocuments})}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(_=>{_&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(_=>!!_),Je(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}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=qO(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=qO(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(Z.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(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!Co(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,c=`${fn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,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(Z.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 c=Date.now(),p=c-this.lastSetDocumentIdCallTime,h=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,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=c;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})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){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?hl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${fn(e)}`,_=c?.organizationId?i?Rt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),_&&this.documentPaths$.value?.organizationId&&_!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==_){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,D=new IM;E.clientDocumentId=e,D.clientDocumentId=e,E.documentId=h,D.documentId=h,_&&(E.organizationId=_,E.clientOrganizationId=i??c?.clientOrganizationId,D.organizationId=_,D.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;_&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),D.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,D.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,D.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,D.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,D.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,D.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,D.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,D.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,D.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,D.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,D.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,_&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),D.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,D.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,D.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,D.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(D),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(Z.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(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(Z.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 ee(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,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let _=[];for(let D=0;D<e.length;D+=20)_.push(e.slice(D,D+20));_.forEach(D=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=D.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let h={};c.length>0&&Promise.all(c).then(_=>{_?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(h[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(_=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",_)})}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=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(_=>{_?.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(Ln(i=>re(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`${fn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Rt(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=Xo(e),r=fn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(Z.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(Z.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),re([])}}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 ee(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 ee(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=>ee(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=_i();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(c){let _=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});_?.clientDocumentId?_?.folderId&&(_?.folderId!==c?.folderId||_?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):_?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(h){let _={};Object.entries(s).forEach(([E,D])=>{_[E]=D}),Co(_,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 ee(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"}}),c=new mM;c.locationId=i?.locationId,c.veltLocationId=uV(i?.location?.id??""),c.location=i?.location,c.pageInfo=_i(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),h=T(I({},c),{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:c.veltLocationId}});let _=this.locationMetadata$.value;if(_||(_={}),i?.location?.id){let E=_?.[a.documentId],D=E?.[i?.location?.id??""];_&&(E||(_[a.documentId]={}),D||(_[a.documentId][i?.location?.id??""]={}),_[a.documentId][i?.location?.id??""]=T(I({},D),{location:i?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?fn(JSON.stringify(Xo(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),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(Z.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(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);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),re({})}}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(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),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(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.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(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.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 c=e?.[s.documentId];c&&(i[s.documentId]=c)});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,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,h=c?.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),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}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 ee(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=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("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 ee(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=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("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 ee(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=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=ud(p.documentId),_=c?.[h];_&&(c[h]=I(I({},_),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:hd(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return ee(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(_=>_.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 c=s.map(_=>ud(_)),p=[],h=this.locationMetadata$.value;h||(h={}),c.forEach(_=>{a.forEach(E=>{let D=this.location$.value;if(E?.id===D?.location?.id&&this.location$.next({locationId:D?.locationId,location:E}),E?.id){delete E?.metadata;let B=uV(E.id),G=h?.[_],X=G?.[E.id];h&&(G||(h[_]={}),X||(h[_][E.id]={}),h[_][E.id]=T(I({},X),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:hd(r),documentId:_,id:B}}))}})}),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 ee(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 c=hl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[mt("metadata.veltParentFolderId","==",c)],folderId:c,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(ge(e=>e?this.documentPaths$.pipe(ge(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),Kt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?di.RESTRICTED:di.PUBLIC:e&&e.documentAccessType?e.documentAccessType:di.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),di.PUBLIC}}changeDocumentAccessType(e){return ee(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 di.PUBLIC:r.features.all.restricted=!1;break;case di.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||this.configService?.getApiKey()||""}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)(J(Qe),J(je),J(pn),J(Fe),J($t),J(y),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hn=(()=>{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=>ee(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new ln,this.userDataProvider$=new fe(null),this.userById$=new fe({}),this.userByIdCalled$=new fe({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);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 ee(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(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let h,_=new Promise((E,D)=>{h=setTimeout(()=>{D(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(h)}),_]),this.analyticsService.trackEvent(Z.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,_])=>{_&&(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(In(e=>ee(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return ee(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),re({})}}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)(J(Qe),J(je),J(lt),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ase=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fp=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 pt.error("Error in isTestingDb:",t),!1}}};var Lp=(()=>{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 fe(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 ee(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 sc(()=>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(Z.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 ee(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 sc(()=>a?.delete({attachmentId:e,metadata:i,event:Ha.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(Z.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)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Uv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[jt.NEWLY_ADDED]:Ha.COMMENT_ANNOTATION_ADD,[jt.ADDED]:Ha.COMMENT_ADD,[jt.UPDATED]:Ha.COMMENT_UPDATE,[jt.DELETED]:Ha.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,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(im(`{{${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 c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let h=p?.attachmentId;c?.[h]&&(p.name=c?.[h]?.name,p.url=c?.[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?!Co(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={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:sv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let D;r&&(D={},E.attachments?.forEach(B=>{D[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),D&&{attachments:D})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let _=new ko;Object.assign(_,e),_.comments=e.comments?.map(E=>{let D=new pc;if(Object.assign(D,E),D.isCommentResolverUsed=!0,r){let B=D.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));D.attachments=B}return delete D?.commentHtml,delete D?.commentText,D})||[],c=_}return{strippedData:s,originalData:c,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(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(im(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 ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=$O(this.authService.getFirebaseConfig()?.firebaseOptions),p=Cr(this.functions,Zn.cloudFunction?.[c]?.setEncryptedData,{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let D=r?.targetAnnotationData?.commentId;if(D){let B=e?.comments?.find(G=>G?.commentId===D);B&&(r.targetAnnotationData=B)}}let h=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Zn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:Ta()},E=yield bp(_,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(vs),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var cse=(()=>{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)(J(y),J(Hn))},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 ee(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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var pse=(()=>{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)(J(y),J(Hn))},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){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 ee(this,null,function*(){try{return yield bp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y),J(Hn))},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,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}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 c of s)i.add(c)}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 ee(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 bp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(J(Uv),J(jv),J(y),J(Hn),J(je),J(vs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var use=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hse=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}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 ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=$O(this.authService.getFirebaseConfig()?.firebaseOptions),c=Cr(this.functions,Zn.cloudFunction?.[s]?.setEncryptedData,{timeout:20*60*1e3}),p=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",_={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:Ta()},E=yield bp(_,h);yield c({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?!Co(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:sv(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)(J(y),J(Hn),J(je),J(Vo),J($t),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vse=(()=>{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)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $v=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=_,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=X,this.tagUtilsService=he,this.usersService=Ie,this.docService=Me,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=We}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){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}/${U.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}/${U.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 U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.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:c,organizationId:p}=i;p||(p=r?.organizationId);let h=new xd({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){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}/${U.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(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return ee(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(c){return ee(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(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}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,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,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}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(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}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(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 c=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,c);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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return ee(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}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 ee(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 ee(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let _={comment:"allComments",reaction:"allReactions"}[e];if(!_)return null;let E=i?.metadata?.documentId,D=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(_)&&(!E||B.includes(E)||D&&B.includes(D))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return ee(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(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return ee(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)(J(ase),J(sse),J(Uv),J(lse),J(cse),J(xM),J(dse),J(y),J(pse),J(TM),J(use),J(hse),J(jv),J(fse),J(vse),J(Hn),J(lt),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new fe(null);try{Dn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),Je(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(Q6(Fp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||Q6("DocumentIdDb");if(e){let i=kS(e,"generateDocumentId");return kv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(J($t),J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=_,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(D=>{if(D){this.db=D;let B=on(D,".info/serverTimeOffset");this.offsetListener=gu(B,G=>{let X=G.val();this.offset=X})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}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){Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),Je(1),In(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return ee(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(_=>ee(this,[_],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 D=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 B,G;try{D&&(B=on(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(G=kv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!h})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){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=>ee(this,null,function*(){if(h.dbRef){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Of(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_)}}catch(_){this.loggingService.catch(`Error in setData for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){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=>ee(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield jA(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_,{merge:!0})}}catch(_){this.loggingService.catch(`Error in updateDoc for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return ee(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,c=>ee(this,null,function*(){c.dbRef&&(yield VA(c.dbRef));try{if(c.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:c.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:c.firestorePath??"",eventType:"DELETE"}))}else yield Lae(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}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=xn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),xn()||"noDocumentId"}}queryData(r){return ee(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 ee(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=kS(this.firestore,r);i?.useCollectionGroup&&(a=Kj(this.firestore,r));let s=i?.firestoreQuery??[],c=Xj(a,...s);if(i?.getCount){let p=yield Vae(c).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield jae(c).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 ee(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=on(this.db,r),s=i?.rtdbQuery??[],c=xL(a,...s),p=yield bL(c).catch(_=>(this.loggingService.catch(`Error in get for ${e}`,_),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 ee(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 c=yield Uae(kv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}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 c=yield bL(on(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}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 Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ge(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new fe({}),count:0};let _=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=_}return new Ft(h=>{let _=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{_?.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 re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Ig(()=>{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 Ft(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ge(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ge(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ge(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),Kt(_o)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=kS(e,i);if(s?.useCollectionGroup&&(p=Kj(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=Xj(p,...E)}let h=!0,_=[];return Zj(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(X=>{["allComments","allReactions"].includes(r)&&!h&&X.type!=="removed"&&_.push(X.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:X,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(D,this.handleCollectionChange(X,D)),X.type==="removed"&&(B||(B={type:X.type,ids:[]}),B.ids.push(X.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&_?.length&&(this.commonDbUtilsService.resolveAnnotations({data:_,feature:r}),_=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:B})),h=!1}catch(D){this.handleListenerError(D,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 c=kv(e,i);return Zj(c,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}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=xL(s,...c)}return Af(s).pipe(Ln(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((h,[_,E])=>(h[_]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(c,i))),ge(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ge(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(J(je),J($v),J(y),J(Cse),J(pn),J($t),J(lt),J(Hn),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=h,this.db=Ci(),this.internalUserContacts$=new fe([]),this.userGlobalContact$=new fe(!1),this.userGroupContact$=new fe(null),this.users$=new fe([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new fe([]),this.userFolderContacts$=new fe([]),this.userDocumentContacts$=new fe([]),this.userOrganizationGroups$=new fe([]),this.onContactSelectedSubject$=new et,this.documentAccessType=null,this.atHereEnabled$=new fe(!1),this.atHereLabel$=new fe("here"),this.atHereDescription$=new fe(null),this.contactListScopeForOrganizationUsers$=new fe([xi.ALL]),this.customUserContacts$=new fe(null),this.customUserContactsConfig$=new fe({merge:!1}),this.currentOrganizationUserIAM$=new fe(null),this.userContacts$=new fe([]),this.userSnippylyIdContacts$=new fe(null),this.usersByOrganizationId$=new fe({}),this.usersByOrganizationIdAndDocumentId$=new fe({}),this.usersByOrganizationIdAndFolderId$=new fe({}),this.userById$=new fe({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ge(_=>this.docService.getDocumentPaths$().pipe(In(E=>{this.documentPaths=E}),ce(()=>_)))).subscribe(_=>ee(this,null,function*(){this.user=_,_&&this.documentPaths?_?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getLoggedInUsersSubscription?.unsubscribe(),this.getOrganizationContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription?.unsubscribe())}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),Dn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,E,D])=>{E?D?.merge?this.userContacts$.next([..._||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(E=>{let D=E?.userSnippylyId||ov(this.configService.getApiKey(),E.userId);D&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[D]: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 ee(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:Rt(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:Rt(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:Rt(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 ee(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:Rt(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 c=r.contacts[s];if(c?.userId){let p=Rt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(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:Rt(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:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new wo;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:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return ee(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:Rt(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:Rt(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:Rt(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(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Rt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(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:Rt(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:Rt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return ee(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=>ee(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Rt(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:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return ee(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(Je(1)).subscribe(i=>ee(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===di.PUBLIC)r=!0;else if(a===di.RESTRICTED){let s=Rt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Rt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new Rp;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=>ee(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:Rt(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:Rt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return ee(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?Dn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,h,_,E,D])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let X=We=>D.some(ke=>We.includes(ke)),he=X([xi.ALL,xi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ie=a?X([xi.ALL,xi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Me=X([xi.ALL,xi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...he,...Ie||[],...Me].forEach(We=>{let ke=h?.[We];ke&&(B[We]=ke)}),_){let{merge:We,options:ke}=E||{},{organizationId:we,documentId:Ee,folderId:Pe}=ke||{},Ce=Pe?hl(Pe):void 0;(!we||we===i)&&(!Ee||Ee===r)&&(!Ce||Ce===a)&&(We||(B={}),_.forEach(ue=>{ue?.userId&&(B[ue.userId]=ue)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),In(i=>{this.documentPaths=i}),ce(()=>e))),ge(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();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),In(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),In(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:Rt(e?.userId)}}).pipe(ce(r=>r?.data),In(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),io(...i).pipe(oo(this.authService.getUser$().pipe(Ne(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(ge(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),In(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).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(ge(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(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(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)})):re():re()}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),In(r=>{this.documentPaths=r}),ce(()=>i))),ge(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ge(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),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)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",s?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let _=0;_<a.length;_+=U.LISTENER_BATCH_SIZE)h.push(a.slice(_,_+U.LISTENER_BATCH_SIZE));c=Dn(h.map(_=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",_),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[mt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(_=>ca(_)?.data))}return c.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let _=Object.values(h??{});this.setUserDocumentContacts(_)}else this.setUserDocumentContacts([])}))})):re():re())),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).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(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(xi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.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(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{if(this.setUserOrganizationGroups([]),!i)return re();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([])})):re()})):(this.setUserOrganizationGroups([]),re()))).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 di.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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}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(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.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 ee(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.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(ge(e=>e?Dn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(_=>this.convertToClientUser(_)),p.folderUsers=r?.map(_=>this.convertToClientUser(_)),p.documentUsers=a?.map(_=>this.convertToClientUser(_)),p.updatedContactList=c?.map(_=>this.convertToClientUser(_));let h=[];return s?.forEach(_=>{let E=this.convertToClientUserGroup(_,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),Kt(_o)):re(null)),Ln(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(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 c=Rt(s.userId);a[c]=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)(J(Qe),J(je),J($t),J(pn),J(lt),J(y),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _se=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){pt.catch("Error in File utils getFileName: ",o);return}},p$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){pt.catch("Error in File utils getFileExtension: ",o);return}},yse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+p$(n),{type:n.type})}catch(t){pt.catch("Error in File utils updateFile: ",t);return}},Sse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),bse={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 Bp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ty();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ty(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 Nv;r.name=i.name;let a=yse(i,`${r.attachmentId}_${_se(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=p$(i),r?.type&&(r.mimeType=bse[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=wy(this.storage,e.bucketPath),c=QL(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{XL(c.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(c){return ee(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:Ha.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,c)=>{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:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=wy(this.storage,c),h=QL(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",_=>{let E=_.bytesTransferred/_.totalBytes*100},_=>{s(_)},()=>{XL(h.snapshot.ref).then(_=>{a(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,_),s(_)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}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(U.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 c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),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(c=>{s(c)});else{let c=wy(this.storage,e.bucketPath);ZL(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=wy(this.storage,e);ZL(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(J(je),J($t),J(y),J(Lp))},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,s,c,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new fe(null),this.workspaceIAM$=new fe(null),this.roles$=new fe([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_,this.getUser(),this.getDocumentPaths())},_=>{this.loggingService.catch("Error in CommentService getDb subscription: ",_)}),this.getRole$().pipe(Je(1)).subscribe(_=>{this.authService?.getUser()&&!_&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(_=>{_?.accessType&&this.contactService.setDocumentAccessType(_.accessType)})}catch(_){this.loggingService.catch("Error in IamService constructor: ",_)}}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(Ne(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(Ne(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(Ln(e=>re(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),Kt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ge(e=>this.getRole$().pipe(ce(i=>(i===mo.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(ge(()=>this.documentIAM$.pipe(Ne(i=>!!i),ge(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ge(()=>this.configService.getSF$()),ge(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ge(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ge(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return mo.ADMIN;if(!e&&this.user?.isAdmin)return mo.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?di.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||di.PUBLIC:null){case di.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||mo.COMMENTER;break;case di.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===mo.ADMIN),Kt())}isUserAdmin(){try{return this.getRole()===mo.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?.[Rt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Rt(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?.[Rt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(gi),J(pn),J(lt),J($t),J(y),J(bn))},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,c,p,h,_,E,D,B,G,X,he,Ie){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=_,this.docService=E,this.domService=D,this.iamService=B,this.loggingService=G,this.notificationUtilsService=X,this.usersService=he,this.functions=Ie,this.db=Ci(),this.notificationsDb=Ci(void 0,Zn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new fe([]),this.rawNotificationsByIdMap$=new fe(new Map),this.processedNotifications$=new fe([]),this.readNotificationsOnForYouTab$=new fe(!1),this.notificationViews$=new fe({}),this.notificationsByIdMap$=new fe(new Map),this.historyPanelVisible$=new fe(!1),this.notificationsForYou$=new fe(null),this.notificationsByDocumentIdMap$=new fe(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new fe(null),this.maxNotificationDays$=new fe(15),this.tabConfig$=new fe({people:{enable:!1}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Me=>!!Me),Je(1)).subscribe(Me=>{Me&&(this.db=Me,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Me=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Me)}),this.authService.getUser$().subscribe(Me=>{Me?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Me=>{if(Me){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Me||{}).forEach(We=>{let ke=Le?.[We]?.notifications;ke?.length&&ke.forEach(we=>{this.notificationUtilsService.mergeLocationWithNotification({notification:we},Me)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(Me){this.loggingService.catch("Error in NotificationService constructor: ",Me)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}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(Vi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),c=a?.map(h=>({documentId:h,timestamp:i?.find(_=>_.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let _=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:_}}).filter(h=>{let _=e?.find(E=>E.documentId===h.documentId)?.timestamp;return _&&h.timestamp&&_!==h.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),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(ge(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new xd({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ge(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Fi(mt("timestamp",">=",p)),Ga("timestamp","desc"),Rv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let _=[];return Object.keys(h||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],B=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===D){let G=B.id,X=h[E]?.metadata?.documentId,he=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=he?.[X]??{documentMetadata:null,notifications:[]},Me=Ie.notifications??[],Le=Me?.findIndex(We=>We.id===G);Le!==-1&&(Me.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},he),{[X]:T(I({},Ie),{notifications:Me})})))}_.push({documentId:E,timestamp:D})}),_}),Ln(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return ee(this,null,function*(){try{if(e?.length){let r=Cr(this.functions,Zn.cloudFunction.getNotificationsForDocuments,{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),_=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Pie(_,E);if(D&&typeof D=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),X=[],he=[];Object.keys(D).forEach((Ie,Me)=>{let Le=D[Ie].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ie]||!Co(ke?.[Ie],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ie]:Le}))}let We=D[Ie].notifications||[];We.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ie,Le,We),B&&X.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldAwait:!0,forceResolve:!0})),G&&he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(X).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[Ie]?.notifications||[]});Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})}),G&&Promise.all(he).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=D?.[Ie]?.notifications?.reduce((We,ke)=>(We[ke.notificationId]=ke,We),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],_=this.docService.getLocationMetadatas(),E=r?.map(G=>{let X=G.notification;return X.metadata&&(X.metadata.documentName=i?.documentName||X.metadata.documentName,X.metadata.organizationMetadata=c||X.metadata.organizationMetadata,X.metadata.documentMetadata=i||X.metadata.documentMetadata),_&&(X=this.notificationUtilsService.mergeLocationWithNotification({notification:X},_)?.notification),X})?.filter(G=>!!G)||[],D=new Map(h.map(G=>[G.id,G]));E.forEach(G=>{D.set(G.id,G)});let B=Array.from(D.values()).sort((G,X)=>(X.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,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})),ge(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ge(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[EL("timestamp"),TL(h),IL(i)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",a.userId),Rv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ge(_=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:_,operation:null}})),ce(_=>_?.data??[]),ce(_=>(_.sort((E,D)=>D.timestamp-E.timestamp),_)),Ln(_=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",_),re([]))),ce(_=>(_.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),_)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}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(ge(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ge(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ge(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Rt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[EL("timestamp"),TL(h),IL(50)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",r.userId),Rv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ge(_=>_?.data?re(_).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),D.sort((G,X)=>X.timestamp-G.timestamp),D.map(G=>G.notification).filter(G=>!!G)}),ge(E=>{let D={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ge(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ge(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([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=fn(e)),i&&typeof i=="object"){let s=Xo(i);r=fn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return Wn(this.afAuth).pipe(Ne(s=>!!s),ge(s=>this.isFeatureAllowed({firebaseUser:s})),ge(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ge(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(),re([])):re(s).pipe(ge(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ge(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(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+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Af(a).pipe(Ln(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(_=>{let E=s?.raw[_];E?.id&&c.push(E)}),c.forEach(_=>{_.id&&p.set(_.id,_)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(_=>{let E=s?.processed[_];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Rt(e?.email));let a;e?.userId&&(a=Rt(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 _={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(_.id);if(E?.metadata&&(_.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}),_?.notificationSource==="comment"&&_?.targetAnnotationId){let D=this.commentService?.getAnnotationById(_.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(_.notificationSourceData=$n(D))}s.set(p.id,_)}}),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 c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let h=null;c?.email&&(h=Rt(c?.email));let _=null;c?.userId&&(_=Rt(c?.userId));let E=!1,D=!0;(h&&p.notifyUsers?.[h]||_&&p.notifyUsersByUserId?.[_])&&(E=!0),_&&a?.[_]&&(D=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):B={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:D,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=$n(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);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(c=>c.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 xd({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 c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.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=on(this.notificationsDb),r=this.processNotificationData(e);RA(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(ge(e=>e?e.organizationId?this.getAllNotifications$().pipe(ge(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,c)=>(c.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)),Eg()):re(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,c=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(c)}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(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.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(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let c=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(c)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let c=r?.[s]?.notifications||[],p=c.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(Je(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),ge(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),re({forYou:null,all:null})}}setNotificationAsRead(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Rt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,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:c,documentId:p,apiKey:s},data:h})));let _=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});_?.notificationId&&(this.getReadNotificationsOnForYouTab()?_?.views?.[r]||(_.views||(_.views={}),_.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:_})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}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 ee(this,null,function*(){try{this.getAllNotifications$().pipe(Je(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}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(bn),J($v),J(Uv),J(vs),J(pn),J(lt),J(Fe),J(gn),J(y),J(TM),J(Hn),J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $o=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new fe(U.CommentAnnotationStatusMap),this._customPriorityMap=new fe(U.CommentAnnotationPriorityMap),this._customCategoryMap=new fe(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.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(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.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(U.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(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.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(U.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(U.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 U.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 U.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[U.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(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,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=U.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=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hc=(()=>{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"/>
|