@veltdev/sdk-staging 5.0.2-beta.41 → 5.0.2-beta.43

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/velt.js +3 -3
package/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '5.0.2-beta.41';
1
+ var SNIPPYLY_VERSION = '5.0.2-beta.43';
2
2
  (function(c,E){"use strict";function U(){var e=X.splice(0,X.length);for(ue=0;e.length;)e.shift().call(null,e.shift())}function fe(e,t){for(var n=0,r=e.length;n<r;n++)Le(e[n],t)}function ot(e){for(var t,n=0,r=e.length;n<r;n++)t=e[n],_(t,B[pe(t)])}function de(e){return function(t){Lt(t)&&(Le(t,e),L.length&&fe(t.querySelectorAll(L),e))}}function pe(e){var t=ae.call(e,"is"),n=e.nodeName.toUpperCase(),r=H.call(D,t?J+t.toUpperCase():q+n);return t&&-1<r&&!Ie(n,t)?-1:r}function Ie(e,t){return-1<L.indexOf(e+'[is="'+t+'"]')}function Fe(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,o=e.target,l=e[Y]||2,a=e[ge]||3;!se||o&&o!==t||!t[C]||r==="style"||e.prevValue===e.newValue&&(e.newValue!==""||n!==l&&n!==a)||t[C](r,n===l?null:e.prevValue,n===a?null:e.newValue)}function Se(e){var t=de(e);return function(n){X.push(t,n.target),ue&&clearTimeout(ue),ue=setTimeout(U,1)}}function he(e){rt&&(rt=!1,e.currentTarget.removeEventListener(Ze,he)),L.length&&fe((e.target||u).querySelectorAll(L),e.detail===v?v:y),R&&at()}function lt(e,t){var n=this;Je.call(n,e,t),Ee.call(n,{target:n})}function Pe(e,t,n){var r=t.apply(e,n),o=pe(r);return-1<o&&_(r,B[o]),n.pop()&&L.length&&ot(r.querySelectorAll(L)),r}function Te(e,t){Tt(e,t),Q?Q.observe(e,gt):(ce&&(e.setAttribute=lt,e[g]=ve(e),e[b](st,Ee)),e[b](N,Fe)),e[x]&&se&&(e.created=!0,e[x](),e.created=!1)}function at(){for(var e,t=0,n=z.length;t<n;t++)e=z[t],P.contains(e)||(n--,z.splice(t--,1),Le(e,v))}function Ve(e){throw new Error("A "+e+" type is already registered")}function Le(e,t){var n,r,o=pe(e);-1<o&&!Mt.call(e,"TEMPLATE")&&(W(e,B[o]),o=0,t!==y||e[y]?t!==v||e[v]||(e[y]=!1,e[v]=!0,r="disconnected",o=1):(e[v]=!1,e[y]=!0,r="connected",o=1,R&&H.call(z,e)<0&&z.push(e)),o&&(n=e[t+O]||e[r+O])&&n.call(e))}function K(){}function Re(e,t,n){var r=n&&n[k]||"",o=t.prototype,l=we(o),a=t.observedAttributes||Ce,m={prototype:l};le(l,x,{value:function(){if(ne)ne=!1;else if(!this[j]){this[j]=!0,new t(this),o[x]&&o[x].call(this);var i=G[re.get(t)];(!Z||i.create.length>1)&&ke(this)}}}),le(l,C,{value:function(i){-1<H.call(a,i)&&o[C]&&o[C].apply(this,arguments)}}),o[Be]&&le(l,ut,{value:o[Be]}),o[je]&&le(l,ct,{value:o[je]}),r&&(m[k]=r),e=e.toUpperCase(),G[e]={constructor:t,create:r?[r,oe(e)]:[e]},re.set(t,e),u[S](e.toLowerCase(),m),Me(e),V[e].r()}function Ue(e){var t=G[e.toUpperCase()];return t&&t.constructor}function _e(e){return typeof e=="string"?e:e&&e.is||""}function ke(e){for(var t,n=e[C],r=n?e.attributes:Ce,o=r.length;o--;)t=r[o],n.call(e,t.name||t.nodeName,null,t.value||t.nodeValue)}function Me(e){return e=e.toUpperCase(),e in V||(V[e]={},V[e].p=new $e(function(t){V[e].r=t})),V[e].p}function xe(){w&&delete c.customElements,I(c,"customElements",{configurable:!0,value:new K}),I(c,"CustomElementRegistry",{configurable:!0,value:K});for(var e=it.get(/^HTML[A-Z]*[a-z]/),t=e.length;t--;(function(n){var r=c[n];if(r){c[n]=function(o){var l,a;return o||(o=this),o[j]||(ne=!0,l=G[re.get(o.constructor)],a=Z&&l.create.length===1,o=a?Reflect.construct(r,Ce,l.constructor):u.createElement.apply(u,l.create),o[j]=!0,ne=!1,a||ke(o)),o},c[n].prototype=r.prototype;try{r.prototype.constructor=c[n]}catch{pt=!0,I(r,j,{value:c[n]})}}})(e[t]));u.createElement=function(n,r){var o=_e(r);return o?Oe.call(this,n,oe(o)):Oe.call(this,n)},tt||(Ne=!0,u[S](""))}var u=c.document,T=c.Object,it=(function(e){var t,n,r,o,l=/^[A-Z]+[a-z]/,a=function(d){var f,h=[];for(f in i)d.test(f)&&h.push(f);return h},m=function(d,f){(f=f.toLowerCase())in i||(i[d]=(i[d]||[]).concat(f),i[f]=i[f.toUpperCase()]=d)},i=(T.create||T)(null),s={};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 s.get=function(d){return typeof d=="string"?i[d]||(l.test(d)?[]:""):a(d)},s.set=function(d,f){return l.test(d)?m(d,f):m(f,d),s},s})({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 E!="object"&&(E={type:E||"auto"});var X,Ee,$,ve,Q,He,W,_,A,S="registerElement",qe=1e5*c.Math.random()>>0,g="__"+S+qe,b="addEventListener",y="attached",O="Callback",v="detached",k="extends",C="attributeChanged"+O,ut=y+O,Be="connected"+O,je="disconnected"+O,x="created"+O,ct=v+O,Y="ADDITION",ge="REMOVAL",N="DOMAttrModified",Ze="DOMContentLoaded",st="DOMSubtreeModified",q="<",J="=",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=[],B=[],L="",P=u.documentElement,H=D.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},be=T.prototype,ye=be.hasOwnProperty,ee=be.isPrototypeOf,I=T.defineProperty,Ce=[],te=T.getOwnPropertyDescriptor,Ge=T.getOwnPropertyNames,dt=T.getPrototypeOf,ze=T.setPrototypeOf,Ke=!!T.__proto__,pt=!1,j="__dreCEv1",w=c.customElements,Z=!/^force/.test(E.type)&&!!(w&&w.define&&w.get&&w.whenDefined),Xe=T.create||T,ht=c.Map||function(){var e,t=[],n=[];return{get:function(r){return n[H.call(t,r)]},set:function(r,o){e=H.call(t,r),e<0?n[t.push(r)-1]=o:n[e]=o}}},$e=c.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},ne=!1,G=Xe(null),V=Xe(null),re=new ht,oe=function(e){return e.toLowerCase()},we=T.create||function e(t){return t?(e.prototype=t,new e):this},Tt=ze||(Ke?function(e,t){return e.__proto__=t,e}:Ge&&te?(function(){function e(t,n){for(var r,o=Ge(n),l=0,a=o.length;l<a;l++)r=o[l],ye.call(t,r)||I(t,r,te(n,r))}return function(t,n){do e(t,n);while((n=dt(n))&&!ee.call(n,t));return t}})():function(e,t){for(var n in t)e[n]=t[n];return e}),F=c.MutationObserver||c.WebKitMutationObserver,Qe=c.HTMLAnchorElement,p=(c.HTMLElement||c.Element||c.Node).prototype,R=!ee.call(p,P),le=R?function(e,t,n){return e[t]=n.value,e}:I,Lt=R?function(e){return e.nodeType===1}:function(e){return ee.call(p,e)},z=R&&[],We=p.attachShadow,Ye=p.cloneNode,Mt=p.closest||function(e){for(var t=this;t&&t.nodeName!==e;)t=t.parentNode;return t},Ae=p.dispatchEvent,ae=p.getAttribute,Et=p.hasAttribute,vt=p.removeAttribute,Je=p.setAttribute,ie=u.createElement,Ht=u.importNode,Oe=ie,gt=F&&{attributes:!0,characterData:!0,attributeOldValue:!0},et=F||function(e){ce=!1,P.removeEventListener(N,et)},ue=0,tt=S in u&&!/^force-all/.test(E.type),nt=!0,Ne=!1,ce=!0,rt=!0,se=!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=te(p,"innerHTML");var n=A&&A.set;n&&I(p,"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=""),tt||(ze||Ke?(W=function(e,t){ee.call(t,e)||Te(e,t)},_=Te):(W=function(e,t){e[g]||(e[g]=T(!0),Te(e,t))},_=W),R?(ce=!1,(function(){var e=te(p,b),t=e.value,n=function(l){var a=new CustomEvent(N,{bubbles:!0});a.attrName=l,a.prevValue=ae.call(this,l),a.newValue=null,a[ge]=a.attrChange=2,vt.call(this,l),Ae.call(this,a)},r=function(l,a){var m=Et.call(this,l),i=m&&ae.call(this,l),s=new CustomEvent(N,{bubbles:!0});Je.call(this,l,a),s.attrName=l,s.prevValue=m?i:null,s.newValue=a,m?s.MODIFICATION=s.attrChange=1:s[Y]=s.attrChange=0,Ae.call(this,s)},o=function(l){var a,m=l.currentTarget,i=m[g],s=l.propertyName;i.hasOwnProperty(s)&&(i=i[s],a=new CustomEvent(N,{bubbles:!0}),a.attrName=i.name,a.prevValue=i.value||null,a.newValue=i.value=m[s]||null,a.prevValue==null?a[Y]=a.attrChange=0:a.MODIFICATION=a.attrChange=1,Ae.call(m,a))};e.value=function(l,a,m){l===N&&this[C]&&this.setAttribute!==r&&(this[g]={className:{name:"class",value:this.className}},this.setAttribute=r,this.removeAttribute=n,t.call(this,"propertychange",o)),t.call(this,l,a,m)},I(p,b,e)})()):F||(P[b](N,et),P.setAttribute(g,1),P.removeAttribute(g),ce&&(Ee=function(e){var t,n,r,o=this;if(o===e.target){t=o[g],o[g]=n=ve(o);for(r in n){if(!(r in t))return $(0,o,r,t[r],n[r],Y);if(n[r]!==t[r])return $(1,o,r,t[r],n[r],"MODIFICATION")}for(r in t)if(!(r in n))return $(2,o,r,t[r],n[r],ge)}},$=function(e,t,n,r,o,l){var a={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:o};a[l]=e,Fe(a)},ve=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(),nt&&(nt=!1,F?(Q=(function(i,s){function d(f,h){for(var M=0,me=f.length;M<me;h(f[M++]));}return new F(function(f){for(var h,M,me,De=0,bt=f.length;De<bt;De++)h=f[De],h.type==="childList"?(d(h.addedNodes,i),d(h.removedNodes,s)):(M=h.target,se&&M[C]&&h.attributeName!=="style"&&(me=ae.call(M,h.attributeName))!==h.oldValue&&M[C](h.attributeName,h.oldValue,me))})})(de(y),de(v)),He=function(i){return Q.observe(i,{childList:!0,subtree:!0}),i},He(u),We&&(p.attachShadow=function(){return He(We.apply(this,arguments))})):(X=[],u[b]("DOMNodeInserted",Se(y)),u[b]("DOMNodeRemoved",Se(v))),u[b](Ze,he),u[b]("readystatechange",he),u.importNode=function(i,s){switch(i.nodeType){case 1:return Pe(u,Ht,[i,!!s]);case 11:for(var d=u.createDocumentFragment(),f=i.childNodes,h=f.length,M=0;M<h;M++)d.appendChild(u.importNode(f[M],!!s));return d;default:return Ye.call(i,!!s)}},p.cloneNode=function(i){return Pe(this,Ye,[!!i])}),Ne)return Ne=!1;if(-2<H.call(D,J+n)+H.call(D,q+n)&&Ve(e),!mt.test(n)||-1<H.call(ft,n))throw new Error("The type "+e+" is invalid");var n,r,o=function(){return a?u.createElement(m,n):u.createElement(m)},l=t||be,a=ye.call(l,k),m=a?t[k].toUpperCase():n;return a&&-1<H.call(D,q+m)&&Ve(m),r=D.push((a?J:q)+n)-1,L=L.concat(L.length?",":"",a?m+'[is="'+e.toLowerCase()+'"]':m),o.prototype=B[r]=ye.call(l,"prototype")?l.prototype:we(p),L.length&&fe(u.querySelectorAll(L),y),o},u.createElement=Oe=function(e,t){var n=_e(t),r=n?ie.call(u,e,oe(n)):ie.call(u,e),o=""+e,l=H.call(D,(n?J:q)+(n||o).toUpperCase()),a=-1<l;return n&&(r.setAttribute("is",n=n.toLowerCase()),a&&(a=Ie(o.toUpperCase(),n))),se=!u.createElement.innerHTMLHelper,a&&_(r,B[l]),r}),addEventListener("beforeunload",function(){delete u.createElement,delete u.importNode,delete u[S]},!1),K.prototype={constructor:K,define:Z?function(e,t,n){if(n)Re(e,t,n);else{var r=e.toUpperCase();G[r]={constructor:t,create:[r]},re.set(t,r),w.define(e,t)}}:Re,get:Z?function(e){return w.get(e)||Ue(e)}:Ue,whenDefined:Z?function(e){return $e.race([w.whenDefined(e),Me(e)])}:Me},!w||/^force/.test(E.type))xe();else if(!E.noBuiltIn)try{(function(e,t,n){var r=new RegExp(`^<a\\s+is=('|")`+n+"\\1></a>$");if(t[k]="a",e.prototype=we(Qe.prototype),e.prototype.constructor=e,c.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(Qe,[],e)},{},"document-register-element-a"+qe)}catch{xe()}if(!E.noBuiltIn)try{if(ie.call(u,"a","a").outerHTML.indexOf("is")<0)throw{}}catch{oe=function(t){return{is:t.toLowerCase()}}}})(window);Promise.allSettled||(Promise.allSettled=function(c){return Promise.all(c.map(function(E){return Promise.resolve(E).then(function(U){return{status:"fulfilled",value:U}}).catch(function(U){return{status:"rejected",reason:U}})}))});
3
3
 
4
4
  var R3e=Object.create;var W5=Object.defineProperty,N3e=Object.defineProperties,F3e=Object.getOwnPropertyDescriptor,L3e=Object.getOwnPropertyDescriptors,U3e=Object.getOwnPropertyNames,z5=Object.getOwnPropertySymbols,$te=Object.getPrototypeOf,aB=Object.prototype.hasOwnProperty,Hte=Object.prototype.propertyIsEnumerable,V3e=Reflect.get;var jte=(n,o,r)=>o in n?W5(n,o,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[o]=r,f=(n,o)=>{for(var r in o||={})aB.call(o,r)&&jte(n,r,o[r]);if(z5)for(var r of z5(o))Hte.call(o,r)&&jte(n,r,o[r]);return n},k=(n,o)=>N3e(n,L3e(o));var Dh=(n,o)=>{var r={};for(var e in n)aB.call(n,e)&&o.indexOf(e)<0&&(r[e]=n[e]);if(n!=null&&z5)for(var e of z5(n))o.indexOf(e)<0&&Hte.call(n,e)&&(r[e]=n[e]);return r};var B3e=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),q5=(n,o)=>{for(var r in o)W5(n,r,{get:o[r],enumerable:!0})},j3e=(n,o,r,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of U3e(o))!aB.call(n,t)&&t!==r&&W5(n,t,{get:()=>o[t],enumerable:!(e=F3e(o,t))||e.enumerable});return n};var Gte=(n,o,r)=>(r=n!=null?R3e($te(n)):{},j3e(o||!n||!n.__esModule?W5(r,"default",{value:n,enumerable:!0}):r,n));var Cm=(n,o,r)=>V3e($te(n),r,o);var Q=(n,o,r)=>new Promise((e,t)=>{var i=s=>{try{l(r.next(s))}catch(d){t(d)}},a=s=>{try{l(r.throw(s))}catch(d){t(d)}},l=s=>s.done?e(s.value):Promise.resolve(s.value).then(i,a);l((r=r.apply(n,o)).next())});var lte=B3e((G0i,ate)=>{"use strict";var Nt={};Nt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Nt.localCName=Nt.generateIdentifier();Nt.splitLines=function(n){return n.trim().split(`
@@ -219,7 +219,7 @@ This typically indicates that your device does not have a healthy Internet conne
219
219
  <img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
220
220
  </a>
221
221
  `}};var up=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Oo}};var yL=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Oo}};var r3=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var pp=class{constructor(){this.pageInfo=new Oo}},o3=(function(n){return n.Start="start",n.End="end",n})(o3||{}),iS=(function(n){return n.Avatar="avatar",n.Label="label",n})(iS||{});var xL=class{constructor(){this.sources=[],this.playerState=new i3}},i3=class{constructor(){this.volume=1}};var a3=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Oo}};var im=class{constructor(){this.visibility="private"}};var kL=class{};var $s=(function(n){return n.EDITOR="editor",n.VIEWER="viewer",n})($s||{}),_o=(function(n){return n.DOES_NOT_EXIST="does_not_exist",n.PERMISSION_DENIED="permission_denied",n.SOMETHING_WENT_WRONG="something_went_wrong",n})(_o||{});var IL=(function(n){return n.INTERNAL="internal",n.EXTERNAL="external",n})(IL||{}),EL=(function(n){return n.UPDATE_DATA="updateData",n})(EL||{});var Ft=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new Se(null),this.disableLogsConfig$=new Se({warnings:!0,suppressAll:!1}),this.apiKey$=new Se(""),this.baseFeatureAllowList=[],this.sf$=new Se(!1),this.sdkType$=new Se("core"),this.logsEnabled$=new Se(!0),this.safeEval$=new Se(!1),this.firestorePersistentCacheEnabled$=new Se(!1),this.encryptionProvider$=new Se(null);try{this.analyticsService.setConfigService(this),this.sdkType$.subscribe(i=>{this.analyticsService.updateDefaultProperties({sdkType:i})},i=>{this.loggingService.catch("Error in ConfigService sdkType$: ",i)}),this.logsEnabled$.subscribe(i=>{i?this.loggingService.enableLogs():this.loggingService.disableLogs(),at.logsEnabled=i},i=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",i)})}catch(i){this.loggingService.catch("Error in ConfigService constructor: ",i)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(je)),this.baseFeatureAllowList=e.featureAllowList?.slice();try{e.proxyConfig?.authHost?localStorage.setItem(U.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST,btoa(e.proxyConfig.authHost)):localStorage.removeItem(U.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST)}catch{}this.config$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService initConfig: ",t)}}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 t=this.config$.value;t&&(e?.length?t.featureAllowList=this.baseFeatureAllowList.filter(i=>!e.includes(i)):t.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(t)}catch(t){this.loggingService.catch("Error in ConfigService disableFeatures: ",t)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(t){this.loggingService.catch("Error in ConfigService setSF: ",t)}}getSF(){try{return this.sf$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSF: ",e),!1}}getSF$(){try{return this.sf$.asObservable().pipe(xt(Jt))}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),le(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setSdkType: ",t)}}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),le("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(t){this.loggingService.catch("Error in ConfigService disableLogs: ",t)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getProxyConfig(){try{return this.config$.value?.proxyConfig}catch(e){this.loggingService.catch("Error in ConfigService getProxyConfig: ",e);return}}getAuthProxyHost(){try{let e=this.config$.value?.proxyConfig?.authHost;if(e)return e;let t=localStorage.getItem(U.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST);return t?atob(t):void 0}catch(e){this.loggingService.catch("Error in ConfigService getAuthProxyHost: ",e);return}}getApiHost(){try{return this.getProxyConfig()?.apiHost||this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiHost: ",e);return}}getApiProxyDomain(){return this.getApiHost()}enableSafeEval(){try{this.safeEval$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableSafeEval: ",e)}}disableSafeEval(){try{this.safeEval$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableSafeEval: ",e)}}getSafeEval(){try{return this.safeEval$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval: ",e),!1}}getSafeEval$(){try{return this.safeEval$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval$: ",e),le(!1)}}enableFirestorePersistentCache(){try{this.firestorePersistentCacheEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableFirestorePersistentCache: ",e)}}disableFirestorePersistentCache(){try{this.firestorePersistentCacheEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableFirestorePersistentCache: ",e)}}isFirestorePersistentCacheEnabled(){try{return this.firestorePersistentCacheEnabled$.value}catch(e){return this.loggingService.catch("Error in ConfigService isFirestorePersistentCacheEnabled: ",e),!1}}getFirestorePersistentCacheEnabled$(){try{return this.firestorePersistentCacheEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getFirestorePersistentCacheEnabled$: ",e),le(!1)}}setEncryptionProvider(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEncryptionProvider","color: green;"),this.encryptionProvider$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setEncryptionProvider: ",t)}}getEncryptionProvider(){try{return this.encryptionProvider$.value}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider: ",e),null}}getEncryptionProvider$(){try{return this.encryptionProvider$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider$: ",e),le(null)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var d_e=(()=>{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 t=new F0;return this.setLocalStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new F0}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let t=JSON.stringify(e);localStorage?.setItem(U.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setLocalStorageData:",t)}}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 t=new F0;return this.setSessionStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new F0}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let t=JSON.stringify(e);sessionStorage?.setItem(U.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setSessionStorageData:",t)}}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(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sv=(()=>{let o=class o{constructor(e,t){this.localStorageService=e,this.loggingService=t,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 ra,t=this.localStorageService.getSessionStorageData();if(t.snippylyAvatar)e=t.snippylyAvatar;else{let i=this.generateUserAvatar();t.snippylyAvatar=i,this.localStorageService.setSessionStorageData(t)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new ra}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),t=this.avatarList[e];return t.color=this.generateUserColor(),t}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 t=Math.floor(Math.random()*U.AVATAR_COLOR_LIST.length);return U.AVATAR_COLOR_LIST[t]}catch(t){return this.loggingService.catch("Error in generateUserColor:",t),""}}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(t){return new(t||o)(X(d_e),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var tr=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new it),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CoreActionsService triggerAction: ",i)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new it);let t=this.actionSubjects.get(e);return t?t.asObservable():le(null)}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),le(null)}}};o.\u0275fac=function(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:__e,setPrototypeOf:m_e,isFrozen:aWe,getPrototypeOf:lWe,getOwnPropertyDescriptor:sWe}=Object,{freeze:ps,seal:nd,create:CQ}=Object,{apply:_Q,construct:bQ}=typeof Reflect<"u"&&Reflect;ps||(ps=function(o){return o});nd||(nd=function(o){return o});_Q||(_Q=function(o,r){for(var e=arguments.length,t=new Array(e>2?e-2:0),i=2;i<e;i++)t[i-2]=arguments[i];return o.apply(r,t)});bQ||(bQ=function(o){for(var r=arguments.length,e=new Array(r>1?r-1:0),t=1;t<r;t++)e[t-1]=arguments[t];return new o(...e)});var TL=hs(Array.prototype.forEach),cWe=hs(Array.prototype.lastIndexOf),v_e=hs(Array.prototype.pop),s3=hs(Array.prototype.push),dWe=hs(Array.prototype.splice),DL=hs(String.prototype.toLowerCase),vQ=hs(String.prototype.toString),gQ=hs(String.prototype.match),c3=hs(String.prototype.replace),mWe=hs(String.prototype.indexOf),vWe=hs(String.prototype.trim),am=hs(Object.prototype.hasOwnProperty),us=hs(RegExp.prototype.test),d3=gWe(TypeError);function hs(n){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var r=arguments.length,e=new Array(r>1?r-1:0),t=1;t<r;t++)e[t-1]=arguments[t];return _Q(n,o,e)}}function gWe(n){return function(){for(var o=arguments.length,r=new Array(o),e=0;e<o;e++)r[e]=arguments[e];return bQ(n,r)}}function Rr(n,o){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:DL;m_e&&m_e(n,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let i=r(t);i!==t&&(aWe(o)||(o[e]=i),t=i)}n[t]=!0}return n}function uWe(n){for(let o=0;o<n.length;o++)am(n,o)||(n[o]=null);return n}function Eg(n){let o=CQ(null);for(let[r,e]of __e(n))am(n,r)&&(Array.isArray(e)?o[r]=uWe(e):e&&typeof e=="object"&&e.constructor===Object?o[r]=Eg(e):o[r]=e);return o}function m3(n,o){for(;n!==null;){let e=sWe(n,o);if(e){if(e.get)return hs(e.get);if(typeof e.value=="function")return hs(e.value)}n=lWe(n)}function r(){return null}return r}var g_e=ps(["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","search","section","select","shadow","slot","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"]),uQ=ps(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),pQ=ps(["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"]),pWe=ps(["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"]),hQ=ps(["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"]),hWe=ps(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),u_e=ps(["#text"]),p_e=ps(["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","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","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","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),fQ=ps(["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","mask-type","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"]),h_e=ps(["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"]),wL=ps(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),fWe=nd(/\{\{[\w\W]*|[\w\W]*\}\}/gm),CWe=nd(/<%[\w\W]*|[\w\W]*%>/gm),_We=nd(/\$\{[\w\W]*/gm),bWe=nd(/^data-[\-\w.\u00B7-\uFFFF]+$/),SWe=nd(/^aria-[\-\w]+$/),b_e=nd(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),yWe=nd(/^(?:\w+script|data):/i),xWe=nd(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),S_e=nd(/^html$/i),kWe=nd(/^[a-z][.\w]*(-[.\w]+)+$/i),f_e=Object.freeze({__proto__:null,ARIA_ATTR:SWe,ATTR_WHITESPACE:xWe,CUSTOM_ELEMENT:kWe,DATA_ATTR:bWe,DOCTYPE_NAME:S_e,ERB_EXPR:CWe,IS_ALLOWED_URI:b_e,IS_SCRIPT_OR_DATA:yWe,MUSTACHE_EXPR:fWe,TMPLIT_EXPR:_We}),v3={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},IWe=function(){return typeof window>"u"?null:window},EWe=function(o,r){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,t="data-tt-policy-suffix";r&&r.hasAttribute(t)&&(e=r.getAttribute(t));let i="dompurify"+(e?"#"+e:"");try{return o.createPolicy(i,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},C_e=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function y_e(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:IWe(),o=yn=>y_e(yn);if(o.version="3.3.0",o.removed=[],!n||!n.document||n.document.nodeType!==v3.document||!n.Element)return o.isSupported=!1,o;let{document:r}=n,e=r,t=e.currentScript,{DocumentFragment:i,HTMLTemplateElement:a,Node:l,Element:s,NodeFilter:d,NamedNodeMap:g=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:u,DOMParser:b,trustedTypes:E}=n,A=s.prototype,M=m3(A,"cloneNode"),V=m3(A,"remove"),q=m3(A,"nextSibling"),ae=m3(A,"childNodes"),fe=m3(A,"parentNode");if(typeof a=="function"){let yn=r.createElement("template");yn.content&&yn.content.ownerDocument&&(r=yn.content.ownerDocument)}let ie,Ce="",{implementation:xe,createNodeIterator:ke,createDocumentFragment:ye,getElementsByTagName:Oe}=r,{importNode:Ne}=e,Ue=C_e();o.isSupported=typeof __e=="function"&&typeof fe=="function"&&xe&&xe.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:ze,ERB_EXPR:Ge,TMPLIT_EXPR:$r,DATA_ATTR:et,ARIA_ATTR:Tt,IS_SCRIPT_OR_DATA:Xe,ATTR_WHITESPACE:$t,CUSTOM_ELEMENT:rn}=f_e,{IS_ALLOWED_URI:lr}=f_e,Hr=null,bo=Rr({},[...g_e,...uQ,...pQ,...hQ,...u_e]),Zn=null,So=Rr({},[...p_e,...fQ,...h_e,...wL]),Xr=Object.seal(CQ(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}})),Mn=null,un=null,hi=Object.seal(CQ(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Po=!0,aa=!0,md=!1,FC=!0,um=!1,Rg=!0,vd=!1,LC=!1,UC=!1,Ng=!1,fh=!1,Ch=!1,VC=!0,LE=!1,XV="user-content-",_h=!0,Tv=!1,pm={},xi=null,Va=Rr({},["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"]),bh=null,UE=Rr({},["audio","video","img","source","image","track"]),BC=null,D5=Rr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),hm="http://www.w3.org/1998/Math/MathML",Sh="http://www.w3.org/2000/svg",Oc="http://www.w3.org/1999/xhtml",fm=Oc,VE=!1,BE=null,jE=Rr({},[hm,Sh,Oc],vQ),yh=Rr({},["mi","mo","mn","ms","mtext"]),xh=Rr({},["annotation-xml"]),kh=Rr({},["title","style","font","a","script"]),wv=null,$E=["application/xhtml+xml","text/html"],Dv="text/html",zi=null,gd=null,O5=r.createElement("form"),Fg=function(Ke){return Ke instanceof RegExp||Ke instanceof Function},jC=function(){let Ke=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(gd&&gd===Ke)){if((!Ke||typeof Ke!="object")&&(Ke={}),Ke=Eg(Ke),wv=$E.indexOf(Ke.PARSER_MEDIA_TYPE)===-1?Dv:Ke.PARSER_MEDIA_TYPE,zi=wv==="application/xhtml+xml"?vQ:DL,Hr=am(Ke,"ALLOWED_TAGS")?Rr({},Ke.ALLOWED_TAGS,zi):bo,Zn=am(Ke,"ALLOWED_ATTR")?Rr({},Ke.ALLOWED_ATTR,zi):So,BE=am(Ke,"ALLOWED_NAMESPACES")?Rr({},Ke.ALLOWED_NAMESPACES,vQ):jE,BC=am(Ke,"ADD_URI_SAFE_ATTR")?Rr(Eg(D5),Ke.ADD_URI_SAFE_ATTR,zi):D5,bh=am(Ke,"ADD_DATA_URI_TAGS")?Rr(Eg(UE),Ke.ADD_DATA_URI_TAGS,zi):UE,xi=am(Ke,"FORBID_CONTENTS")?Rr({},Ke.FORBID_CONTENTS,zi):Va,Mn=am(Ke,"FORBID_TAGS")?Rr({},Ke.FORBID_TAGS,zi):Eg({}),un=am(Ke,"FORBID_ATTR")?Rr({},Ke.FORBID_ATTR,zi):Eg({}),pm=am(Ke,"USE_PROFILES")?Ke.USE_PROFILES:!1,Po=Ke.ALLOW_ARIA_ATTR!==!1,aa=Ke.ALLOW_DATA_ATTR!==!1,md=Ke.ALLOW_UNKNOWN_PROTOCOLS||!1,FC=Ke.ALLOW_SELF_CLOSE_IN_ATTR!==!1,um=Ke.SAFE_FOR_TEMPLATES||!1,Rg=Ke.SAFE_FOR_XML!==!1,vd=Ke.WHOLE_DOCUMENT||!1,Ng=Ke.RETURN_DOM||!1,fh=Ke.RETURN_DOM_FRAGMENT||!1,Ch=Ke.RETURN_TRUSTED_TYPE||!1,UC=Ke.FORCE_BODY||!1,VC=Ke.SANITIZE_DOM!==!1,LE=Ke.SANITIZE_NAMED_PROPS||!1,_h=Ke.KEEP_CONTENT!==!1,Tv=Ke.IN_PLACE||!1,lr=Ke.ALLOWED_URI_REGEXP||b_e,fm=Ke.NAMESPACE||Oc,yh=Ke.MATHML_TEXT_INTEGRATION_POINTS||yh,xh=Ke.HTML_INTEGRATION_POINTS||xh,Xr=Ke.CUSTOM_ELEMENT_HANDLING||{},Ke.CUSTOM_ELEMENT_HANDLING&&Fg(Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Xr.tagNameCheck=Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ke.CUSTOM_ELEMENT_HANDLING&&Fg(Ke.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Xr.attributeNameCheck=Ke.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ke.CUSTOM_ELEMENT_HANDLING&&typeof Ke.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Xr.allowCustomizedBuiltInElements=Ke.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),um&&(aa=!1),fh&&(Ng=!0),pm&&(Hr=Rr({},u_e),Zn=[],pm.html===!0&&(Rr(Hr,g_e),Rr(Zn,p_e)),pm.svg===!0&&(Rr(Hr,uQ),Rr(Zn,fQ),Rr(Zn,wL)),pm.svgFilters===!0&&(Rr(Hr,pQ),Rr(Zn,fQ),Rr(Zn,wL)),pm.mathMl===!0&&(Rr(Hr,hQ),Rr(Zn,h_e),Rr(Zn,wL))),Ke.ADD_TAGS&&(typeof Ke.ADD_TAGS=="function"?hi.tagCheck=Ke.ADD_TAGS:(Hr===bo&&(Hr=Eg(Hr)),Rr(Hr,Ke.ADD_TAGS,zi))),Ke.ADD_ATTR&&(typeof Ke.ADD_ATTR=="function"?hi.attributeCheck=Ke.ADD_ATTR:(Zn===So&&(Zn=Eg(Zn)),Rr(Zn,Ke.ADD_ATTR,zi))),Ke.ADD_URI_SAFE_ATTR&&Rr(BC,Ke.ADD_URI_SAFE_ATTR,zi),Ke.FORBID_CONTENTS&&(xi===Va&&(xi=Eg(xi)),Rr(xi,Ke.FORBID_CONTENTS,zi)),_h&&(Hr["#text"]=!0),vd&&Rr(Hr,["html","head","body"]),Hr.table&&(Rr(Hr,["tbody"]),delete Mn.tbody),Ke.TRUSTED_TYPES_POLICY){if(typeof Ke.TRUSTED_TYPES_POLICY.createHTML!="function")throw d3('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ke.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw d3('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ie=Ke.TRUSTED_TYPES_POLICY,Ce=ie.createHTML("")}else ie===void 0&&(ie=EWe(E,t)),ie!==null&&typeof Ce=="string"&&(Ce=ie.createHTML(""));ps&&ps(Ke),gd=Ke}},Ba=Rr({},[...uQ,...pQ,...pWe]),HE=Rr({},[...hQ,...hWe]),Ih=function(Ke){let Ut=fe(Ke);(!Ut||!Ut.tagName)&&(Ut={namespaceURI:fm,tagName:"template"});let sn=DL(Ke.tagName),Ho=DL(Ut.tagName);return BE[Ke.namespaceURI]?Ke.namespaceURI===Sh?Ut.namespaceURI===Oc?sn==="svg":Ut.namespaceURI===hm?sn==="svg"&&(Ho==="annotation-xml"||yh[Ho]):!!Ba[sn]:Ke.namespaceURI===hm?Ut.namespaceURI===Oc?sn==="math":Ut.namespaceURI===Sh?sn==="math"&&xh[Ho]:!!HE[sn]:Ke.namespaceURI===Oc?Ut.namespaceURI===Sh&&!xh[Ho]||Ut.namespaceURI===hm&&!yh[Ho]?!1:!HE[sn]&&(kh[sn]||!Ba[sn]):!!(wv==="application/xhtml+xml"&&BE[Ke.namespaceURI]):!1},Tl=function(Ke){s3(o.removed,{element:Ke});try{fe(Ke).removeChild(Ke)}catch{V(Ke)}},Ov=function(Ke,Ut){try{s3(o.removed,{attribute:Ut.getAttributeNode(Ke),from:Ut})}catch{s3(o.removed,{attribute:null,from:Ut})}if(Ut.removeAttribute(Ke),Ke==="is")if(Ng||fh)try{Tl(Ut)}catch{}else try{Ut.setAttribute(Ke,"")}catch{}},A5=function(Ke){let Ut=null,sn=null;if(UC)Ke="<remove></remove>"+Ke;else{let ii=gQ(Ke,/^[\r\n\t ]+/);sn=ii&&ii[0]}wv==="application/xhtml+xml"&&fm===Oc&&(Ke='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ke+"</body></html>");let Ho=ie?ie.createHTML(Ke):Ke;if(fm===Oc)try{Ut=new b().parseFromString(Ho,wv)}catch{}if(!Ut||!Ut.documentElement){Ut=xe.createDocument(fm,"template",null);try{Ut.documentElement.innerHTML=VE?Ce:Ho}catch{}}let ja=Ut.body||Ut.documentElement;return Ke&&sn&&ja.insertBefore(r.createTextNode(sn),ja.childNodes[0]||null),fm===Oc?Oe.call(Ut,vd?"html":"body")[0]:vd?Ut.documentElement:ja},Av=function(Ke){return ke.call(Ke.ownerDocument||Ke,Ke,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},GE=function(Ke){return Ke instanceof u&&(typeof Ke.nodeName!="string"||typeof Ke.textContent!="string"||typeof Ke.removeChild!="function"||!(Ke.attributes instanceof g)||typeof Ke.removeAttribute!="function"||typeof Ke.setAttribute!="function"||typeof Ke.namespaceURI!="string"||typeof Ke.insertBefore!="function"||typeof Ke.hasChildNodes!="function")},M5=function(Ke){return typeof l=="function"&&Ke instanceof l};function xs(yn,Ke,Ut){TL(yn,sn=>{sn.call(o,Ke,Ut,gd)})}let zE=function(Ke){let Ut=null;if(xs(Ue.beforeSanitizeElements,Ke,null),GE(Ke))return Tl(Ke),!0;let sn=zi(Ke.nodeName);if(xs(Ue.uponSanitizeElement,Ke,{tagName:sn,allowedTags:Hr}),Rg&&Ke.hasChildNodes()&&!M5(Ke.firstElementChild)&&us(/<[/\w!]/g,Ke.innerHTML)&&us(/<[/\w!]/g,Ke.textContent)||Ke.nodeType===v3.progressingInstruction||Rg&&Ke.nodeType===v3.comment&&us(/<[/\w]/g,Ke.data))return Tl(Ke),!0;if(!(hi.tagCheck instanceof Function&&hi.tagCheck(sn))&&(!Hr[sn]||Mn[sn])){if(!Mn[sn]&&Eh(sn)&&(Xr.tagNameCheck instanceof RegExp&&us(Xr.tagNameCheck,sn)||Xr.tagNameCheck instanceof Function&&Xr.tagNameCheck(sn)))return!1;if(_h&&!xi[sn]){let Ho=fe(Ke)||Ke.parentNode,ja=ae(Ke)||Ke.childNodes;if(ja&&Ho){let ii=ja.length;for(let dl=ii-1;dl>=0;--dl){let Ks=M(ja[dl],!0);Ks.__removalCount=(Ke.__removalCount||0)+1,Ho.insertBefore(Ks,q(Ke))}}}return Tl(Ke),!0}return Ke instanceof s&&!Ih(Ke)||(sn==="noscript"||sn==="noembed"||sn==="noframes")&&us(/<\/no(script|embed|frames)/i,Ke.innerHTML)?(Tl(Ke),!0):(um&&Ke.nodeType===v3.text&&(Ut=Ke.textContent,TL([ze,Ge,$r],Ho=>{Ut=c3(Ut,Ho," ")}),Ke.textContent!==Ut&&(s3(o.removed,{element:Ke.cloneNode()}),Ke.textContent=Ut)),xs(Ue.afterSanitizeElements,Ke,null),!1)},$C=function(Ke,Ut,sn){if(VC&&(Ut==="id"||Ut==="name")&&(sn in r||sn in O5))return!1;if(!(aa&&!un[Ut]&&us(et,Ut))){if(!(Po&&us(Tt,Ut))){if(!(hi.attributeCheck instanceof Function&&hi.attributeCheck(Ut,Ke))){if(!Zn[Ut]||un[Ut]){if(!(Eh(Ke)&&(Xr.tagNameCheck instanceof RegExp&&us(Xr.tagNameCheck,Ke)||Xr.tagNameCheck instanceof Function&&Xr.tagNameCheck(Ke))&&(Xr.attributeNameCheck instanceof RegExp&&us(Xr.attributeNameCheck,Ut)||Xr.attributeNameCheck instanceof Function&&Xr.attributeNameCheck(Ut,Ke))||Ut==="is"&&Xr.allowCustomizedBuiltInElements&&(Xr.tagNameCheck instanceof RegExp&&us(Xr.tagNameCheck,sn)||Xr.tagNameCheck instanceof Function&&Xr.tagNameCheck(sn))))return!1}else if(!BC[Ut]){if(!us(lr,c3(sn,$t,""))){if(!((Ut==="src"||Ut==="xlink:href"||Ut==="href")&&Ke!=="script"&&mWe(sn,"data:")===0&&bh[Ke])){if(!(md&&!us(Xe,c3(sn,$t,"")))){if(sn)return!1}}}}}}}return!0},Eh=function(Ke){return Ke!=="annotation-xml"&&gQ(Ke,rn)},ud=function(Ke){xs(Ue.beforeSanitizeAttributes,Ke,null);let{attributes:Ut}=Ke;if(!Ut||GE(Ke))return;let sn={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Zn,forceKeepAttr:void 0},Ho=Ut.length;for(;Ho--;){let ja=Ut[Ho],{name:ii,namespaceURI:dl,value:Ks}=ja,Ac=zi(ii),pd=Ks,Wi=ii==="value"?pd:vWe(pd);if(sn.attrName=Ac,sn.attrValue=Wi,sn.keepAttr=!0,sn.forceKeepAttr=void 0,xs(Ue.uponSanitizeAttribute,Ke,sn),Wi=sn.attrValue,LE&&(Ac==="id"||Ac==="name")&&(Ov(ii,Ke),Wi=XV+Wi),Rg&&us(/((--!?|])>)|<\/(style|title|textarea)/i,Wi)){Ov(ii,Ke);continue}if(Ac==="attributename"&&gQ(Wi,"href")){Ov(ii,Ke);continue}if(sn.forceKeepAttr)continue;if(!sn.keepAttr){Ov(ii,Ke);continue}if(!FC&&us(/\/>/i,Wi)){Ov(ii,Ke);continue}um&&TL([ze,Ge,$r],WE=>{Wi=c3(Wi,WE," ")});let R5=zi(Ke.nodeName);if(!$C(R5,Ac,Wi)){Ov(ii,Ke);continue}if(ie&&typeof E=="object"&&typeof E.getAttributeType=="function"&&!dl)switch(E.getAttributeType(R5,Ac)){case"TrustedHTML":{Wi=ie.createHTML(Wi);break}case"TrustedScriptURL":{Wi=ie.createScriptURL(Wi);break}}if(Wi!==pd)try{dl?Ke.setAttributeNS(dl,ii,Wi):Ke.setAttribute(ii,Wi),GE(Ke)?Tl(Ke):v_e(o.removed)}catch{Ov(ii,Ke)}}xs(Ue.afterSanitizeAttributes,Ke,null)},P5=function yn(Ke){let Ut=null,sn=Av(Ke);for(xs(Ue.beforeSanitizeShadowDOM,Ke,null);Ut=sn.nextNode();)xs(Ue.uponSanitizeShadowNode,Ut,null),zE(Ut),ud(Ut),Ut.content instanceof i&&yn(Ut.content);xs(Ue.afterSanitizeShadowDOM,Ke,null)};return o.sanitize=function(yn){let Ke=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ut=null,sn=null,Ho=null,ja=null;if(VE=!yn,VE&&(yn="<!-->"),typeof yn!="string"&&!M5(yn))if(typeof yn.toString=="function"){if(yn=yn.toString(),typeof yn!="string")throw d3("dirty is not a string, aborting")}else throw d3("toString is not a function");if(!o.isSupported)return yn;if(LC||jC(Ke),o.removed=[],typeof yn=="string"&&(Tv=!1),Tv){if(yn.nodeName){let Ks=zi(yn.nodeName);if(!Hr[Ks]||Mn[Ks])throw d3("root node is forbidden and cannot be sanitized in-place")}}else if(yn instanceof l)Ut=A5("<!---->"),sn=Ut.ownerDocument.importNode(yn,!0),sn.nodeType===v3.element&&sn.nodeName==="BODY"||sn.nodeName==="HTML"?Ut=sn:Ut.appendChild(sn);else{if(!Ng&&!um&&!vd&&yn.indexOf("<")===-1)return ie&&Ch?ie.createHTML(yn):yn;if(Ut=A5(yn),!Ut)return Ng?null:Ch?Ce:""}Ut&&UC&&Tl(Ut.firstChild);let ii=Av(Tv?yn:Ut);for(;Ho=ii.nextNode();)zE(Ho),ud(Ho),Ho.content instanceof i&&P5(Ho.content);if(Tv)return yn;if(Ng){if(fh)for(ja=ye.call(Ut.ownerDocument);Ut.firstChild;)ja.appendChild(Ut.firstChild);else ja=Ut;return(Zn.shadowroot||Zn.shadowrootmode)&&(ja=Ne.call(e,ja,!0)),ja}let dl=vd?Ut.outerHTML:Ut.innerHTML;return vd&&Hr["!doctype"]&&Ut.ownerDocument&&Ut.ownerDocument.doctype&&Ut.ownerDocument.doctype.name&&us(S_e,Ut.ownerDocument.doctype.name)&&(dl="<!DOCTYPE "+Ut.ownerDocument.doctype.name+`>
222
- `+dl),um&&TL([ze,Ge,$r],Ks=>{dl=c3(dl,Ks," ")}),ie&&Ch?ie.createHTML(dl):dl},o.setConfig=function(){let yn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};jC(yn),LC=!0},o.clearConfig=function(){gd=null,LC=!1},o.isValidAttribute=function(yn,Ke,Ut){gd||jC({});let sn=zi(yn),Ho=zi(Ke);return $C(sn,Ho,Ut)},o.addHook=function(yn,Ke){typeof Ke=="function"&&s3(Ue[yn],Ke)},o.removeHook=function(yn,Ke){if(Ke!==void 0){let Ut=cWe(Ue[yn],Ke);return Ut===-1?void 0:dWe(Ue[yn],Ut,1)[0]}return v_e(Ue[yn])},o.removeHooks=function(yn){Ue[yn]=[]},o.removeAllHooks=function(){Ue=C_e()},o}var g3=y_e();var x_e={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Be=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new it,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new it,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new ur),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),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.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let s=[];return l.forEach(d=>{if(!Co(d))if(d instanceof HTMLElement){if(d.className.includes("cdk-overlay-container")||d.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(d.className.includes("cdk-overlay")){let g=!1;d.childNodes.forEach(u=>{Co(u)&&(g=!0)}),g||s.push(d)}else s.push(d)}else s.push(d)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Nr(),on(([s,d])=>{try{let g=d.filter(b=>!s.includes(b)),u=s.filter(b=>!d.includes(b));u.length&&u.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),g.length&&g.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",A=>{let M=this.calculateScreenSize();this.currentScreenSize$.next(M)})})}catch(g){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",g)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?ohe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):ihe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(l){this.loggingService.catch("Error in DomService constructor: ",l)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}setDynamicIdPatterns(e){try{let t=e.map(i=>typeof i=="string"?new RegExp(i):i).filter(Boolean);t.length&&(this.dynamicIdPatterns=t)}catch(t){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",t)}}isLikelyDynamicId(e){try{return e?this.dynamicIdPatterns.some(t=>t.test(e)):!1}catch{return!1}}getStableAttributes(e){try{let t={};if(!e.getAttributeNames)return t;let i=new Set(["id","class","style"]);return e.getAttributeNames().forEach(l=>{if(i.has(l)||l.includes("snippyly")||l.includes("velt"))return;let s=e.getAttribute(l);s&&s.length<=256&&(t[l]=s)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],l=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((d,g)=>{let u=l.findIndex(E=>d.startsWith(E)),b=l.findIndex(E=>g.startsWith(E));return(u===-1?99:u)-(b===-1?99:b)}).slice(0,4).forEach(d=>{let g=CSS.escape(t[d]);a.push(`[${d}="${g}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,s=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),s++,s>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return Wpe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],s=e,d=0;for(;s&&s!==document.documentElement&&d<i;){let E=this.buildRobustXPathSegment(s);if(E&&(l.unshift(E),this.isStrongAnchorSegment(E)))break;s=s.parentElement,d++}if(l.length===0)return;let u=(a?"/":"//")+l.join("/");return l.some(E=>E.includes("[@")||E.includes("[contains(@class"))?u:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),i=e.id;if(i&&!this.isLikelyDynamicId(i)&&document.querySelectorAll(`[id="${CSS.escape(i)}"]`).length===1)return`*[@id=${this.escapeXPathValue(i)}]`;let a=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let E of a){let A=e.getAttribute(E);if(A)return`${t}[@${E}=${this.escapeXPathValue(A)}]`}let l=Array.from(e.attributes).filter(E=>E.name.startsWith("data-")&&!E.name.includes("snippyly")&&!E.name.includes("velt")&&E.value.length<100).sort((E,A)=>E.value.length-A.value.length);if(l.length>0){let E=l[0];return`${t}[@${E.name}=${this.escapeXPathValue(E.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let g=e.getAttribute("name");if(g)return`${t}[@name=${this.escapeXPathValue(g)}]`;let u=e.getAttribute("type");if(u)return`${t}[@type=${this.escapeXPathValue(u)}]`;let b=Array.from(e.classList||[]).filter(E=>E.length>0&&E.length<40&&!E.includes("yui")&&!E.includes("velt")&&!E.includes("snippyly")&&!this.excludeClassList.includes(E)).slice(0,2);if(b.length>0){let E=b.map(A=>`contains(@class, ${this.escapeXPathValue(A)})`).join(" and ");return`${t}[${E}]`}if(e.parentElement){let E=Array.from(e.parentElement.children).filter(A=>A.tagName===e.tagName);if(E.length>1){let A=E.indexOf(e)+1;return`${t}[${A}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(e.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(a=>e.includes(`[@role='${a}']`))||["data-region","data-instanceid","data-activityid"].some(a=>e.includes(`[@${a}=`)))}catch{return!1}}escapeXPathValue(e,t=!0){try{return e.includes("'")?e.includes('"')?`concat(${e.split("'").map(l=>`'${l}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(s=>`'${s}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(e){try{let t=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),i=[];for(let a=0;a<t.snapshotLength;a++){let l=t.snapshotItem(a);l instanceof Element&&i.push(l)}return i}catch{return[]}}generateAnchorRecord(e,t){try{let i=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Zr(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),i&&a){let l=this.generateAnchorRecordForElement(a,t);l&&(i.parent=l)}return i}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",i),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let i=e,a=i.tagName?.toUpperCase();if(!a)return null;let l=i.id&&!this.isLikelyDynamicId(i.id)?i.id:void 0,s=this.getStableAttributes(i),d=this.buildStableElementSelector(i,s),g=this.getVisibleText(i),u=this.hashText(g||""),b=this.generateRobustXPath(i),E=this.getXPath(i),A=this.getXPath(i,!0),M=this.getXPath(i,!0,!0);return{version:"1.0",id:l,tagName:a,elementSelector:d,robustXPath:b||void 0,xPath:E||void 0,fXPath:A||void 0,cfXPath:M||void 0,contentHash:u?{value:u,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",i),null}}resolveAnchorRecord(e){try{let t=[],i=null,a=(u,b,E=0)=>{let A=[],M=E;if(A.push({method:b,score:E}),e.tagName&&u.tagName?.toUpperCase()===e.tagName&&(M+=10,A.push({method:"tagName-match",score:10})),e.contentHash?.value){let V=this.getVisibleText(u);this.hashText(V)===e.contentHash.value&&(M+=30,A.push({method:"contentHash-match",score:30}))}t.push({el:u,score:M,by:b,scoreBreakdown:A})};if(e.id){let u=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(u.length===1)return{element:u[0],matchedBy:"id",score:90};u.length>1&&u.forEach(b=>a(b,"id-duplicate",70))}if(e.elementSelector){let u=document.querySelectorAll(e.elementSelector);if(u.length===1)return{element:u[0],matchedBy:"element-selector",score:80};u.forEach(b=>a(b,"element-selector-duplicate",60))}e.robustXPath&&this.getAllElementsFromRobustXPath(e.robustXPath).slice(0,20).forEach(A=>a(A,"robustXPath",50)),e?.parent&&(i=this.resolveAnchorRecord(e.parent),i.element&&i.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(b=>a(b,"parent+tag",40)));let l=(u,b,E)=>{if(!u)return;let A=this.getElementFromXPath(u);A&&a(A,b||"xpath",E||30)};if(l(e.xPath,"xPath",30),l(e.cfXPath,"cfXPath",30),l(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let b=E=>{let A=0;for(let M=0;M<E.length&&A<400;M++){let V=E[M];if(A++,!this.isElementVisible(V))continue;let q=this.getVisibleText(V),ae=this.hashText(q);ae&&ae===e.contentHash?.value&&a(V,"contentHash",15)}};if(i?.element&&i?.element instanceof Element){let E=i?.element?.querySelectorAll("*");b(E)}}if(!t.length)return{element:null};t.sort((u,b)=>b.score-u.score);let s=t[0].score,d=t.filter(u=>u.score===s);if(d.length>1){let u=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let b of u)if(b.path){let E=this.getElementFromXPath(b.path);if(E){let A=d.find(M=>M.el===E);if(A)return{element:A.el,matchedBy:`${A.by}+position`,score:A.score,scoreBreakdown:A.scoreBreakdown}}}}let g=t[0];return{element:g.el,matchedBy:g.by,score:g.score,scoreBreakdown:g.scoreBreakdown}}catch(t){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",t),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ue(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.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.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),this.onDocumentClick()}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(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}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.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let i=t.filter(a=>a.type==="childList").filter(a=>{let l=a.target;return a.removedNodes.forEach(s=>{let d=s;if(typeof d.getAttribute=="function"){let g=d.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(g!==null&&g!==""){let u=this.xpathCacheId.get(g);u!==void 0&&(this.xpathCacheId.delete(g),this.xpathCache.delete(u))}}}),Co(l)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(i.filter(a=>!this.isAnimatingElement(a.target))):this.childListMutation$.next(i),i.push(...t.filter(a=>a.type==="attributes").filter(a=>!Co(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let l=a.target;return l?.classList?.contains("snippyly-sidebar-panel")?!1:l?!l.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),i=i.filter(a=>{let l=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(s=>{a.target?.closest(s)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Zr(a.target)),this.animationFilterEnabled&&(i=i.filter(a=>!this.isAnimatingElement(a.target))),i.length&&this.mutation$.next(i)}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let e=window;return e.gsap||e.TweenMax||e.TweenLite||e.TimelineMax||e.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):e.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):e.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):e.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):e.lottie||e.Lottie||e.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(e){try{if(!e||typeof e.closest!="function")return!1;let t=window;if(t.gsap&&typeof t.gsap.isTweening=="function"){if(t.gsap.isTweening(e))return!0;if(typeof t.gsap.getTweensOf=="function")try{if(t.gsap.getTweensOf(e).length>0)return!0}catch{}}else if(t.TweenMax&&typeof t.TweenMax.isTweening=="function"){if(t.TweenMax.isTweening(e))return!0;if(typeof t.TweenMax.getTweensOf=="function")try{if(t.TweenMax.getTweensOf(e).length>0)return!0}catch{}}let i=e.style?.cssText||"";if(i){let d=i.includes("transform")||i.includes("translate3d")||i.includes("translate(")||i.includes("scale3d")||i.includes("rotate"),g=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(g||u))return!0}if(e.style&&(e.style.animation!==""&&e.style.animation!=="none"||e.style.transition!==""&&e.style.transition!=="none")||e.classList?.contains("animate")||e.classList?.contains("animating")||e.classList?.contains("animated")||e.classList?.contains("animation"))return!0;let a=this.staticAnimationCache.get(e);if(a!==void 0)return a;let l=!1,s=e.className||"";return typeof s=="string"&&(s.includes("slider")&&(s.includes("bullet")||s.includes("pagination"))&&(l=!0),s.includes("swiper-pagination")&&(l=!0)),!l&&(e.hasAttribute("data-aos")||e.hasAttribute("data-motion"))&&(l=!0),!l&&e.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(l=!0),this.staticAnimationCache.set(e,l),l}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{Ro(Or(window,"offline").pipe(ue(()=>!1)),Or(window,"online").pipe(ue(()=>!0)),new Gt(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 t=this.calculateScreenSize();this.deviceInfo$.next(new ur),this.currentScreenSize$.next(t)})}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 t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}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 Or(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Mc}}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 t=this.getXPath(e.target),i=e.target;if(t?.includes("name()='svg'")){let u=this.getXPath(t);u&&(i=u.iterateNext()||e.target)}let a=i.getBoundingClientRect(),l=e.clientX-a.x,s=e.clientY-a.y,d=l*100/(a.width||1),g=s*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:g,leftPercentage:d}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,i=!1,a=!0,l,s=!0,d){try{let g=e,u=g?.touches?.length?g.touches[0]?.clientX:g?.clientX,b=g?.touches?.length?g.touches[0]?.clientY:g?.clientY;d&&(u=d.clientX,b=d.clientY);let E=this.getBackgroundElement(u,b,t,i);if(E&&l&&typeof l=="function"&&(E=l(E)),E){let A=this.getXPath(E),M=this.getXPath(E,!0),V=E.getBoundingClientRect(),q=u-V.x,ae=b-V.y,fe=q*100/(V.width||1),ie=ae*100/(V.height||1),Ce={xpath:A,fXpath:M,leftPercentage:fe,topPercentage:ie};if(a){let xe=this.getXPath(E,!0,!0);Ce.cfXpath=xe}if(s){let xe=this.generateAnchorRecord(E);xe&&(Ce.anchor=xe)}return Ce}else return null}catch(g){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",g),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),s=[];l.forEach(g=>{Co(g)?s=[]:Zr(g)&&s.push(g)}),a&&(s=s.filter(g=>this.isElementVisibleOnScreen(g)));let d=0;return i||s?.forEach((g,u)=>{g.tagName.toLowerCase()==="svg"&&(d=u)}),s[d]}catch(l){return this.loggingService.catch("Error in DomService getBackgroundElement: ",l),null}}getBackgroundVeltElement(e,t){try{let i=document.elementsFromPoint(e,t),a=[];return i.forEach(l=>{Co(l)&&Zr(l)&&a.push(l)}),a[0]}catch(i){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",i),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(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}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(),t=this.currentMousePosition?.pageX||e.x+200,i=Math.min(t,e.width/2),a=Math.abs(e.y),l=e.y-20;return a>50&&(l=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(i),this.loggingService.log(l),{topPositionX:i,topPositionY:l}}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,t,i){if(e){if(!i&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),l=e.style.getPropertyPriority("cursor"),s=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,s?JSON.stringify(s):""),e.style.setProperty("cursor",t,"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 t=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,i,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"),t&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,t),i&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,i))}catch(l){this.loggingService.catch("Error in DomService highlightUserElement: ",l)}}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(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,i=!1,a){try{let l=this.calculateXPath(e,t,i,a);if(l&&typeof l=="string"&&l.includes("/svg")){let s=l.split("/"),d=!1;s.forEach((g,u)=>{g.includes("svg")&&(d=!0),d&&(s[u]="svg:"+g)}),l=s.join("/")}return l}catch(l){this.loggingService.catch("Error in DomService getXPath:",l)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,i,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&&!t)return"//*[@id='"+e.id+"']";if(i&&e.className&&e.className.split){let s=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(s){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),g=Array.from(e.parentNode?.children||[]).filter(u=>u.nodeType===1&&u.tagName===e.tagName?u.className?.split(" ")?.filter(E=>E?.includes("snippyly")||E?.includes("velt")||["show-pin-cursor"].includes(E))[0]===s:!1);if(g.length>1){let u=g.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(s){return s.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,i)+"/"+e.tagName.toLowerCase()+(l.length>1?"["+([].indexOf.call(l,e)+1)+"]":"")}}catch(l){this.loggingService.catch("Error in DomService calculateXPath:",l)}}getElementFromXPath(e,t=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 i=this.getXPath(e,!1,!1,t);if(i){let a=i?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let l=ot();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,l),this.xpathCacheId.set(l,e)}return this.xpathCache.set(e,a),a}return null}catch(i){return this.loggingService.catch("Error in DomService getElementFromXPath:",i),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let i=this.resolveAnchorRecord(e.anchor);i?.element&&(t=i.element)}else e?.xpath?t=this.getElementFromXPath(e.xpath):e?.cfXpath?t=this.getElementFromXPath(e.cfXpath):e?.fXpath&&(t=this.getElementFromXPath(e.fXpath));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",t),null}}getElementFromTargetTextRange(e){try{let t=null;if(e?.commonAncestorContainerAnchor){let i=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);i?.element&&(t=i.element)}else e?.commonAncestorContainer&&(t=this.getElementFromXPath(e.commonAncestorContainer));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",t),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],t=[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 i=new r3;return i.screenWidth=Math.max(...t),i.screenHeight=Math.max(...e),i.screenScrollHeight=this.pageScrollHeight,i}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new r3}}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 i=new DOMParser().parseFromString(e,"text/html");i.querySelectorAll("[data-snippyly-cache-id]").forEach(b=>{b.removeAttribute("data-snippyly-cache-id")}),i.querySelectorAll("[data-velt-cache-id]").forEach(b=>{b.removeAttribute("data-velt-cache-id")}),i.querySelectorAll(".comment-text-highlight").forEach(b=>{b?.parentNode?.insertBefore(document.createTextNode(b?.textContent),b),b.remove()});let d=document.createNodeIterator(i,NodeFilter.SHOW_COMMENT),g;for(;g=d.nextNode();)g?.remove();return this.mergeAdjacentTextNodes(i.body),this.sanitizeHtml(i.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let i=t.nextSibling;for(;i&&i.nodeType===Node.TEXT_NODE;)t.textContent+=i.textContent,i.remove(),i=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let i=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(i,this.pageScrollHeight),this.nodeMap[i]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let i=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];i.push(...a),i=Array.from(new Set(i));let l=i.map(u=>u.classList.contains("velt-annotation-draft-checked")?(u.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(u,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(u,"velt-comment-dialog-shake"),u.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||u.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(u,"velt-annotation-draft-checked")},100),u.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(u=>u),s=Object.keys(this.getRecordingInProgress()||{});l=[...l,...s];let d=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let u=[];Object.keys(d).forEach(b=>{if(d[b]?.type==="tag"){let E=d[b];E?.to?.length||l.includes(b)||u.push(E)}else d[b]?.comments?.length||l.includes(b)||u.push(d[b])}),this.deleteAnnotations$.next(u),this.deleteAnnotations$.next([])}let g={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(g[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(g[u]=d[u]);break;default:d[u]?.type!==t&&(g[u]=d[u]);break}}),Object.keys(g).forEach(u=>{let b=g[u]?.multiThreadAnnotationId;b&&!g[b]&&(g[b]={annotationId:b,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(g)&&this.selectedAnnotationsMap$.next(g),this.setDialogOpenedInSidebar(!1)}catch(i){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",i)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(k(f({},this.recordingInProgress$.value),{[e]:t}));else{let i=this.recordingInProgress$.value;delete i[e],this.recordingInProgress$.next(i)}}catch(i){this.loggingService.catch("Error in DomService setRecordingInProgress: ",i)}}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=[],t=Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),i=Array.from(document.querySelectorAll(`${U.TAGS.VELT_COMMENT_DIALOG}`));return[...t,...i].forEach(l=>{if(l?.shadowRoot){let s=l.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=l.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(s?.shadowRoot){let d=s.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}else{let d=l.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let i={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(i[a]=t[a]);break;default:t[a].type===e&&(i[a]=t[a]);break}}),i}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ue(t=>{if(e){let i={};return Object.keys(t).forEach(a=>{t[a].type===e&&(i[a]=t[a])}),i}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ue(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,t,i,a=!1,l){try{i==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));s[e.annotationId]&&!a?delete s[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(s[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(s),Object.keys(d).forEach(g=>{s[g]||delete d[g]}),this.selectedAnnotationsLocationMap$.next(d)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,t){try{let i=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));i?.[e]!==t&&(i[e]=t,this.selectedAnnotationsLocationMap$.next(i))}catch(i){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",i)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(i=>{t[i.annotationId]&&(t[i.annotationId]=i)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),le([])}}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(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),le([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let i={offsetTop:0,offsetLeft:0},a=e;if(a===t){let l=window.getComputedStyle(e);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(i.offsetLeft=e?.offsetLeft||0,i.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let s=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let g=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-g.left,i.offsetTop+=u.top-g.top}}else s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let d=window.getComputedStyle(a);d.position==="static"&&d.transformStyle!="preserve-3d"&&d.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0)}}else{let s=window.getComputedStyle(a);s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop)}return i}catch(i){return this.loggingService.catch("Error in DomService getElementOffset: ",i),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:i,top:a,bottom:l}=e?.getBoundingClientRect();return t>0||i>0||a<window.innerHeight&&l>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,i=window.getComputedStyle(t);return!(i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Gt(e=>{let t=Or(document,"mousedown").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=Or(document,"mousemove").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=Or(document,"mouseup").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),s=t.pipe(_e(d=>i.pipe(Nr(),ue(([g,u])=>({startPoint:d,prevPoint:g,curPoint:u})),zo(a)))).subscribe(e);return()=>s.unsubscribe()})}drawRectangle(e,t){let i=document.querySelector(".rectangle");i||(i=document.createElement("div"),this.addClassToElement(i,"rectangle"),i.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),i.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(i));let a=Math.abs(t.x-e.x),l=Math.abs(t.y-e.y),s=Math.min(e.x,t.x),d=Math.min(e.y,t.y);return i.style.width=`${a}px`,i.style.height=`${l}px`,i.style.left=`${s}px`,i.style.top=`${d}px`,i.style.position="absolute",i.style.border="2px dashed #f00",i.style.pointerEvents="none",i.style.zIndex="2147483577",i}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 t={},i=e.commonAncestorContainer;i?.nodeType===Node.TEXT_NODE&&(i=i.parentElement);let a=document.body;if(i){let s=this.getTextXPath(i);this.isXpathWithId(s)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let s=this.getElementFromXPath(t.commonAncestorContainer);if(s){t.commonAncestorContainerFXpath=this.getXPath(s,!0),t.commonAncestorContainerCFXpath=this.getXPath(s,!0,!0);let d=this.generateAnchorRecord(s);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=a0(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,i=e.previousSibling;for(;i;)i.nodeType===Node.TEXT_NODE&&t++,i=i.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let i=e?.closest("picture");return i?i?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,elementQuerySelectors:i}){try{let a=[];if(e?.length)for(let l=0;l<e.length;l++){let s=document.getElementById(e[l]);s&&a.push(s)}if(t?.length)for(let l=0;l<t.length;l++){let s=document.getElementsByClassName(t[l]);for(let d=0;d<s.length;d++){let g=s[d];g&&g instanceof HTMLElement&&a.push(g)}}if(i?.length)for(let l=0;l<i.length;l++){let s=document.querySelectorAll(i[l]);for(let d=0;d<s.length;d++){let g=s[d];g&&g instanceof HTMLElement&&a.push(g)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementById(t[i]);if(a&&a.contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",i),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementsByClassName(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",i),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.querySelectorAll(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",i),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(i){this.loggingService.catch("Error in DomService addClassToElement: ",i)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(i){this.loggingService.catch("Error in DomService removeClassFromElement: ",i)}}isElementInsideParentWithAttribute(e,t,i){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===i)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(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}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(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}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),le(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let i=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(i&&i.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.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(t?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let i=t.innerHTML;return i=i.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),i}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(l){return i.test(l.innerHTML)};var t=a;let i=/^\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(i){this.loggingService.catch("Error in DomService removeEmptyElements: ",i)}}normalizeWhitespace(e){try{e.childNodes.forEach(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),g3.sanitize(e,x_e)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return g3.sanitize(e,x_e)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ur;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),le(new ur)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID);!e&&this.tabId&&(e=this.tabId,sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e)),!this.tabId&&e&&(this.tabId=e);let t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=ot(),this.tabId=e,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(t){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",t)}}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 ur}}isMobileDevice(){try{return new ur().getDeviceType()===Bi.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ur().getDeviceType()===Bi.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ur().getDeviceType()===Bi.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(i=>{t.setAttribute(i.nodeName,i.nodeValue)}),e.childNodes.forEach(i=>{i.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(i)):i.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(i.nodeValue))}),t}catch(i){return this.loggingService.catch("Error in DomService deepCloneElement: ",i),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(i=>{if(this.removeWireframeSuffixFromTags(i),i.tagName.toLowerCase().endsWith("-wireframe")){let a=i.tagName.toLowerCase().replace("-wireframe",""),l=document.createElement(a);for(Array.from(i.attributes).forEach(s=>{l.setAttribute(s.name,s.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new ur().getDeviceType()===Bi.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(X(lt),X(ki),X(x),X(Rd))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var We=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=s,this.analyticsService=d,this.loggingService=g,this.user$=new Se(null),this.userOptions$=new Se(null),this.userContacts$=new Se(null),this.userOrganization$=new Se(null),this.isPrivateCommentsEnabled$=new Se(!1),this.providedUser=new ra,this.firebaseConfig$=new Se(null),this.advancedQueries$=new Se(null),this.planDetails$=new Se(null),this.signOutPreviousUser$=new Se(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.onRetrySubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{try{let u=this.configService.getAuthProxyHost();if(u){let b=this.afAuth?.config;b&&(b.apiHost=u,b.tokenApiHost=u)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(u=>{this.config=u}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=fr(this.afAuth).pipe(yo(this.afAuth.currentUser),Nr(),_e(([u,b])=>this.domService.onNetworkStatusChange$().pipe($e(E=>E),ut(1),ue(()=>({previousUser:u,currentUser:b}))))).subscribe(E=>Q(this,[E],function*({previousUser:u,currentUser:b}){if(!b&&u){let A=u?.stsTokenManager?.expirationTime,M=new Date().getTime(),V=A-M;M>A&&(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&u?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(K.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:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),u=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",u)}),this.getUser$().pipe(xt(Jt)).subscribe(u=>{let b=Uo(u);this.coreActionsService.triggerAction(Qe.USER_UPDATE,b),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:Qe.USER_UPDATE,payload:{user:b}})})}catch(u){this.loggingService.catch("Error in AuthService constructor: ",u)}}setApiKey(e,t){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),t||(t=new gL),this.configService.initConfig(t);let i=this.configService.getProxyConfig();if(i?.authHost)try{let a=this.afAuth?.config;a&&(a.apiHost=i.authHost,a.tokenApiHost=i.authHost)}catch(a){this.loggingService.catch("Error setting auth proxy config: ",a)}t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||fr(this.afAuth).pipe(ut(1)).subscribe(a=>Q(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Hm(a,!0).catch(s=>null);if(l){let{user:s}=l?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?k(f({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(i){this.loggingService.catch("Error in setApiKey: ",i)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setActivityService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setActivityService","color: green;"),this.activityService=e}catch(t){this.loggingService.catch("Error in setActivityService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}setCrdtService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCrdtService","color: green;"),this.crdtService=e}catch(t){this.loggingService.catch("Error in setCrdtService: ",t)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(K.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")}setVeltAuthProvider(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;if(!e.user)return null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let i=yield eZ(()=>window.Velt.identify(e.user,f(f({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}).catch(a=>(e.onError&&typeof e.onError=="function"&&e.onError(a),Promise.reject(a))),e.retryConfig||{retryCount:0,retryDelay:0});return i&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(Qe.ERROR).pipe($e(a=>a.code==="token_expired"),ut(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(E=>({id:E.clientDocumentId}))??[],s=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],g=this.docService?.getLocation();g&&d.push(g.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(E=>{d.push(E.location)}),(yield eZ(()=>Q(this,null,function*(){try{let E=yield e.generateToken?.();return E?window.Velt.identify(e.user,f(f({},e.options||{}),E&&{authToken:E}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:l,options:s,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!g}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return Q(this,null,function*(){try{if(e){let t=yield hc(e,e?.userId??"");localStorage.setItem(U.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return Q(this,null,function*(){try{let t=localStorage.getItem(U.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield Q1(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}setIsPrivateCommentsEnabled(e){try{this.isPrivateCommentsEnabled$.next(e)}catch(t){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",t)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),i=yield this.getUserFromStorage(t);return!i||Object.keys(i).length===0?(delete t?.color,delete t?.textColor,t):(i?.color&&(t.color=i?.color),i?.textColor&&(t.textColor=i?.textColor),t)}catch(t){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",t),e}})}updateUserIfRequired(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let t=yield this.getUserFromStorage(e),i={};e.color&&e.color!==t?.color&&(i.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(i.textColor=e.textColor),Object.keys(i).length>0&&e.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:e.clientOrganizationId,user:k(f({},i),{userId:e.userId})})}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,i,a,l){return Q(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=Qc(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let s=yield fr(this.afAuth).pipe(ut(1)).toPromise().catch(g=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),s){let g=yield Hm(s,!0).catch(A=>null);if(!g)return;let{user:u,firebaseConfig:b,advancedQueries:E}=g.claims;s?.uid!==e?.userSnippylyId||e?.groupId!==u?.groupId||e?.organizationId!==u?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,b)||this.forceReLoginRequiredForCommentViews(e)?(localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal")):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(b),this.setAdvancedQueries(E),u&&(this.providedUser.isAdmin=!!u.isAdmin),this.initializeSignedInUser(s,a,e),d=!1,this.analyticsService.trackEvent(K.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:l}))}if(d){this.analyticsService.trackEvent(K.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:l},!0,e.userSnippylyId,e.userId);let g=Gr(this.functions,Wr({url:En.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=fa(),b=(yield g({apiKey:this.apiKey,user:e,version:u,authToken:t?.authToken}))?.data;if(b.error){if(this.analyticsService.trackEvent(K.Events.Core.SDK_VALIDATE_CLIENT_FAILED,k(f({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:b.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},b),{source:l}),!0,e.userSnippylyId,e.userId),b.error&&typeof b.error=="string")if(b.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let E={code:"token_expired",message:"Token expired",error:b?.error,source:b?.source};this.coreActionsService.triggerAction(Qe.ERROR,E)}else{let E={code:"too_many_retries",message:"Token expired. Too many retries.",error:b?.error,source:b?.source};this.coreActionsService.triggerAction(Qe.ERROR,E),this.analyticsService.trackEvent(K.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:l},!0,e.userSnippylyId,e.userId)}else{let E=b;this.coreActionsService.triggerAction(Qe.ERROR,E)}throw b}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(K.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:l},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),b.firebaseConfig){this.setFirebaseConfig(b.firebaseConfig),yield this.signInWithCustomToken(e,b.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let E=yield Hm(this.afAuth.currentUser,!0).catch(V=>null);if(!E)return;let{user:A,advancedQueries:M}=E.claims;this.setAdvancedQueries(M),this.providedUser.isAdmin=!!A?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:i,autoLogin:a},this.checkForPendingLogin()}return e}catch(s){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",s),t?.throwError?Promise.reject(s):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=fa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=fa();if(e){let t=e.split("."),i=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),l=parseInt(t[2]||"0");if(i>=4&&a>=5)return i===4&&a===5&&l===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),i=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(i=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),i=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(i=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",i),!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:f(f({},En.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}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(t){this.loggingService.catch("Error in setAdvancedQueries: ",t)}}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 pn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ue(()=>this.getAdvancedQueriesEnabled()),Jn(()=>le(!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;"),fr(this.afAuth).pipe(_e(e=>e?this.user$.asObservable():le(null)),xt(Jt))}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 t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=f(f({},this.providedUser),e),t){let i=f(f({},t),e);this.updateUserInternally(i)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,i="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return bde(this.afAuth,t).then(a=>(this.analyticsService.trackEvent(K.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(K.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,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)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.setIsPrivateCommentsEnabled(!1),this.activityService?.setActivityFeatureConfig({immutable:!1,isEnabled:!1})}catch(e){this.loggingService.catch("Error in clearCache: ",e)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),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,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new ra;a.userSnippylyId=e.uid,a.type="signedIn",i&&(a=f(f({},a),i)),this.setUserToStorage(a),this.mergeUserWithProvidedUserData(a,t)}catch(a){this.loggingService.catch("Error in initializeSignedInUser: ",a)}}mergeUserWithProvidedUserData(e,t){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let i=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=ot(),l=xc.IDENTIFY;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:gi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let s=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});s&&s[e.userId]&&(i=JSON.parse(JSON.stringify(s[e.userId]||{}))),e=f(f({},e),i||{})}e.name=i?i?.name:this.providedUser?.name||e.name,e.clientUserName=i?i?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=i?i?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=i?i?.email:this.providedUser?.email||e.email,e.color=i?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=i?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=i?.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(i){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",i)}})}updateUserInternally(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||this.getPlanDetailsFromDb();let i=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=_l({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let g=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:ro.IDENTIFY,organizationId:e.clientOrganizationId}}],u=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:g}}),l=this.userPermissionService?.onResourceAccessRequired({requests:g,uniqueId:u,userId:e.userId,methodName:ro.IDENTIFY,fromCache:!1})??Promise.resolve()}let[s,d]=yield Promise.allSettled([a,l]);s.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!s.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(s.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",s.reason),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),i=k(f({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return Q(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield Gr(this.functions,Wr({url:En.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:fa(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(K.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}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($e(e=>!!e),ue(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreSignOutFuction: ",i)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(_e(e=>e?this.userOrganization$.asObservable().pipe(ue(t=>t?.metadata?.organizationId===e.organizationId?t:null)):le(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(K.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 t=yield fr(this.afAuth).pipe(ut(1)).toPromise().catch(i=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[i,a]of this.preSignOutFunctions)try{yield a(t)}catch(l){this.loggingService.catch(`Error in signOutUser ${i} function: `,l)}return this.user$.next(null),yield Hu(1e3),Sde(this.afAuth).catch(i=>{this.loggingService.catch("Error in signOutUser:",i)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return Ao(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return Uo(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Qn(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(Ft),X(sv),X(tr),X(Be),X(Do),X(lt),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $n=(()=>{let o=class o{constructor(e,t,i){this.authService=e,this.configService=t,this.loggingService=i,this.db$=new Se(null);try{this.authService.getFirebaseConfig$().subscribe(a=>{if(a){let l=this.configService.getProxyConfig(),s=a.firebaseOptions.databaseURL;l?.v1DbHost&&s&&(s=kN(s,l.v1DbHost),l?.forceLongPolling&&Hq());let d=x1(void 0,s);l?.v1DbHost&&s&&this.lockDatabaseHost(d),this.db$.next(d)}},a=>{this.loggingService.catch("Error in DatabaseService constructor: ",a)})}catch(a){this.loggingService.catch("Error in DatabaseService constructor:",a)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(e){try{let i=e?._repo?.repoInfo_;if(i){let a=i.host;Object.defineProperty(i,"host",{get:()=>a,set:()=>{},configurable:!0}),i.internalHost=a}}catch(t){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",t)}}};o.\u0275fac=function(t){return new(t||o)(X(We),X(Ft),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var OL=class{};var rl=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=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 Se(null),this.commentAnnotationById$=new Se({}),this.fieldsToRemove=[],this.additionalFields=[],this.getCommentAnnotationById=a=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",l);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]))})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",a)}}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(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:e}}),b(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],V=k(f({},e),{commentAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.commentAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.commentAnnotationById$.next(f(f({},this.commentAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return Q(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 a=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=f(f({},l),e.commentAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return 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 s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let a=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let l=this.commentAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.commentAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:g,event:Io.COMMENT_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:g,event:Io.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:E,commentAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:s}}),{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()):le(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",t);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",e),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.commentAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=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 Se(null),this.reactionAnnotationById$=new Se({}),this.getReactionAnnotationById=a=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",l);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",a)}}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(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:e}}),b(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],V=k(f({},e),{reactionAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.reactionAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.reactionAnnotationById$.next(f(f({},this.reactionAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return Q(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 a=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=f(f({},l),e);let s={reactionAnnotation:e,event:Io.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Ai(()=>i?.config?.saveConfig?.url?ji(i.config.saveConfig.url,i.config.saveConfig.headers,s,!1):i?.save?.(s)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return d&&d.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(d?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:d,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:s.event}),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let a=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=t??l?.[e]?.metadata,d=s?ti(s):void 0,g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.reactionAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:g,event:Io.REACTION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:g,event:Io.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:E,reactionAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:s}}),{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()):le(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(a){this.loggingService.catch("Error in AttachmentResolverService constructor:",a)}}getProvider(e){try{let t=e||"default";return this.providers.get(t)||void 0}catch(t){this.loggingService.catch("Error in AttachmentResolverService getProvider:",t);return}}getRetrySaveConfig(e){let t=e||"default";return this.retrySaveConfigs.get(t)||this.defaultRetryConfig}getRetryDeleteConfig(e){let t=e||"default";return this.retryDeleteConfigs.get(t)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(e,t,i,a){return Q(this,null,function*(){try{let l=new FormData;l.append("file",i);let s={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(s));let d={};t&&Object.entries(t).forEach(([b,E])=>{b.toLowerCase()!=="content-type"&&(d[b]=E)});let g=yield fetch(e,{method:"POST",headers:d,body:l});return g.ok?{data:(yield g.json())?.data??{},success:!0,statusCode:200}:(at.catch(`Error in makeAttachmentConfigBasedRequest: ${g.status} ${g.statusText}`),{data:{},success:!1,statusCode:g.status})}catch(l){return at.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let a=this.getProvider(i);if(!this.attachmentDataProviderAvailable(i))throw new Error("Attachment save data provider not available");let l=this.getRetrySaveConfig(i),s=t||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Ai(()=>Q(this,null,function*(){if(a?.config?.saveConfig?.url){let g=e.attachment,{file:u}=g,b=Dh(g,["file"]);return this.makeAttachmentConfigBasedRequest(a.config.saveConfig.url,a.config.saveConfig.headers,u,{attachment:b,event:e.eventType,metadata:e.attachment.metadata})}return a?.save?.({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",l);if(d?.statusCode!==200){this.loggingService.catch(d?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{error:d,request:e}});return}return this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,s,d){return Q(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let g=this.getProvider(a);if(!this.attachmentDataProviderAvailable(a))throw new Error("Attachment delete data provider not available");let u=t?f({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0,b=this.getRetryDeleteConfig(a),E=i||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Ai(()=>{if(g?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE};return ji(g.config.deleteConfig.url,g.config.deleteConfig.headers,M,!1)}return g?.delete?.({attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",b);return A?.statusCode!==200?(this.loggingService.catch(A?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{error:A,attachmentId:e,metadata:u}}),{revertOnFailure:b.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:b.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:b.revertOnFailure,isSuccess:!0})}catch(g){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",g);let u=this.getRetryDeleteConfig(a),b=i||ot(),E=t?f({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0;return this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{error:g,attachmentId:e,metadata:E}}),{revertOnFailure:u.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e,t="default"){try{if(e){this.loggingService.log(`Setting attachment data provider for scope: ${t}`);let i=e.config,a=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],l=[];if(a.forEach(({method:s,configKey:d})=>{let g=i?.[d]?.url,u=s in e&&typeof e[s]=="function";!g&&!u&&l.push(s)}),l.length>0){let s=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(s);return}else this.providers.set(t,e),e.config?.saveRetryConfig&&this.retrySaveConfigs.set(t,e.config.saveRetryConfig),e.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(t,e.config.deleteRetryConfig)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(e){try{let t=e||"default";return this.providers.has(t)}catch(t){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",t),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ol=(()=>{let o=class o{constructor(e,t,i,a){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.attachmentResolverService=a,this.resolveTimeout=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.recorderAnnotationDataProvider$=new Se(null),this.recorderAnnotationById$=new Se({}),this.additionalFields=[],this.uploadChunks=!1,this.getRecorderAnnotationById=l=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[l]:void 0}catch(s){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",s);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(l=>{l&&(l.config?.resolveTimeout&&(this.resolveTimeout=l.config.resolveTimeout),l.config?.saveRetryConfig&&(this.retrySaveConfig=l.config.saveRetryConfig),l.config?.deleteRetryConfig&&(this.retryDeleteConfig=l.config.deleteRetryConfig),l.config?.getRetryConfig&&(this.retryGetConfig=l.config.getRetryConfig),l.config?.additionalFields&&(this.additionalFields=l.config.additionalFields||[]),this.uploadChunks=l.uploadChunks??!1)})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",l)}}getProvider(){try{let e=this.recorderAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",e)}}resolveRecorderAnnotations(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:e}}),b(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],V=k(f({},e),{recorderAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.recorderAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.recorderAnnotationById$.next(f(f({},this.recorderAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let i=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let a=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=f(f({},l),e.recorderAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(e.recorderAnnotation),eventType:e.eventType}),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let a=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let l=this.recorderAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.recorderAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:g,event:Io.RECORDER_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:g,event:Io.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:E,recorderAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",t);return}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting recorder annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else e.storage&&this.attachmentResolverService.setAttachmentDataProvider(e.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",t)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt),X(Gs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=s,this.commentResolverService=d,this.reactionResolverService=g,this.recorderResolverService=u,this.coreActionsService=b,this.functions=E,this.documentPaths$=new Se(null),this.docContext$=new Se(null),this.documentIds$=new Se([]),this.organizationConfig$=new Se(null),this.firestorePaths$=new Se(null),this.location$=new Se(null),this.excludedLocationIds$=new Se([]),this.organizationMetadata$=new Se(null),this.documentMetadata$=new Se(null),this.locationMetadata$=new Se(null),this.customerMetadata$=new Se(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Se({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Se({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new it,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(PB(()=>Js(this.currentDebounceTime))).subscribe({next:A=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(A.documentId,A.clientOrganizationId,A.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:A=>{this.loggingService.catch("Error in setDocumentId subscription:",A),this.queueSize--}}),this.databaseService.getDb().pipe($e(A=>!!A),ut(1)).subscribe(A=>{A&&(this.db=A)}),this.configService.getApiKey$().subscribe(A=>{if(this.apiKey=A,this.apiKey){if(!this.isCustomDocId){let M=AN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>Q(this,null,function*(){if(A&&(this.analyticsService.updateDefaultProperties({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&A?.organizationId&&this.documentPaths$.value?.organizationId!==A?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(M=>({id:M.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),A?.organizationId&&A?.clientOrganizationId)){let M={organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),yield this.updateOrganizationMetadata(M)}})),this.documentPaths$.subscribe(A=>{let M={documentId:A?.documentId,clientDocumentId:A?.clientDocumentId,folderId:A?.folderId,allDocuments:A?.allDocuments,veltFolderId:A?.veltFolderId};A?.organizationId&&(M.organizationId=A.organizationId,M.clientOrganizationId=A.clientOrganizationId),this.analyticsService.updateDefaultProperties(M),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(A=>{this.analyticsService.updateDefaultProperties({clientLocation:A?.location,locationId:A?.locationId})}),this.organizationMetadata$.subscribe(A=>{this.authService.setUserOrganization(A?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe($e(A=>!!A),ut(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(A){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}},A=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(A){this.loggingService.catch("Error in DocService constructor:",A)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(e=>({id:e.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setUsersService(e){try{this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService:",t)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=AN(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=AN(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(l){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:i,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:a,payload:{documentId:e,documentMetadata:t,options:i}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:f({organizationId:t?.organizationId},i??{}),source:a})}catch(s){this.loggingService.catch("Error in DocService setDocument:",s)}})}shouldSetDocumentsAgain(e,t={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&e.length===this.pendingDocumentIds.length&&e.every(u=>this.pendingDocumentIds.includes(u.id))&&Mr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(g=>g.clientDocumentId),s=ON(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(g=>l.includes(g.id))||!Mr(s,t)||i!==a}catch(i){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",i),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let i=[];return e.forEach(a=>{let l=a.id,s=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:s,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return Q(this,arguments,function*({documents:e,options:t,source:i="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(i){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:yl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(s=>s.clientDocumentId);if(!l.includes(e.id)){let s=[...l.map(g=>({id:g})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:s,setClientDocumentMetadataMap:!0});this.documentIds$.next(d)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocContext(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let t=JSON.parse(JSON.stringify(e??null));this.docContext$.next(t)}catch(t){this.loggingService.catch("Error in setDocContext: ",t)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(xt(Jt))}getProcessedDocContext(){return Che(this.getDocContext())}filterRelevantDocuments(a){return Q(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:i=!1}){try{let l=this.authService.getUser();return!l||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,l),yield this.handlePermissionProvider(e,t,l),t=yield this.filterDocumentsByPermissions(e,t,l,i),t=t.slice(0,50)),t}catch(l){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",l),t}})}fetchDocumentsFromFolder(e,t,i){return Q(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield _l({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(s=>{t.find(d=>d.clientDocumentId===s.id)||t.push({documentId:mi(s.id),clientDocumentId:s.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,i){try{let a=[];return e.organizationId&&e.organizationId!==i.clientOrganizationId&&a.push({userId:i.userId,resource:{id:e.organizationId,type:oa.ORGANIZATION,source:ro.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}}),t&&t.forEach(l=>{a.push({userId:i.userId,resource:{id:l.clientDocumentId,type:oa.DOCUMENT,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&FN({input:e?.context}).forEach(s=>{let d=JSON.stringify(s.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:s}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let i=e.data.filter(a=>a.type===oa.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(i??"nil"))),i?.length){let a=t.filter(s=>i.includes(s.resource.id)).map(s=>s.resource.context).filter(s=>!!s),l=_he({input:a});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(l??"nil"))),l?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(l??"nil"))),this.setDocContext(l))}}catch(i){this.loggingService.catch("Error in processAccessibleContexts:",i)}}handlePermissionProvider(e,t,i){return Q(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil")));let a=this.buildPermissionRequests(e,t,i),l=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let s=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:ro.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(s??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(s,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return Q(this,null,function*(){if(a)return t;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil"))),!(e?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(e,t,i);let s=this.currentValidationToken,d=[...t];return s&&this.validatePermissionsInBackground(e,t,i,s),d})}validateAndFilterPermissions(e,t,i){return Q(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(g=>g.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),e?.folderId&&l?.[i.userId]?.folders?.[e?.folderId]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let s=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([g,u])=>{u?.errorCode===_o.PERMISSION_DENIED&&s.add(g)}),s.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...s].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...s],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(g=>!s.has(g.clientDocumentId));return d.length===0&&t.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),d}catch(a){return this.loggingService.catch("Error in validateAndFilterPermissions:",a),t}})}validatePermissionsInBackground(e,t,i,a){let l=e?.organizationId??i?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:l,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let d=[];Object.entries(s?.[i.userId]?.documents??{}).forEach(([g,u])=>{u?.errorCode===_o.PERMISSION_DENIED&&d.push(g)}),l&&s?.[i.userId]?.organization?.[l]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&s?.[i.userId]?.folders?.[e?.folderId]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0),d.length>0&&(this.loggingService.catch(`User does not have access to documents: ${d.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(d,i,a))}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,i){try{if(this.currentValidationToken!==i)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:e,userId:t.userId,timestamp:new Date().getTime()});let l=this.documentIds$.value||[],s=l.filter(d=>!e.includes(d.clientDocumentId));s.length!==l.length&&(s.length>0?this.setDocuments({documents:s.map(d=>({id:d.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:e,userId:t.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(a){this.loggingService.catch("Error in handleDeniedDocumentAccess:",a)}}addUserInfoToOrganization(l){return Q(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let s=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield _l({data:f({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:s,userId:a??t?.userId??""})}catch(s){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",s)}})}setDocumentsImpl(l){return Q(this,arguments,function*({documents:e,options:t,source:i,skipPermissionValidation:a=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(e??"nil")),"options:",JSON.parse(JSON.stringify(t??"nil"))),!this.shouldSetDocumentsAgain(e,ON(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let s=ot();this.currentValidationToken=s;let d=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(d?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let g=this.authService.getUser();if(!g){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(b=>b.id),this.pendingOptions=ON(t)??{},this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let u=t?.organizationId??g?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:g}),d=yield this.filterRelevantDocuments({options:t,documentIds:d,skipPermissionValidation:a}),this.documentIds$.next(d),d?.length){let b=d[0]?.clientDocumentId;t?.rootDocumentId&&d.find(E=>E.clientDocumentId===t?.rootDocumentId)&&(b=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:b,clientOrganizationId:t?.organizationId,options:t})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(s){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENT_ID,source:i,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:i})}catch(l){this.loggingService.catch("Error in setDocumentId:",l);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:i}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let l=i?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=l;let s=Date.now(),d=s-this.lastSetDocumentIdCallTime,g=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&g>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:i??void 0});return}catch(l){this.loggingService.catch("Error in debounceSetDocuments:",l)}})}setDocumentIdImpl(e,t,i){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let l=this.currentDocumentId;if(this.apiKey){let s=`${Qn(e)}`,d=i?.folderId,g=i?.folderId?Pr(i?.folderId):void 0,u=i?.locationId,b=i?.allDocuments,E=a?.organizationId?t?It(t):a?.organizationId:void 0,A=ot(),M=Jb.SET_DOCUMENTS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let V=ot(),q=Xb.SET_DOCUMENTS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,moduleName:q,methodName:ri.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=ot(),fe=Qb.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ae,moduleName:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:V,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:fe})]),this.currentDocumentId!==s||this.documentPaths$.value?.organizationId!==E){this.loggingService.log("setting new docid"),this.currentDocumentId=s;let ie=new hL,Ce=new OL;ie.clientDocumentId=e,Ce.clientDocumentId=e,ie.folderId=d,Ce.folderId=d,ie.locationId=u,Ce.locationId=u,ie.allDocuments=b,Ce.allDocuments=b,ie.veltFolderId=g,Ce.veltFolderId=g,ie.documentId=s,Ce.documentId=s,E&&(ie.organizationId=E,ie.clientOrganizationId=t??a?.clientOrganizationId,Ce.organizationId=E,Ce.clientOrganizationId=t??a?.clientOrganizationId);let xe=`${this.apiKey}`,ke=`apiKey/${this.apiKey}`;E&&(xe=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${ie.organizationId}`,ke=`${ke}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${ie.organizationId}`),Ce.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,Ce.document=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,ie.presence=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,ie.cursor=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,ie.comment=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,Ce.comment=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,ie.multiThread=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,Ce.multiThread=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,ie.tag=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,ie.area=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,Ce.area=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AREA}`,ie.arrow=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,ie.selection=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,ie.audioHuddle=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,ie.huddle=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,ie.recorder=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,Ce.recorder=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,ie.flock=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,ie.syncVideoPlayer=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,ie.liveState=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,ie.liveStateSingleEditorMode=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,ie.reaction=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,Ce.reaction=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,ie.crdt=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,Ce.crdt=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,ie.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,ie.views=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,Ce.notificationViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,Ce.documentViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,Ce.locationViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,ie.notifications=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,ie.metadata=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,ie.users=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,ie.documentIam=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.groupContacts=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,ie.globalContacts=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,ie.logins=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,ie.userFeedback=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,ie.userReportBugs=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,ie.userContactUs=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,E&&(ie.organizationMetadata=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,ie.organizationIam=`${xe}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.organizationGroups=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,ie.organizationNotifications=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,s&&(ie.organizationNotificationsWithDocumentId=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/`,ie.heartbeatByDocument=`${xe}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${s}/`),ie.organizationNotificationsLastNotificationTimestamp=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,ie.organizationNotificationsUsers=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,ie.heartbeat=`${xe}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),Ce.organizationUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,Ce.users=`${ke}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,Ce.documentUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,Ce.notificationDocs=`${ke}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,Ce.notificationUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(ie),this.firestorePaths$.next(Ce),ie?.clientOrganizationId&&ie?.organizationId&&!(ie?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&ie?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:ie?.organizationId,clientOrganizationId:ie?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),l&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:s,clientDocumentId:e}}),this.analyticsService.trackEvent(K.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:s,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:yl.UNSET_DOCUMENT_ID,source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let i=JSON.parse(JSON.stringify(this.documentIds$.value??[])),a=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),l=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:i,folderId:a,context:l}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(K.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{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())}catch(i){this.loggingService.catch("Error in unsetDocumentImpl: ",i)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:yl.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",i)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,i]of this.preDocumentIdChangeFunctions)try{yield i(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig()),this.db&&e?.organizationId){let t=e?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:t,field:"metadata"}}).then(i=>{i&&!i?.errorCode&&this.organizationMetadata$.next(k(f({},this.organizationMetadata$.value),{[t]:i}))}).catch(i=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)})}}catch(t){this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)}})}fetchDocumentMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentMetadata$.value;if(e=e.filter(a=>!i?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,l=[],s={organizationId:t?.clientOrganizationId,folderId:a},d=[],g=20;for(let b=0;b<e.length;b+=g)d.push(e.slice(b,b+g));d.forEach(b=>{let E=JSON.parse(JSON.stringify(s));E.documentIds=b.map(A=>A.clientDocumentId),l.push(this.fetchDocuments(E))});let u={};l.length>0&&(yield Promise.all(l).then(b=>{b?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.setAllDocumentMetadata(f(f({},this.documentMetadata$.value),u))}).catch(b=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",b)}))}else i?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.setDocumentMetadata(a.documentId,a)}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,i=e?.folderId,a=e?.allDocuments,l=[],s={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],g=20;for(let b=0;b<t.length;b+=g)d.push(t.slice(b,b+g));d.forEach(b=>{let E=JSON.parse(JSON.stringify(s));E.documentIds=b.map(A=>A.clientDocumentId),l.push(this.fetchLocations(E))});let u=this.locationMetadata$.value??{};l.length>0&&Promise.all(l).then(b=>{b?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=k(f({},u?.[A.metadata.documentId]??{}),{[A.location.id]:A}))})}),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}).catch(b=>{this.loggingService.catch("Error in fetchLocationMetadata: ",b)})}}catch(e){this.loggingService.catch("Error in fetchLocationMetadata: ",e)}})}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Jn(t=>le(null))).subscribe(t=>{this.customerMetadata$.next(t?.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(ue(e=>e?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}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`${Qn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${It(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(i){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:yl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return Q(this,arguments,function*({locations:e,options:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.SET_LOCATIONS,source:i,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(l){this.loggingService.catch("Error in setLocations: ",l)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(i=>{if(i&&typeof i=="object"){let a=!0;i?.version&&(!i?.version?.id||!i?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${i?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(i)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(i){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:yl.SET_ROOT_LOCATION,source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(l=>l.location).filter(l=>String(l.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=k(f(f({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=f(f({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),l=[],s=[];this.location$.value?.location.id&&s.push(this.location$.value?.location.id),s=[...s,...Object.values(this.locations$.value).map(u=>u.location.id)].filter(u=>u!==void 0);let d;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(d=a.find(u=>u.id===t?.rootLocationId),!d)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(d){let u=Oi(d),b=Qn(JSON.stringify(u));u.id&&l.push({locationId:b,location:u}),this.location$.next({locationId:b,location:u})}}else{d||(d=a[0]);let u=Oi(d),b=Qn(JSON.stringify(u));u.id&&l.push({locationId:b,location:u}),this.location$.next({locationId:b,location:u})}let g=[];return a.slice(t?.appendLocation?0:1).forEach(u=>{if(u.id!==this.location$.value?.location.id){let b=f({},u),E=this.locations$.value;u?.id&&Object.keys(E).forEach(q=>{let ae=E[q];ae.location?.id===u.id&&(b=f(f({},ae.location),u),delete E?.[q])});let A=this.genarateLocationId(b),M={locationId:A,location:b};b.id&&l.push({locationId:A,location:b}),g.push(M);let V=k(f({},E),{[A]:M});this.locations$.next(V)}}),this.updateDocumentLocationMetadata(l),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:yl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(K.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),g}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.ADD_LOCATION,source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(i){this.loggingService.catch("Error in DocService addLocation:",i);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:yl.REMOVE_LOCATION,payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:yl.REMOVE_LOCATIONS,source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(i){this.loggingService.catch("Error in removeLocations: ",i)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(i=>{let a=this.genarateLocationId(i);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==i.id))),this.removeCustomLocation(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:yl.UNSET_LOCATION_IDS,source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(i=>{this.getLocation()?.location.id===i&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==i))),this.removeCustomLocationId(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:yl.REMOVE_LOCATIONS_SUCCESS,source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetLocationIds: ",i)}}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(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),le([])}}updateOrganizationMetadata(e){return Q(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,i=this.documentPaths$.value;if(this.db&&t&&i?.documentId){if(this.organizationMetadata$.value?.[t])return;let l=new kL;l.apiKey=this.configService?.getApiKey()??"",l.organizationId=t,l.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:t,documentId:i?.documentId??""}})),yield this.fetchOrganizationMetadata(e)}}catch(t){this.loggingService.catch("Error in updateOrganizationMetadata: ",t)}})}updateFolderMetadata(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let i={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield _l({methodName:"createFolder",data:{type:"createFolder",metadata:i},getSdkProxy:a,userId:this.authService.getUser()?.userId??""})}}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let i=t.map(a=>Q(this,null,function*(){let l=new pL;this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(l=f(f({},this.clientDocumentMetadataMap[a.clientDocumentId]),l)),l.apiKey=this.configService?.getApiKey()??"",l.documentId=a.documentId,l.clientDocumentId=a.clientDocumentId,l.organizationId=e.organizationId,l.clientOrganizationId=e.clientOrganizationId,l.pageInfo=to();let s=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let g=!0,u=this.documentMetadata$.value?.[a.documentId];if(s&&d){let b=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));b?.clientDocumentId&&!b?.errorCode?b?.folderId&&(b?.folderId!==s||b?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),g=!1):b?.folderId===s?(s&&(l.folderId=s),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${s??""}`),g=!1):(s&&(l.folderId=s),d&&(l.veltFolderId=d))}if(u){let b={};Object.entries(l).forEach(([E,A])=>{b[E]=A}),Mr(b,u)&&(g=!1)}g&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(i),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(a=>a.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of i){let l=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});l?.errorCode&&(l={});let s=[];for(let d of e){let g=new bL;g.locationId=d?.locationId,g.veltLocationId=$K(d?.location?.id??""),g.location=d?.location,g.pageInfo=to(),g?.pageInfo?.deviceInfo&&delete g?.pageInfo?.deviceInfo;let u=k(f({},l),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:k(f({},l[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:g})});this.commonDbService?.shouldUseFirestore()||s.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let b=this.locationMetadata$.value;if(b||(b={}),d?.location?.id){let E=b?.[a.documentId],A=E?.[d?.location?.id??""];b&&(E||(b[a.documentId]={}),A||(b[a.documentId][d?.location?.id??""]={}),b[a.documentId][d?.location?.id??""]=k(f({},A),{location:d?.location})),Object.keys(b||{}).length>0&&this.locationMetadata$.next(b)}}yield Promise.allSettled(s)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Oi(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let i=this.genarateLocationId(e),a=this.locations$.value;a[i]&&(delete a[i],this.locations$.next(f({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==e.id)))}catch(i){this.loggingService.catch("Error in DocService removeLocation:",i)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let i=this.locations$.value;Object.entries(i).forEach(([a,l])=>{l.location.id===e&&(delete i[a],this.locations$.next(f({},i)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e)))})}catch(i){this.loggingService.catch("Error in DocService removeCustomLocationId:",i)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let i=this.getLocations();Object.keys(i).forEach(a=>{let l=i[a];l.location?.id===e&&(t=l.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i=[];t.forEach(a=>{let l=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(l){let s=JSON.parse(l),d=this.genarateLocationId(s);i.push(d)}}),Object.keys(e).forEach(a=>{let l=e[a];i.includes(l.locationId)||delete e[a]}),this.locations$.next(f({},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),le({})}}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 t=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),t){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(i){let a=JSON.parse(i);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),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(i=>{if(i.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(i);a?.locationId&&(e[a.locationId]={element:i,location:a})}else if(i.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=i.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let l=this.getLocationByClientLocationId(a);l?.locationId&&(e[l.locationId]={element:i,location:l});let s={id:a},d=this.genarateLocationId(s);e[a]={element:i,location:{locationId:d,location:s}}}}}),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 t;if(t=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(i)return JSON.parse(i)}else if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(i)return{id:i}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(t){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",t),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadata:",t),null}}getAllDocumentMetadata$(e){return this.getAllDocumentMetadataMap$().pipe(ue(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),xt(Jt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ue(e=>e||{}),xt(Jt))}getAllDocumentMetadataMap(){try{return 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||{},t={},i=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(i&&a)Object.values(e).forEach(l=>{l?.documentId&&l?.veltFolderId===i&&(t[l.documentId]=l)});else{let l=this.documentIds$.value;if(l?.length)l.forEach(s=>{let d=e?.[s.documentId];d&&(t[s.documentId]=d)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(t[this.documentPaths$.value?.documentId]=s)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ue(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),xt(Jt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let i=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));i[e]=t,this.documentMetadata$.next(i)}catch(i){this.loggingService.catch("Error in DocService setDocumentMetadata:",i)}}setAllDocumentMetadata(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(e)}catch(t){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",t)}}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ue(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ue(e=>e||{}),xt(Jt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(xt(Jt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(i){this.loggingService.catch("Error in DocService getMetadataFromType:",i);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let i=this.documentPaths$.value;if(!i)return;let a=e||i.clientDocumentId,l=t||i.documentId,s=this.getDocumentMetadata(l);if(!s)return;let d=s?.folderId,g=s?.veltFolderId;return f(f({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),g?{veltFolderId:g}:{})}catch(i){this.loggingService.catch("Error in DocService getDefaultMetadata:",i);return}}getBaseMetadata(e,t){try{let i,a;t?.element?i=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(i=t.clientDocumentId),i&&(a=this.generateDocumentId(i));let l=this.getMetadataFromType(e,t),s=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||s||{};return d.sdkVersion=fa(),d}catch(i){return this.loggingService.catch("Error in DocService getBaseMetadata:",i),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(i){return this.loggingService.catch("Error in DocService getServerId:",i),null}}fetchDocuments(e){return Q(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 i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return Q(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 i=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return Q(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,documents:a,folderId:l}=e;if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let s=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],g=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=s,u.clientOrganizationId=i,u.clientDocumentId=u.documentId;let b=mi(u.documentId);u.documentId=b,u.apiKey=this.configService.getApiKey()??void 0,(l||this.documentPaths$.value?.folderId)&&(u.folderId=l||this.documentPaths$.value?.folderId,u.veltFolderId=Pr(l||this.documentPaths$.value?.folderId||""));let E=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=g?.[b];M?g[b]=f(f({},M),u):g[b]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:b,organizationId:s,field:"metadata"}});if(A?.errorCode&&(A={}),A&&A.apiKey&&A.folderId&&l&&A.folderId!=u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists with different folderId: ${A.folderId}`);continue}if(A&&A.apiKey&&!A.folderId&&u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists, move this document to folder with REST API`);continue}E(),u&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:u?.documentId??""})&&d.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{organizationId:s,documentId:b}}))}yield Promise.all(d),this.setAllDocumentMetadata(g)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return Q(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:i,locations:a,documentIds:l}=e;if((!l||l.length===0)&&(l=this.documentIds$.value.map(u=>u.clientDocumentId)??[],l.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))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 s=l.map(u=>mi(u)),d=[],g=this.locationMetadata$.value;g||(g={}),s.forEach(u=>{a.forEach(b=>{let E=this.location$.value;if(b?.id===E?.location?.id&&this.location$.next({locationId:E?.locationId,location:b}),b?.id){delete b?.metadata;let A=$K(b.id),M=g?.[u],V=M?.[b.id];g&&(M||(g[u]={}),V||(g[u][b.id]={}),g[u][b.id]=k(f({},V),{location:b})),b&&this.commonDbService&&d.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:b})),properties:{organizationId:Pa(i),documentId:u,id:A}}))}})}),yield Promise.all(d),Object.keys(g||{}).length>0&&this.locationMetadata$.next(g)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return Q(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 i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],l=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let s=Pr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}}),i&&(i=[i]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ft("metadata.veltParentFolderId","==",s)],folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}})}else i=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}});return{data:i,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(_e(e=>e?this.documentPaths$.pipe(_e(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ue(i=>i?.data?.docIamConfig??i?.data),xt((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):le(null))):le(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?zr.RESTRICTED:zr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:zr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),zr.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(i?.errorCode)return;switch(delete i.documentAccessType,i.features||(i.features={}),i.features.all||(i.features.all={}),e){case zr.PUBLIC:i.features.all.restricted=!1;break;case zr.RESTRICTED:i.features.all.restricted=!0,i.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(i)),properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(f(f({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X($n),X(Be),X(Ft),X(x),X(rl),X(Hs),X(ol),X(tr),X(Do))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var An=(()=>{let o=class o{constructor(e,t,i,a,l){this.analyticsService=e,this.authService=t,this.coreActionsService=i,this.docService=a,this.loggingService=l,this.resolveOrganizationUsers=new Se(!0),this.resolveFolderUsers=new Se(!0),this.resolveDocumentUsers=new Se(!0),this.unresolvedUsers=new Se([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Bn,this.userDataProvider$=new Se(null),this.anonymousUserDataProvider$=new Se(null),this.userIdByEmailCache={},this.userById$=new Se({}),this.userByIdCalled$=new Se({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(d){this.loggingService.catch("Error in UsersService getUserById:",d);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe($e(s=>!!s),_e(()=>this.getUnresolvedUsers$().pipe($e(s=>s.length>0),Qr(300),ut(20),_e(s=>{let d=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:d,isCollection:!0,useQuery:!0,firestoreQuery:[_r(ft("user.userId","in",s.slice(0,20)))]}}).pipe(ue(g=>g?.data),on(g=>{if(g&&typeof g=="object"){delete g.undefined,delete g.null;let u=Object.values(g??{});this.setUserByIds(u.map(E=>E.user));let b=s.filter(E=>!u.some(A=>A.user.userId===E));b.length!==s.length&&this.setUnresolvedUsers(b)}})):le([])})))).subscribe()}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in UsersService setCommonDbService:",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in UsersService setContactService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(g){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:s,moduleName:d}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let u=!1;if(i&&(u=this.isResolverForFeatureDisabled(i)),u)return{};{let b={},E=[],A={};if(e?.forEach(M=>{let V=this.getUserById(M);V?b[M]=V:this.userByIdCalled$.getValue()[M]?t&&E.push(M):(E.push(M),this.userByIdCalled$.next(k(f({},this.userByIdCalled$.getValue()),{[M]:!0})))}),E.length>0){let M=s||ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:gi.RESOLVE_USERS,source:"internal",payload:{userIds:E,organizationId:a,feature:i,forceResolve:t,skipUserCheck:l,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let V={};try{let q,ae=new Promise((fe,ie)=>{q=setTimeout(()=>{ie(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});V=yield Promise.race([this.getUsersFromDB({userIds:E,organizationId:a,skipUserCheck:l}).finally(()=>{clearTimeout(q)}),ae]),this.analyticsService.trackEvent(K.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:E}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{result:V,userIds:E,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(q){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",q,{userIds:E}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:q,userIds:E,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{E?.forEach(q=>{if(!V[q]){let ae=new Set([...this.getUnresolvedUsers(),q]);this.unresolvedUsers.next(Array.from(ae)),V[q]={userId:q,name:`User ${q}`}}})}Object.entries(V).forEach(([q,ae])=>{ae&&(b[q]=V?.[q],A[q]=V?.[q])})}return Object.keys(A).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(A)),this.userById$.next(f(f({},this.userById$.getValue()),A))),b}}catch(u){this.loggingService.catch("Error in UsersService resolveUsers:",u);let b=s||ot();return this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:u,userIds:e,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(e){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",e),[]}}setUnresolvedUsers(e){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(e)){let t=JSON.parse(JSON.stringify(e));this.unresolvedUsers.next(t)}}catch(t){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",t)}}getUsersFromDB(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let l=this.userDataProvider$.getValue();if(l){if(l.config?.getConfig?.url){if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let u={organizationId:t,userIds:e},b=yield ji(l.config.getConfig.url,l.config.getConfig.headers,u,!0);return b.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${b.statusCode}. Message: ${b.message||"Unknown error"}`),{}):b.data??{}}let g=yield l.get(e);if(g&&typeof g=="object"&&"success"in g&&"statusCode"in g&&typeof g.success=="boolean"&&typeof g.statusCode=="number"){let u=g;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return g}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let s=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(s.flat());let d={};return s.forEach(g=>{g.forEach(u=>{u?.user?.userId&&(d[u.user.userId]=u.user)})}),d}catch(l){return this.loggingService.catch("Error in UsersService getUsersFromDB:",l),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let g=0;g<e.length;g+=30)l.push(e.slice(g,g+30));let s=l.map((g,u)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",g)],skipUserCheck:i}}))||[]}catch(b){return this.loggingService.catch(`Error in batch ${u+1}:`,b),[]}}));return yield Promise.all(s)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:i}){try{if(!e?.length||!i?.length)return[];let l=[];for(let M=0;M<e.length;M+=30)l.push(e.slice(M,M+30));let s=[];for(let M=0;M<i.length;M+=30)s.push(i.slice(M,M+30));let d=[],g=0,u=(M,V)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_r(ft("userId","in",M),ft("veltResourceId","in",V))]}}))??[])||[]}catch(q){return this.loggingService.catch(`Error in batch ${g+1}:`,q),[]}});for(let M of l)for(let V of s)d.push(u(M,V)),g++;return(yield Promise.all(d)).flat().filter((M,V,q)=>V===q.findIndex(ae=>ae.userId===M.userId&&ae.resourceId===M.resourceId))}catch(l){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",l),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(xt(Jt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),le({})}}setUserByIds(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;");let t=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));e.forEach(i=>{t[i.userId]=f(f({},t?.[i.userId]??{}),i)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let t=e.config?.getConfig?.url,i="get"in e&&typeof e.get=="function";if(!t&&!i){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}setAnonymousUserDataProvider(e){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in e)||typeof e.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",t)}}resolveUserIdsByEmail(i){return Q(this,arguments,function*({emails:e,uniqueId:t}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!e?.length)return{};let a=this.anonymousUserDataProvider$.getValue();if(!a||typeof a.resolveUserIdsByEmail!="function")return{};let l=[...new Set(e.filter(ie=>!!ie))];if(l.length===0)return{};let s={},d=[];if(l.forEach(ie=>{let Ce=this.userIdByEmailCache[ie];Ce?s[ie]=Ce:d.push(ie)}),d.length===0)return s;let g=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",b=this.docService.getDocumentPaths()?.folderId||"",E={organizationId:g,documentId:u,folderId:b,emails:d},A=t||ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:g,documentId:u,folderId:b}});let M=a.config?.resolveTimeout||this.resolveTimeout,V,q=new Promise((ie,Ce)=>{V=setTimeout(()=>{Ce(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},fe=Q(this,null,function*(){try{let ie=yield Ai(()=>a.resolveUserIdsByEmail(E),"resolveUserIdsByEmail",ae);return ie?.statusCode===200&&ie?.data?ie.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${ie?.statusCode}. Message: ${ie?.message||"Unknown error"}`),{})}finally{clearTimeout(V)}});try{let ie=yield Promise.race([fe,q]);return Object.entries(ie).forEach(([Ce,xe])=>{xe&&(this.userIdByEmailCache[Ce]=xe,s[Ce]=xe,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:xe,name:Ce,email:Ce},currentUserId:this.authService.getUser()?.userId??""}).catch(ke=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",ke)}))}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:ie,emails:d}}),s}catch(ie){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",ie),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:ie,emails:d}}),s}}catch(a){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",a),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",e),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(tr),X(ct),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return at.error("Error in isTestingDb:",r),!1}}};var cv=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=s,this.attachmentResolverService=d,this.coreActionsService=g,this.notificationActionTypeMap={[At.NEWLY_ADDED]:Io.COMMENT_ANNOTATION_ADD,[At.ADDED]:Io.COMMENT_ADD,[At.UPDATED]:Io.COMMENT_UPDATE,[At.DELETED]:Io.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let i of e){if(i?.from?.userId&&t.add(i?.from?.userId),i?.comments)for(let a of i?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let l of a?.to)l?.userId&&t.add(l?.userId);if(a?.taggedUserContacts)for(let l of a?.taggedUserContacts)l?.userId&&t.add(l?.userId)}if(i?.assignedTo?.userId&&t.add(i?.assignedTo?.userId),i?.resolvedByUserId&&t.add(i?.resolvedByUserId),i?.subscribedUsers)for(let a of Object.values(i?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(i?.unsubscribedUsers)for(let a of Object.values(i?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let l=this.usersService.getUserById(a?.userId);if(l)return f(f({},a),l)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let l=this.usersService.getUserById(a?.contact?.userId);l&&(a.contact=l,(l?.name||l?.email)&&(a.text=`@${l?.name||l?.email}`))}return a}));let i=t?.taggedUserContacts?.filter((a,l,s)=>s.findIndex(d=>d.text===a.text)===l)||[];i.sort((a,l)=>(l.text?.length||0)-(a.text?.length||0)),i.forEach(a=>{if(a?.text){let l=new RegExp(Xc(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(Xc(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(l,a.text),t.commentHtml=t.commentHtml?.replaceAll(l,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.resolvedByUserId){let t=this.usersService.getUserById(e?.resolvedByUserId);t&&(e.resolvedByUser=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=i)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=i)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.isCommentTextAvailable=!0)}),e?.viewedBy&&delete e.viewedBy,e?.unread!==void 0&&delete e.unread,e?.resolvedByUser!==void 0&&delete e.resolvedByUser,e?.comments&&e.comments.forEach(t=>{t?.reactionAnnotations&&delete t.reactionAnnotations}),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 t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(l=>{let s=t?.comments?.[l?.commentId];if(s){l.commentHtml=s?.commentHtml,l.commentText=s?.commentText;let d=s?.attachments;i&&d&&l.attachments?.forEach(g=>{let u=g?.attachmentId;d?.[u]&&(g.name=d?.[u]?.name,g.url=d?.[u]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(l=>{t?.[l]&&(e[l]=t[l])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let i=e?.location?.id,a=e?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.location=l?.location),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",i),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let i=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",i),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new yc;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(s=>(s.isAttachmentResolverUsed=!0,delete s?.name,delete s?.url,s));a.attachments=l}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}resolveTaggedUserEmails(e){return Q(this,null,function*(){try{let t=new Set;if(e.comments?.forEach(i=>{i.taggedUserContacts?.forEach(a=>{a?.contact?.email&&!a?.userId&&t.add(a.contact.email)}),i.to?.forEach(a=>{a?.email&&!a?.userId&&t.add(a.email)})}),t.size>0){let i=ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(t)}});let a=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(t),uniqueId:i});Object.keys(a).length>0&&e.comments?.forEach(l=>{l.taggedUserContacts?.forEach(s=>{if(s?.contact?.email&&!s?.userId){let d=a[s.contact.email];if(d){let g=s.text;if(g){let u=Xc(g),b=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(b,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(b,`{{${d}}}`))}s.userId=d,s.contact.userId=d,delete s.contact?.email,delete s.contact?.visibility,s.text=""}}}),l.to=l.to?.map(s=>{if(s?.email&&!s?.userId){let d=a[s.email];if(d)return delete s?.email,delete s?.visibility,k(f({},s),{userId:d})}return s})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return Q(this,arguments,function*({data:e,actionType:t,commentId:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),e=yield this.resolveTaggedUserEmails(e),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let l=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),g;t&&(g=this.notificationActionTypeMap?.[t]);let u={},b=null,E=!1;if(e&&e.annotationId){let M=e.annotationId;if(u[M]=f(f(f(f({annotationId:M,metadata:ti(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,s?.length>0&&s.forEach(q=>{e?.[q]&&(u[M][q]=e[q],delete e[q])}),d?.length)for(let q of d)e?.[q]!==void 0&&(u[M][q]=JSON.parse(JSON.stringify(e[q])));e.comments?.forEach(q=>{if(q.commentId){let ae;l&&(ae={},q.attachments?.forEach(fe=>{ae[fe.attachmentId]={attachmentId:fe.attachmentId,name:fe.name,url:fe.url}})),u[M].comments[q.commentId]=f(f(f(f(f(f({commentId:q.commentId},q?.commentHtml&&{commentHtml:q?.commentHtml}),q?.commentText&&{commentText:q?.commentText}),ae&&{attachments:ae}),q?.from&&{from:q?.from}),q?.to&&{to:q?.to}),q?.taggedUserContacts&&{taggedUserContacts:q?.taggedUserContacts})}}),E=this.isCommentsDataChanged(u[M],M);let V=new Br;Object.assign(V,e),V.comments=e.comments?.map(q=>this.stripCommentsFromAnnotationData({comment:q}))||[],b=V}let A=b?.comments?.find(M=>M.commentId===i);return A?.isDraft&&(g=b?.comments?.length&&b?.comments?.length>0?Io.COMMENT_ADD:Io.COMMENT_ANNOTATION_ADD),{strippedData:E&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:b,eventType:g}}catch(l){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",l),{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(i=>i?.userId?{userId:i.userId}:i)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(i=>i?.contact?.userId?k(f({},i),{contact:{userId:i.contact.userId}}):i));let t=e?.taggedUserContacts?.filter((i,a,l)=>l.findIndex(s=>s.text===i.text)===a)||[];t.sort((i,a)=>(a.text?.length||0)-(i.text?.length||0)),t.forEach(i=>{if(i?.text&&i?.contact?.userId){let a=new RegExp(Xc(i.text),"g");e.commentText=e.commentText?.replaceAll(a,l=>`{{${i.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,l=>`{{${i.userId}}}`)}}),t.forEach(i=>{i?.text&&i?.contact?.userId&&(i.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}getDeniedForYouUsers(t){return Q(this,arguments,function*({extraData:e}){try{let i=Object.values(e?.annotationData?.subscribedUsers||{}).map(l=>l.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&i.length){let l=e?.metadata?.clientDocumentId,s=e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?e?.annotationData?.context?.access:null,d=[];i.forEach(b=>{if(d.push({userId:b,resource:{id:l,type:oa.DOCUMENT,source:ro.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:s?{access:s}:void 0}}),s){let E=JSON.stringify(s);d.push({userId:b,resource:{id:E,type:oa.CONTEXT,source:ro.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:s}}})}});let g=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.SET_NOTIFICATIONS,uniqueId:g,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:g,methodName:ro.SET_NOTIFICATIONS});u?.success&&u?.data?.length&&u.data.forEach(b=>{b.hasAccess||a.push(b.userId)})}return a}catch(i){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",i),[]}})}handleCommentEncryption(s){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let d=IN(this.authService.getFirebaseConfig()?.firebaseOptions),g=Gr(this.functions,Wr({url:En.cloudFunction?.[d]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(i){i=this.notificationService?.processNotificationData(i),i.annotationData=e;let M=i?.targetAnnotationData?.commentId;if(M){let V=e?.comments?.find(q=>q?.commentId===M);V&&(i.targetAnnotationData=V)}try{let V=yield this.stripCommentAnnotationData({data:i.annotationData,actionType:i?.actionType??At.NEWLY_ADDED});V?.originalData&&(i.annotationData=this.formatCommentData(V.originalData)),i?.targetAnnotationData&&(i.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:i.targetAnnotationData})))}catch(V){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",V)}}let u=Cp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),b=yield this.getDeniedForYouUsers({extraData:i}),E={path:t??"",data:e??{},dbId:u??"",notificationData:i||void 0,notificationURL:En.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:fa(),deniedForYouUsers:b,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield hc(E,this.authService.getUser()?.userId??"");yield g({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(We),X(Do),X(Ft),X(rl),X(Gs),X(tr))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var AL=(()=>{let o=class o{constructor(e,t,i,a,l,s){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=s}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i?.from?.userId),i?.reactions?.length)for(let a of i?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=IN(this.authService.getFirebaseConfig()?.firebaseOptions),s=Gr(this.functions,Wr({url:En.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=Cp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:fa()},b=yield hc(u,g);yield s({veltData:b})}catch(l){this.loggingService.catch("Error in handleReactionEncryption:",l)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",i),!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 t={};if(e&&e.annotationId){let i=e.annotationId;if(t[i]=f({annotationId:i,metadata:ti(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[i],i))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{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 t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(We),X(Do),X(Ft),X(Hs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _p=(()=>{let o=class o{constructor(e,t,i,a){this.authService=e,this.loggingService=t,this.usersService=i,this.recorderAnnotationsResolverService=a}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId),i?.transcription?.from?.userId&&t.add(i?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?k(f({},e.transcription),{lastUpdated:t}):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(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",i),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield hc(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}stripRecorderAnnotationData({data:e,actionType:t}){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())return{strippedData:null,originalData:e};let i=e?.annotationId;if(!i)return{strippedData:null,originalData:e};let a=this.recorderAnnotationsResolverService.getAdditionalFields(),l={annotationId:i,metadata:ti(e.metadata??{})};if(e?.from&&(l.from=JSON.parse(JSON.stringify(e.from))),e?.transcription&&(l.transcription=JSON.parse(JSON.stringify(e.transcription))),e?.attachment!==void 0&&(l.attachment=e.attachment?JSON.parse(JSON.stringify(e.attachment)):null),e?.attachments?.length&&(l.attachments=JSON.parse(JSON.stringify(e.attachments))),e?.chunkUrls&&Object.keys(e.chunkUrls).length>0&&(l.chunkUrls=JSON.parse(JSON.stringify(e.chunkUrls))),e?.recordingEditVersions){let d={};for(let[g,u]of Object.entries(e.recordingEditVersions)){let b=Number(g),E={};u?.from&&(E.from=JSON.parse(JSON.stringify(u.from))),u?.attachment!==void 0&&(E.attachment=u.attachment?JSON.parse(JSON.stringify(u.attachment)):null),u?.attachments?.length&&(E.attachments=JSON.parse(JSON.stringify(u.attachments))),u?.transcription&&(E.transcription=JSON.parse(JSON.stringify(u.transcription))),Object.keys(E).length>0&&(d[b]=E)}Object.keys(d).length>0&&(l.recordingEditVersions=d)}if(e?.isUrlAvailable!==void 0&&(l.isUrlAvailable=e.isUrlAvailable),a?.length)for(let d of a)e?.[d]!==void 0&&(l[d]=JSON.parse(JSON.stringify(e[d])));if(e?.from?.userId&&(e.from={userId:e.from.userId}),delete e.transcription,e?.attachments?.length&&(e.attachments=e.attachments.map(d=>({attachmentId:d?.attachmentId,name:d?.name,bucketPath:d?.bucketPath}))),e.attachment=null,e?.chunkUrls&&(e.chunkUrls={}),e?.recordingEditVersions)for(let[,d]of Object.entries(e.recordingEditVersions))d?.from?.userId&&(d.from={userId:d.from.userId}),d.attachment=null,d?.attachments?.length&&(d.attachments=d.attachments.map(g=>({attachmentId:g?.attachmentId,name:g?.name,bucketPath:g?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let s;return t===$l.ADDED?s=Io.RECORDER_ANNOTATION_ADD:t===$l.UPDATED?s=Io.RECORDER_ANNOTATION_UPDATE:t===$l.DELETED&&(s=Io.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:s}}catch(i){return this.loggingService.catch("Error in RecorderUtilsService stripRecorderAnnotationData:",i),{strippedData:null,originalData:e}}}mergeStrippedDataWithRecorderAnnotation(e){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e?.annotationId)return e;let t=this.recorderAnnotationsResolverService.getAnnotationById(e.annotationId);if(!t)return e;if(t.from&&(e.from=t.from),t.transcription&&(e.transcription=t.transcription),t.attachments?.length&&(e.attachments=t.attachments),t.attachment!==void 0&&(e.attachment=t.attachment),t.chunkUrls&&Object.keys(t.chunkUrls).length>0&&(e.chunkUrls=t.chunkUrls),t.recordingEditVersions&&e.recordingEditVersions)for(let[i,a]of Object.entries(t.recordingEditVersions)){let l=Number(i);e.recordingEditVersions[l]&&(a.from&&(e.recordingEditVersions[l].from=a.from),a.attachment!==void 0&&(e.recordingEditVersions[l].attachment=a.attachment),a.attachments?.length&&(e.recordingEditVersions[l].attachments=a.attachments),a.transcription&&(e.recordingEditVersions[l].transcription=a.transcription))}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeStrippedDataWithRecorderAnnotation:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(We),X(x),X(An),X(ol))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bp=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Se(null),this.activityById$=new Se({}),this.fieldsToRemove=[],this.getActivityById=a=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ActivityResolverService getActivityById:",l);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove))})}catch(a){this.loggingService.catch("Error in ActivityResolverService constructor:",a)}}getProvider(){try{let e=this.activityDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ActivityResolverService getProvider:",e);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(e){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",e)}}resolveActivities(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:e}}),b(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.activityIds||[])],V=k(f({},e),{activityIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in ActivityResolverService resolveActivities:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.activityById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.activityById$.next(f(f({},this.activityById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let i=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let a=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=f(f({},l),e.activity);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(s?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(e.activity),event:e.event}),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ActivityResolverService saveActivity:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),le(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",e),this.fieldsToRemove}}setActivityDataProvider(e){try{if(e){this.loggingService.log("Setting activity data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.activityDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",t)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sS=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=s,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=g,this.activityResolverService=u}getActivityDisplayMessage(e){try{switch(e.featureType){case"comment":return this.getCommentDisplayMessage(e);case"recorder":return this.getRecorderDisplayMessage(e);case"reaction":return this.getReactionDisplayMessage(e);case"crdt":return this.getCrdtDisplayMessage(e);case"custom":return e.displayMessageTemplate&&e.displayMessageTemplateData?this.resolveTemplate(e.displayMessageTemplate,e.displayMessageTemplateData):"";default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",t),""}}resolveTemplate(e,t){try{return e.replace(/\{\{([\w.]+)\}\}/g,(i,a)=>{let l=a.split(".").reduce((s,d)=>{if(s!=null&&typeof s=="object")return s[d]},t);return l!=null?String(l):""})}catch(i){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",i),e}}buildActivityDataFromExtraData(e){try{let{feature:t,extraData:i}=e;if(!i?.actionType)return null;switch(t){case"comment":return this.buildCommentActivityData({commentAnnotation:i.annotationData,targetComment:i.targetAnnotationData,actionType:i.actionType,otherFields:i});case"recorder":return this.buildRecorderActivityData(i);case"reaction":return this.buildReactionActivityData(i);default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",t),null}}stripActivityPII(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e));if(delete t.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:t};t.actionUser?.userId&&(t.actionUser={userId:t.actionUser.userId}),t.changes&&this.stripUsersFromChanges(t.changes),t.displayMessageTemplateData&&this.stripUsersFromTemplateData(t.displayMessageTemplateData);let i=this.extractCommentChangesForResolver(t),a=this.extractFeatureEntityDataForResolver(t);yield this.stripFeatureSpecificPII(t);let l=this.extractActivityResolverData(t);return i&&(l?l.changes=f(f({},l.changes),i.changes):l=i),a&&(l?(a.entityData!==void 0&&(l.entityData=a.entityData),a.entityTargetData!==void 0&&(l.entityTargetData=a.entityTargetData)):l=a),l&&(t.isActivityResolverUsed=!0),{strippedActivity:t,activityResolverData:l}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",t),{strippedActivity:e}}})}mergeActivityWithUser(e){try{if(!this.usersService.userDataProviderAvailable())return e;if(e=JSON.parse(JSON.stringify(e)),e.actionUser?.userId){let t=this.usersService.getUserById(e.actionUser.userId);t&&(e.actionUser=t)}return e.changes&&this.rehydrateUsersInChanges(e.changes),e.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(e.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(e),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",t),e}}mergeActivityWithFeatureData(e){try{switch(e.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(e);case"reaction":return this.mergeActivityWithReactionData(e);case"recorder":return this.mergeActivityWithRecorderData(e);default:return e}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",t),e}}getUserIdsToResolveFromActivities(e){try{let t=new Set;for(let i of e){if(i.actionUser?.userId&&t.add(i.actionUser.userId),i.changes)for(let a of Object.values(i.changes))a&&(this.extractUserIdFromValue(a.from,t),this.extractUserIdFromValue(a.to,t));if(i.displayMessageTemplateData)for(let a of Object.values(i.displayMessageTemplateData))this.extractUserIdFromValue(a,t);this.extractFeatureSpecificUserIds(i,t)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",t),[]}}getEntityIdsToResolveFromActivities(e,t){try{let i=new Set;for(let a of e)if(!(t&&a.featureType!==t))switch(a.featureType){case"comment":case"reaction":case"recorder":a.targetEntityId&&i.add(a.targetEntityId);break}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",i),[]}}stripFeatureSpecificPII(e){return Q(this,null,function*(){try{switch(e.featureType){case"comment":yield this.stripCommentPII(e);break;case"reaction":this.stripReactionPII(e);break;case"recorder":this.stripRecorderPII(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",t)}})}extractActivityResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let t={id:e.id},i=!1;if(e.featureType==="custom"){let a=this.activityResolverService.getFieldsToRemove();for(let l of a)l in e&&e[l]!==void 0&&(t[l]=e[l],delete e[l],i=!0)}return e.metadata&&(t.metadata=ti(e.metadata)),i?t:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",t);return}}extractCommentChangesForResolver(e){try{return!this.activityResolverService.activityDataProviderAvailable()||e.featureType!=="comment"||!e.changes?.commentText?void 0:{id:e.id,changes:{commentText:e.changes.commentText},metadata:e.metadata?ti(e.metadata):void 0}}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",t);return}}extractFeatureEntityDataForResolver(e){try{if(!this.activityResolverService.activityDataProviderAvailable()||!e.entityData)return;let t=e.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),i=e.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!t&&!i)return;let a={id:e.id,metadata:e.metadata?ti(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let s=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}if(i){let s=this.reactionUtilsService.stripReactionAnnotationData(l);if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}return a.entityData?a:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",t);return}}mergeActivityWithResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return e;let t=this.activityResolverService.getActivityById(e.id);if(!t)return e;t.changes&&(e.changes||(e.changes={}),Object.assign(e.changes,t.changes)),t.entityData!==void 0&&(e.entityData=t.entityData),t.entityTargetData!==void 0&&(e.entityTargetData=t.entityTargetData),t.displayMessageTemplateData&&(e.displayMessageTemplateData||(e.displayMessageTemplateData={}),Object.assign(e.displayMessageTemplateData,t.displayMessageTemplateData));let i=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[a,l]of Object.entries(t))!i.has(a)&&l!==void 0&&(e[a]=l);return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",t),e}}rehydrateFeatureSpecificUserData(e){try{switch(e.featureType){case"comment":this.rehydrateCommentUserData(e);break;case"reaction":this.rehydrateReactionUserData(e);break;case"recorder":this.rehydrateRecorderUserData(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",t)}}getCommentDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case qr.ANNOTATION_ADD:return`${t} added a comment`;case qr.COMMENT_ADD:return`${t} replied to a comment`;case qr.COMMENT_UPDATE:return`${t} edited a comment`;case qr.COMMENT_DELETE:return`${t} deleted a comment`;case qr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case qr.STATUS_CHANGE:{let i=e.changes?.status,a=i?.from?.name,l=i?.to?.name;return a&&l?`${t} changed status from ${a} to ${l}`:`${t} changed the status`}case qr.PRIORITY_CHANGE:{let i=e.changes?.priority,a=i?.to;if(!a)return`${t} removed the priority`;let l=typeof a=="object"?a?.name:String(a),s=i?.from,d=s&&typeof s=="object"?s?.name:s?String(s):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case qr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case qr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case qr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case qr.APPROVE:return`${t} approved the comment`;case qr.ACCEPT:return`${t} accepted a suggestion`;case qr.REJECT:return`${t} rejected a suggestion`;case qr.REACTION_ADD:return`${t} reacted to a comment`;case qr.REACTION_DELETE:return`${t} removed a reaction`;case qr.SUBSCRIBE:return`${t} subscribed to the thread`;case qr.UNSUBSCRIBE:return`${t} unsubscribed from the thread`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",t),""}}getRecorderDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case XD.RECORDING_ADD:return`${t} added a recording`;case XD.RECORDING_DELETE:return`${t} deleted a recording`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",t),""}}getReactionDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case QD.REACTION_ADD:return`${t} added a reaction`;case QD.REACTION_DELETE:return`${t} removed a reaction`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",t),""}}getCrdtDisplayMessage(e){try{let t=e.actionUser?.name??"Someone",a=e.entityData?.editCount??0,l=e.targetEntityId??"unknown";return`${t} made ${a} edit${a!==1?"s":""} to editor ${l}`}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",t),""}}stripCommentPII(e){return Q(this,null,function*(){try{let t=yield this.commentUtilsService.stripCommentAnnotationData({data:e.entityData,actionType:e.eventType??At.NEWLY_ADDED});t?.originalData&&(e.entityData=this.commentUtilsService.formatCommentData(t.originalData)),e.entityTargetData&&(e.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:e.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&e.changes?.commentText&&delete e.changes.commentText}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",t)}})}rehydrateCommentUserData(e){try{e.entityData&&this.commentUtilsService.mergeCommentWithUser(e.entityData),e.entityTargetData&&(this.rehydrateUserInObject(e.entityTargetData,"from"),this.rehydrateUsersInArray(e.entityTargetData,"to"),this.rehydrateUsersInArray(e.entityTargetData,"taggedUserContacts"))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",t)}}stripReactionPII(e){try{if(!e.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(e.entityData),e.entityData=this.reactionUtilsService.formatReactionData(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",t)}}rehydrateReactionUserData(e){try{if(!e.entityData)return;this.reactionUtilsService.mergeReactionWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",t)}}stripRecorderPII(e){try{if(!e.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.recorderUtilsService.stripRecorderAnnotationData({data:e.entityData});return}let t=e.entityData;if(this.usersService.userDataProviderAvailable()){t.from&&typeof t.from=="object"&&"userId"in t.from&&(t.from={userId:t.from.userId});let i=t.transcription;i?.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",t)}}rehydrateRecorderUserData(e){try{if(!e.entityData)return;this.recorderUtilsService.mergeRecorderWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",t)}}mergeActivityWithCommentAnnotationData(e){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e.targetEntityId);if(!t)return e;let i=e.entityData?.comments;if(Array.isArray(i))for(let a of i){let l=a?.commentId;if(l==null)continue;let s=t.comments?.[String(l)];s&&(s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml))}if(e.targetSubEntityId&&e.entityTargetData){let a=t.comments?.[e.targetSubEntityId];if(a){let l=e.entityTargetData;a.commentText&&(l.commentText=a.commentText),a.commentHtml&&(l.commentHtml=a.commentHtml)}}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",t),e}}mergeActivityWithReactionData(e){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",t),e}}mergeActivityWithRecorderData(e){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",t),e}}buildCommentActivityData(e){try{let{commentAnnotation:t,targetComment:i,actionType:a,otherFields:l}=e,s=t,d=i,g=a===At.DELETED&&l?.isAnnotationDelete?qr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!g)return null;let u=s?.annotationId;if(!u)return null;let b=d?.commentId,E=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:g,targetEntityId:u,eventType:a,targetSubEntityId:b??null,changes:Object.keys(E).length>0?E:void 0,entityData:t,entityTargetData:i??void 0}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",t),null}}mapCommentStatusToActionType(e){try{switch(e){case At.NEWLY_ADDED:return qr.ANNOTATION_ADD;case At.ADDED:return qr.COMMENT_ADD;case At.UPDATED:return qr.COMMENT_UPDATE;case At.DELETED:return qr.COMMENT_DELETE;case At.STATUS_CHANGED:return qr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return qr.PRIORITY_CHANGE;case At.ASSIGNED:return qr.ASSIGN;case At.ACCESS_MODE_CHANGED:return qr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return qr.CUSTOM_LIST_CHANGE;case At.APPROVED:return qr.APPROVE;case At.ACCEPTED:return qr.ACCEPT;case At.REJECTED:return qr.REJECT;case At.REACTION_ADDED:return qr.REACTION_ADD;case At.REACTION_DELETED:return qr.REACTION_DELETE;case At.SUBSCRIBED:return qr.SUBSCRIBE;case At.UNSUBSCRIBED:return qr.UNSUBSCRIBE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",t),null}}buildRecorderActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapRecorderStatusToActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"recorder",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",t),null}}mapRecorderStatusToActionType(e){try{switch(e){case $l.ADDED:return XD.RECORDING_ADD;case $l.DELETED:return XD.RECORDING_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",t),null}}buildReactionActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapReactionActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"reaction",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",t),null}}mapReactionActionType(e){try{switch(e){case"add":return QD.REACTION_ADD;case"delete":return QD.REACTION_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",t),null}}buildCommentChanges(e,t,i){try{let a={};switch(e){case At.NEWLY_ADDED:case At.ADDED:a.commentText={from:null,to:t?.commentText??null};break;case At.UPDATED:a.commentText={from:i?.oldCommentText??null,to:t?.commentText??null};break;case At.DELETED:a.commentText={from:t?.commentText??null,to:null};break;case At.STATUS_CHANGED:a.status={from:i?.oldStatus??null,to:i?.newStatus??null};break;case At.PRIORITY_CHANGED:a.priority={from:i?.oldPriority??null,to:i?.newPriority??null};break;case At.ASSIGNED:{a.assignedTo={from:i?.oldAssignedTo??null,to:i?.newAssignedTo??null};break}case At.ACCESS_MODE_CHANGED:a.accessMode={from:i?.oldAccessMode??null,to:i?.newAccessMode??null};break;case At.CUSTOM_LIST_CHANGED:a.customList={from:i?.oldCustomList??null,to:i?.newCustomList??null};break}return a}catch(a){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",a),{}}}extractFeatureSpecificUserIds(e,t){try{switch(e.featureType){case"comment":this.extractCommentActivityUserIds(e,t);break;case"reaction":this.extractReactionActivityUserIds(e,t);break;case"recorder":this.extractRecorderActivityUserIds(e,t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",i)}}extractCommentActivityUserIds(e,t){try{if(e.entityData){let i=this.commentUtilsService.getUserIdsToResolveFromComments([e.entityData]);for(let a of i)t.add(a)}if(e.entityTargetData){let i=e.entityTargetData;if(this.extractUserIdFromValue(i.from,t),Array.isArray(i.to))for(let a of i.to)this.extractUserIdFromValue(a,t);if(Array.isArray(i.taggedUserContacts))for(let a of i.taggedUserContacts)this.extractUserIdFromValue(a,t)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",i)}}extractReactionActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.reactionUtilsService.getUserIdsToResolveFromReactions([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",i)}}extractRecorderActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.recorderUtilsService.getUserIdsToResolveFromRecorders([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",i)}}stripUsersFromChanges(e){try{for(let t of Object.keys(e)){let i=e[t];i&&(i.from=this.stripUserIfPresent(i.from),i.to=this.stripUserIfPresent(i.to))}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",t)}}stripUserIfPresent(e){try{return e&&typeof e=="object"&&"userId"in e?{userId:e.userId}:e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",t),e}}stripUsersFromTemplateData(e){try{for(let t of Object.keys(e)){let i=e[t];i&&typeof i=="object"&&"userId"in i&&(e[t]={userId:i.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",t)}}rehydrateUsersInChanges(e){try{for(let t of Object.values(e))t&&(t.from=this.rehydrateIfUser(t.from),t.to=this.rehydrateIfUser(t.to))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",t)}}rehydrateIfUser(e){try{if(e&&typeof e=="object"&&"userId"in e){let t=e.userId;return this.usersService.getUserById(t)??e}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",t),e}}rehydrateUsersInTemplateData(e){try{for(let t of Object.keys(e))e[t]=this.rehydrateIfUser(e[t])}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",t)}}rehydrateUserInObject(e,t){try{let i=e[t];if(i&&typeof i=="object"&&"userId"in i){let a=i.userId,l=this.usersService.getUserById(a);l&&(e[t]=l)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",i)}}rehydrateUsersInArray(e,t){try{let i=e[t];Array.isArray(i)&&(e[t]=i.map(a=>this.rehydrateIfUser(a)))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",i)}}extractUserIdFromValue(e,t){try{if(e&&typeof e=="object"&&"userId"in e){let i=e.userId;typeof i=="string"&&t.add(i)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",i)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(cv),X(AL),X(_p),X(rl),X(Hs),X(ol),X(bp))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dv=class{constructor({apiKey:o,documentId:r,organizationId:e,folderId:t,veltFolderId:i,clientDocumentId:a,clientOrganizationId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.folderId=t,this.veltFolderId=i,this.clientDocumentId=a,this.clientOrganizationId=l,a&&(this.documentId=mi(a)),l&&(this.organizationId=Pa(l)),t&&(this.folderId=t,this.veltFolderId=Pr(t)),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=`${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.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/`,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.crdt=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,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.userConfig=`${o}/${U.FIREBASE_PARTIAL_PATH_USERS}`),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.heartbeatByDocument=`${o}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${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.heartbeat=`${o}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT 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 heartbeat(){return this.paths.heartbeat?this.paths.heartbeat:this.throwError("Heartbeat path is not available.")}get heartbeatByDocument(){return this.paths.heartbeatByDocument?this.paths.heartbeatByDocument:this.throwError("Heartbeat by document 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 PL=class{constructor({apiKey:o,documentId:r,organizationId:e,clientDocumentId:t,clientOrganizationId:i,folderId:a,veltFolderId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.veltFolderId=l,t&&(this.documentId=mi(t)),i&&(this.organizationId=Pa(i)),a&&(this.folderId=a,this.veltFolderId=Pr(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.users=`${o}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_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.paths.activities=`${o}/${U.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.lastActivityTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${o}/${U.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),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.crdt=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,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 permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get 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.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var I_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),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(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var E_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),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(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var T_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let i of e)i?.user?.userId&&t.add(i?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let i=t;e?.user&&typeof e.user=="object"&&(i=f(f({},i),e.user)),e=k(f({},e),{user:i})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var w_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["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(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var RL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),i=ot(),a=xc.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USERS_FROM_HUDDLE_MESSAGES,moduleName:a,source:"internal",payload:{userIds:t}});let l=yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a});for(let s of e)s?.from?.userId&&l[s.from.userId]&&(s.from=l[s.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),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(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var NL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let i of e)i?.updatedBy?.userId&&t.add(i?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(e){try{let t=new Set;return e?.editor?.userId&&t.add(e?.editor?.userId),e?.requestEditorAccess?.user?.userId&&t.add(e?.requestEditorAccess?.user?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return Q(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=ot(),a=xc.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:a,source:"internal",payload:{userIds:t}}),yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a}),this.mergeSingleEditorLiveStateDataWithUser(e)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),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(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var A_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mv=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Se(null),this.notificationById$=new Se({}),this.inFlightRequests=new Map,this.getNotificationById=a=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",l);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in NotificationResolverService constructor:",a)}}getProvider(){try{let e=this.notificationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in NotificationResolverService getProvider:",e);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(e){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",e)}}resolveNotifications(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let xe=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:e}}),b(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=this.notificationById$.getValue()||{},V=[...new Set(e.notificationIds||[])],q=[],ae=[],fe=[];for(let xe of V)M[xe]||(this.inFlightRequests.has(xe)?(q.push(this.inFlightRequests.get(xe)),ae.push(xe)):fe.push(xe));let ie=k(f({},e),{notificationIds:fe});Q(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),fe.length>0){let xe=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:ie}});let ke,ye=new Promise(Ne=>{ke=Ne});for(let Ne of fe)this.inFlightRequests.set(Ne,ye.then(Ue=>Ue?.[Ne]));let Oe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,ie,!0):E?.get?.(ie)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Ne=>s?{}:(g(),Ne&&Ne.statusCode!==200?(this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Ne,request:ie}}),this.loggingService.catch(Ne?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Ne?.data)).catch(Ne=>{throw g(),Ne});try{A=(yield Oe)||{},ke(A);for(let Ue of fe)this.inFlightRequests.delete(Ue);this.analyticsService.trackEvent(K.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:fe});let Ne={};Object.entries(A).forEach(([Ue,ze])=>{let Ge=this.notificationById$.value?.[Ue];Ge?Ge&&JSON.stringify(Ge)!==JSON.stringify(ze)&&(Ne[Ue]=ze):Ne[Ue]=ze}),Object.keys(Ne).length>0&&this.notificationById$.next(f(f({},this.notificationById$.getValue()),Ne)),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Ne,request:ie}}),u(Ne)}catch(Ne){ke({});for(let ze of fe)this.inFlightRequests.delete(ze);let Ue=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ue,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ne,request:ie}}),s||b(Ne),u(A)}}else g(),u({})}catch(xe){g();let ke=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ke,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:xe,request:ie}}),b(xe)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let a=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let l=i||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let s=this.notificationById$.getValue(),d=f({},s);delete d?.[e],this.notificationById$._value=d;let g={notificationId:e,organizationId:t},u=yield Ai(()=>a?.config?.deleteConfig?.url?ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,g,!1):a?.delete?.(g)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=s),this.loggingService.catch(u?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:u,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:e}),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",a);let l=i||ot();return this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:a,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),le(void 0)}}setNotificationDataProvider(e){try{if(e){this.loggingService.log("Setting notification data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.notificationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",t)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var LL=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=s,this.notificationResolverService=d}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let i of e){let{notification:a}=i;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let l=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let s of l)t.add(s)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),i=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[i]?.commentText,l=t?.comments?.[i]?.commentHtml;return a&&l&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=l),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let i=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.notification.notificationSourceData.location=l?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=l?.location)),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",i),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let i=this.usersService.getUserById(t?.actionUser?.userId);i&&(t.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);i&&(t.displayHeadlineMessageTemplateData.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);i&&(t.displayHeadlineMessageTemplateData.recipientUser=i)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){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,t);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",i),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(i=>{i?.notification?.targetAnnotationId&&i?.raw?.notificationSource==="comment"&&t.push(i.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return Q(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let i="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield hc(e,i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",i),e}})}getCustomNotificationIdsToResolve(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let t=new Set,i=Array.isArray(e)?e:Object.values(e||{});for(let a of i)if(a?.raw?.notificationSource==="custom"){let l=a?.notification?.id||a?.notificationId;l&&t.add(l)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",t),[]}}mergeResolvedNotificationData(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||e?.raw?.notificationSource!=="custom")return e;let t=e?.notification?.id||e?.notificationId;if(!t)return e;let i=this.notificationResolverService.getNotificationById(t);if(!i)return e;let a=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let l of a)i[l]!==void 0&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]));return Object.keys(i).forEach(l=>{!a.includes(l)&&l!=="notificationId"&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]))}),e.notification&&(e.notification.isNotificationResolverUsed=!0),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(cv),X(_p),X(x),X(An),X(We),X(rl),X(mv))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var P_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var R_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let i of e)i?.user?.userId&&t.add(i.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var N_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i.from.userId),i?.to?.length)for(let a of i.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let i=this.usersService.getUserById(t?.userId);i&&(t=i)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),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(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var rd=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V,q,ae,fe,ie,Ce,xe,ke,ye,Oe,Ne){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=s,this.cursorUtilsService=d,this.huddleUtilsService=g,this.liveStateUtilsService=u,this.loggingService=b,this.multiThreadUtilsService=E,this.notificationUtilsService=A,this.presenceUtilsService=M,this.reactionUtilsService=V,this.recorderUtilsService=q,this.selectionUtilsService=ae,this.tagUtilsService=fe,this.usersService=ie,this.docService=Ce,this.commentAnnotationsResolverService=xe,this.reactionAnnotationsResolverService=ke,this.recorderAnnotationsResolverService=ye,this.notificationResolverService=Oe,this.activityResolverService=Ne}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",i),null}}getFirestorePath({feature:e,properties:t,documentPaths:i,apiKey:a}){try{if(!a)return;let{documentId:l,organizationId:s,folderId:d}=t;s||(s=i?.organizationId);let g=new PL({apiKey:a,documentId:l?`${l}`:"",organizationId:s?`${s}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&g?.userConfig?`${g?.userConfig}/${t?.userId}${t?.documentId?`/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return g?.permissionsUsers?`${g?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&g?.comment?`${g?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&g?.comment?`${g?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return g?.lastNotificationTimestamp?`${g?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&g?.lastNotificationTimestamp?`${g?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&g?.activities?`${g?.activities}/${t?.id}`:void 0;case"allActivities":return g?.activities?`${g?.activities}`:void 0;case"allLastActivityTimestamp":return g?.lastActivityTimestamp?`${g?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&g?.lastActivityTimestamp?`${g?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&g?.area?`${g?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&g?.area?`${g?.area}`:void 0;case"allDocuments":return g?.document?`${g?.document}`:void 0;case"allLocations":return g?.location?`${g?.location}`:void 0;case"allFolders":return g?.folder?`${g?.folder}`:void 0;case"folder":return g?.folder&&t.folderId?`${g?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&g?.documentUsers?`${g?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&g?.reaction?`${g?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&g?.document?`${g?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return g?.organization?`${g?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&g?.document?`${g?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&g?.folder?`${g?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&g?.location&&t?.id?`${g?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&g?.documentUsers?`${g?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return g?.users?`${g?.users}`:void 0;case"allFolderUsers":return g?.users?`${g?.users}`:void 0;case"allOrganizationGroups":return g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return g?.users?`${g?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&g?.notificationViews?`${g?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&g?.documentViews?`${g?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&g?.documentViews?`${g?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&g?.locationViews?`${g?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&g?.locationViews?`${g?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&g?.docNotification?`${g?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&g?.docNotification?`${g?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&g?.notificationUsers?`${g?.notificationUsers}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&g?.notificationUsers?`${g?.notificationUsers}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(l){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",l);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"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(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:i,apiKey:a,useFirestore:l}){try{if(!a)return;let{documentId:s,organizationId:d}=t;d||(d=i?.organizationId);let g=new dv({apiKey:a,documentId:s?`${s}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&g?.userConfig?`${g?.userConfig}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&g?.comment?`${g?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&g?.globalContacts?`${g?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&g?.globalContacts?`${g?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&g?.groupContacts?`${g?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&g?.groupContacts?`${g?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&g?.logins?`${g?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&g?.logins?`${g?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&g?.logins?`${g?.logins}${t?.userId}`:void 0;case"customerMetadata":return g?.customerMetadata?`${g?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&g?.arrow?`${g?.arrow}`:void 0;case"arrow":return t?.documentId&&g?.arrow&&t.id?`${g?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&g?.cursor?`${g?.cursor}`:void 0;case"cursor":return t?.documentId&&g?.cursor&&t.id?`${g?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&g?.flock&&t.id?`${g?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&g?.flock&&t.id?`${g?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&g?.huddle?`${g?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&g?.huddle?`${g?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&g?.huddle?`${g?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&g?.huddle?`${g?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&g?.liveState?`${g?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&g?.liveState?`${g?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&g?.liveState&&t?.id?`${g?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&g?.liveStateSingleEditorMode?`${g?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&g?.liveState?`${g?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&g?.liveState?`${g?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&g?.liveState&&t?.id?`${g?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&g?.presence&&t?.userId?`${g?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&g?.presence?`${g?.presence}`:void 0;case"workspaceIam":return g?.workspaceIam?`${g?.workspaceIam}`:void 0;case"selection":return t?.documentId&&g?.selection&&t?.userId?`${g?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&g?.selection?`${g?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&g?.syncVideoPlayer?`${g?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&g?.tag?`${g?.tag}`:void 0;case"tag":return t?.documentId&&g?.tag&&t?.id?`${g?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&g?.userContactUs?`${g?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&g?.userFeedback?`${g?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&g?.userReportBugs?`${g?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&g?.comment?`${g?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&g?.crdt?`${g?.crdt}`:void 0;case"crdtData":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&g?.crdt&&t?.id&&t?.versionId?`${g?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&g?.crdt&&t?.id&&t?.messageId?`${g?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&g?.documentIam?`${g?.documentIam}`:void 0;case"allDocuments":return!l&&g?.docs&&t?.documentId?`${g?.docs}/${t?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&g?.area?`${g?.area}`:void 0;case"area":return!l&&t?.id&&g?.area?`${g?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&g?.folder?`${g?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&g?.documentIam?`${g?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&g?.organizationIam?`${g?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&g?.reaction?`${g?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"organizationMetadata":return!l&&g?.organizationMetadata?`${g?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&g?.heartbeat?`${g?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return g?.heartbeat?`${g?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&g?.heartbeatByDocument?`${g?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return g?.heartbeatByDocument?`${g?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&g?.views?`${g?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&g?.views?`${g?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&g?.views?`${g?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&g?.organizationNotificationsWithDocumentId?`${g?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&g?.organizationNotificationsWithDocumentId?`${g?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&g?.organizationNotificationsUsers?`${g?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&g?.organizationNotificationsUsers?`${g?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",s);return}}resolveAnnotations(i){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=ot(),l=Jb.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:l,source:"internal",payload:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let a=ot(),l=Xb.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:l,source:"internal",payload:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let a=ot(),l=Qb.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:l,source:"internal",payload:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(b){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:s=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:g=!1,shouldRecorderResolverAwait:u=!1}){try{if(this.usersService.userDataProviderAvailable()){let E=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(E=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}case"allActivities":{t&&typeof t=="object"&&(E=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(t)?t:Object.values(t)));break}default:E=[]}if(E?.length){let A=ot(),M=xc.GET_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.FORMAT_RESPONSE,source:"internal",moduleName:M,payload:{userIds:E,feature:e,forceResolve:a}}),i?yield this.usersService.resolveUsers({userIds:E,forceResolve:a,feature:e,uniqueId:A,moduleName:M}):this.usersService.resolveUsers({userIds:E,forceResolve:a,feature:e,uniqueId:A,moduleName:M})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let E=[];switch(e){case"allDocNotifications":case"allUserNotifications":{t&&typeof t=="object"&&(E=this.notificationUtilsService.getCustomNotificationIdsToResolve(t),E=E.filter(A=>!this.notificationResolverService.getNotificationById(A)));break}default:E=[]}if(E?.length){let A=ot(),M=dQ.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:Sl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:s}}),s?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.notificationResolverService.resolveNotifications({request:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let E=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);E=[...E,...A],E=E.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);E=[...E,...A],E=E.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allActivities":{if(t&&typeof t=="object"){let A=Array.isArray(t)?t:Object.values(t),M=this.activityUtilsService.getEntityIdsToResolveFromActivities(A,"comment");E=[...E,...M],E=E.filter(V=>!this.commentAnnotationsResolverService.getCommentAnnotationById(V))}break}default:E=[]}if(E?.length){let A=ot(),M=Jb.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldCommentAnnotationsResolverAwait:l}}),l?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(e==="allActivities"&&t&&typeof t=="object"){let E=Array.isArray(t)?t:Object.values(t),A=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let M=[];for(let V of E)V?.id&&!this.activityResolverService.getActivityById(V.id)&&M.push(V.id);if(M.length){let V=ot(),q=mQ.GET_ACTIVITIES;this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:gs.FORMAT_RESPONSE,moduleName:q,source:"internal",payload:{activityIds:M,organizationId:A,shouldActivityResolverAwait:d}}),d?yield this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:V,moduleName:q})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(E,"reaction");if(M=M.filter(V=>!this.reactionAnnotationsResolverService.getAnnotationById(V)),M.length){let V=ot(),q=Xb.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:g}}),g?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(E,"recorder");if(M=M.filter(V=>!this.recorderAnnotationsResolverService.getAnnotationById(V)),M.length){let V=ot(),q=Qb.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:q,source:"internal",payload:{recorderAnnotationIds:M,organizationId:A,shouldRecorderResolverAwait:u}}),u?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q})}}}return t}catch(E){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",E),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(l),i),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",i),e}}mergeActivityResolverWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable())switch(t){case"allActivities":return Array.isArray(e)?e.map(i=>this.activityUtilsService.mergeActivityWithResolverData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",i),e}}mergeNotificationsWithResolvedData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(t){case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeResolvedNotificationData(l),i),{}):Array.isArray(e)?e.map(i=>this.notificationUtilsService.mergeResolvedNotificationData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",i),e}}mergeNotificationsWithResolvedData$({data:e,feature:t}){try{return this.notificationResolverService.getNotificationsById$().pipe(ue(()=>{let i=this.mergeNotificationsWithResolvedData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),le(e)}}mergeReactionAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",i),e}}mergeRecorderAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(t){case"allRecorders":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",i),e}}mergeActivitiesWithFeatureData(e){return Array.isArray(e)?e.map(t=>this.activityUtilsService.mergeActivityWithFeatureData(t)):e}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),i&&typeof i=="object"&&!Array.isArray(i))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(s,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(s,i),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.areaUtilsService.mergeAreaWithUser(l),i),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.arrowUtilsService.mergeArrowWithUser(l),i),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.cursorUtilsService.mergeCursorUserWithUser(l),i),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeCommentWithUser(l),i),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(l),i),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(i=>this.notificationUtilsService.mergeNotificationWithUser(i)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeNotificationWithUser(l),i),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.presenceUtilsService.mergePresenceUserWithUser(l),i),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeRecorderWithUser(l),i),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeReactionWithUser(l),i),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.tagUtilsService.mergeTagWithUser(l),i),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(l),i),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(l),i),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"liveStateSingleEditorMode":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.selectionUtilsService.mergeSelectionWithUser(l),i),{}):t;case"allActivities":return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithUser(i)):t;default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",i),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ue(()=>{let i=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),le(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ue(()=>{let i=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),le(e)}}mergeRecorderAnnotationsWithData$({data:e,feature:t}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ue(()=>{let i=this.mergeRecorderAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),le(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ue(()=>{let i=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof i=="object"?{data:JSON.parse(JSON.stringify(i)),operation:t?.operation??null}:{data:i,operation:t?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),le(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ue(i=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:i});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),le(e)}}handleDataStripping(l){return Q(this,arguments,function*({feature:e,data:t,actionType:i,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return yield this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:i,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);case"recorder":return this.recorderUtilsService.stripRecorderAnnotationData({data:t,actionType:i});default:return{originalData:t,strippedData:null}}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",s),{originalData:t,strippedData:null}}})}formatData({feature:e,data:t,properties:i,offset:a,isRealtimeDb:l}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let s=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return l?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,s);case"notificationViewsTimestamp":return{views:{[i.user??""]:t}};case"documentUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"documentDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"documentMetadataViews":return l?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return l?t:{metadata:t};case"locationUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"locationDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"locationViews":return l?t:{location:t};case"docNotificationViews":return l?t:{views:t.views};case"userNotificationViews":return l?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",s),t}}modifyAndSetData(l){return Q(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let s=yield this.modifyData({feature:e,data:t});i.next({data:s,operation:a})}catch(s){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",s)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:i}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(i??{}).includes(t.doc.id);if(i?.[t.doc.id]){let a=t.doc.data(),l=i?.[t.doc.id];return a?.lastUpdated===l?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(i){return Q(this,arguments,function*({feature:e,data:t}){try{return yield this.formatResponse({feature:e,data:t})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),t}})}addMetadata(e,t){try{return e&&typeof e=="object"&&!Array.isArray(e)?k(f({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",i),e}}setDataInLocal(d){return Q(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:s=null}){try{let u={comment:"allComments",reaction:"allReactions"}[e];if(!u)return null;let b=t?.metadata?.documentId,E=t?.metadata?.veltFolderId;return Object.keys(i).filter(A=>A.includes(u)&&(!b||A.includes(b)||E&&A.includes(E))).forEach(A=>{let M=i[A]?.subject?.getValue()??{};a==="DELETE"?l&&M?.data?.[l]&&(delete M?.data?.[l],i[A]?.subject&&i[A].subject.next({data:M?.data,operation:s})):i[A]?.subject?.next({data:k(f({},M?.data),{[t?.annotationId]:t}),operation:s})}),null}catch(g){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",g),null}})}handleCommentEncryption(s){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l})}catch(d){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",d),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:i})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",l),e}})}rtdbDefaultTransactionCallback(e,t){try{let i=f({},e||{});return Object.entries(t).forEach(([a,l])=>{l==null?delete i[a]:i[a]=l}),i}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",i),e}}};o.\u0275fac=function(t){return new(t||o)(X(sS),X(I_e),X(E_e),X(cv),X(T_e),X(tr),X(w_e),X(RL),X(NL),X(x),X(A_e),X(LL),X(P_e),X(AL),X(_p),X(R_e),X(N_e),X(An),X(ct),X(rl),X(Hs),X(ol),X(mv),X(bp))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var F_e=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{pn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe($e(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,s])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||En?.firebaseLogLevel||"silent";SX(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=Cp.getFirestoreProdDbName(l,a.firebaseOptions),g=this.configService.getProxyConfig();if(g?.v2DbHost){let u={host:g.v2DbHost,ssl:!0};g.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,s&&(u.localCache=rQ({tabManager:oQ()}));try{this.firestore$.next(aL(Vl(),u,d))}catch(b){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",b),this.firestore$.next(qb(d))}}else if(s)try{let u=Vl(),b=aL(u,{localCache:rQ({tabManager:oQ()})},d);this.firestore$.next(b)}catch{this.firestore$.next(qb(d))}else this.firestore$.next(qb(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||qb("DocumentIdDb");if(e){let t=ZD(e,"generateDocumentId");return Kb(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(X(Ft),X(We),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=s,this.databaseService=d,this.configService=g,this.docService=u,this.usersService=b,this.commentAnnotationsResolverService=E,this.reactionAnnotationsResolverService=A,this.recorderAnnotationsResolverService=M,this.notificationResolverService=V,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(q=>{if(q){this.db=q;let ae=Ur(q,".info/serverTimeOffset");this.offsetListener=mg(ae,fe=>{let ie=fe.val();this.offset=ie})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(q=>{q&&(this.firestore=q)}))}setActivityService(e){this.activityService=e}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return Q(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return ds(i).update(t)}return Promise.resolve()}catch(i){return this.loggingService.catch("Error in setupOnDisconnect:",i),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){pn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe($e(([t,i])=>!!t),ut(1),on(([t,i])=>{e({db:t,firestore:i})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,i,a,l,s){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>Q(this,[u],function*({db:d,firestore:g}){let b;t?.skipFirestore||(b=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let E=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!d){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let A,M;try{E&&(A=Ur(d,`${E}`))}catch{this.loggingService.catch("Error in dbRef")}try{b?.includes("/organizations")&&g&&b&&(M=Kb(g,`${b}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:b}),s&&s({firestoreAvailable:!!g})}catch(A){this.loggingService.catch(`Error in ${e} operation: `,A),l&&l(A)}}))}catch(d){this.loggingService.catch("Error in performDatabaseOperation:",d)}})}setData(d){return Q(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,g=>Q(this,null,function*(){if(g.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield zf(g.dbRef,()=>JSON.parse(JSON.stringify(u))):yield Wf(g.dbRef,JSON.parse(JSON.stringify(u)))}try{if(g.firestoreRef&&g.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:b,originalData:E,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ni.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),b&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:b,eventType:A,commentId:s?.targetAnnotationData?.commentId},V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:E,firestorePath:g.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(b,V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:E,firestorePath:g.firestorePath??""}))}else if(e==="recorder"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:b,eventType:A},V)),E&&(M?.isSuccess||M===null)&&this.firestore&&(yield sQ(this.firestore,q=>Q(this,null,function*(){q.set(g.firestoreRef,JSON.parse(JSON.stringify(E)))})))}else yield cQ(g.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(g){this.loggingService.catch(`Error in setData for ${e}`,g)}})}updateData(d){return Q(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,g=>Q(this,null,function*(){if(g.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield zf(g.dbRef,b=>{let E;return i?.rtdbTransactionCallback?E=i.rtdbTransactionCallback(b,u):E=this.commonDbUtilsService.rtdbDefaultTransactionCallback(b,u),JSON.parse(JSON.stringify(E))}):yield b8(g.dbRef,JSON.parse(JSON.stringify(u)))}try{if(g.firestoreRef&&g.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:b,originalData:E,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ni.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),b&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:b,eventType:A,commentId:s?.targetAnnotationData?.commentId},V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:E,firestorePath:g.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(b,V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:E,firestorePath:g.firestorePath??""}))}else if(e==="recorder"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:b,eventType:A},V)),E&&(M?.isSuccess||M===null)&&this.firestore&&(yield sQ(this.firestore,q=>Q(this,null,function*(){q.set(g.firestoreRef,JSON.parse(JSON.stringify(E)))})))}else yield cQ(g.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(g){this.loggingService.catch(`Error in updateData for ${e}`,g)}})}createActivityFromExtraData(e,t){try{if(!t?.actionType||!this.activityService)return;let i=this.activityUtilsService.buildActivityDataFromExtraData({feature:e,extraData:t});i&&this.activityService.createActivity(i)}catch(i){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",i)}}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,callback:i,errorCallback:a,extraData:l}){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:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.createActivityFromExtraData(e,l),this.performDatabaseOperation(e,t,d=>Q(this,null,function*(){d.dbRef&&(yield _8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield cL(d.firestoreRef))}else if(e==="userNotification"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:Sl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),g=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(g?.isSuccess||g===null)&&(yield cL(d.firestoreRef))}else yield cL(d.firestoreRef)}catch(g){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,g)}}),void 0,a,i)}catch(d){this.loggingService.catch(`Error in deleteData for ${e}`,d)}})}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=ot()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),ot()||"noDocumentId"}}queryData(i){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();return!e||!t?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,t):yield this.handleRtdbQuery(e,t)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,t){return Q(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let i=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=ZD(this.firestore,i);t?.useCollectionGroup&&(a=iQ(this.firestore,i));let l=t?.firestoreQuery??[],s=lQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield n_e(s).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,g),null));return d?d.data().count:0}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,d),0}else try{let d=yield o_e(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let g=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:g})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),g}}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,d),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(i){return this.loggingService.catch(`Error in Firestore query for ${e}:`,i),[]}})}handleRtdbQuery(e,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let i=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Ur(this.db,i),l=t?.rtdbQuery??[],s=Xq(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield Kq(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let g=d.val();return g?t?.skipObjectValues?g:Object.values(g??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let l=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let s=yield r_e(Kb(this.firestore,l)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=s.data();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,s),{}}}if(this.db){let l=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let s=yield Kq(Ur(this.db,l)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=s.val();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,s),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return pn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe($e(l=>!!l))]).pipe($e(([l,s])=>l?i&&!s?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),_e(([l,s])=>{try{if(i&&s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,s).subscribe(b=>{this.observablesCache[a]?.subject?.next(b)},b=>this.observablesCache[a]?.subject?.error(b));this.firestoreSubscriptions[a]=u}return new Gt(g=>{let u=this.observablesCache[a]?.subject?.subscribe(b=>g.next(b),b=>g.error(b),()=>g.complete());return this.observablesCache[a].count+=1,()=>{u?.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(l){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleRealtimeDbListener(e,t,l).subscribe(b=>{this.observablesCache[a]?.subject?.next(b)},b=>this.observablesCache[a]?.subject?.error(b));this.rtdbSubscriptions[a]=u}return new Gt(g=>{let u=this.observablesCache[a]?.subject?.subscribe(b=>g.next(b),b=>g.error(b),()=>g.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return le({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),le({})}}),Uh(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,i){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),l=`${e}-${JSON.stringify(t)}`;return a?new Gt(s=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,s,t):this.setupDocumentListener(i,a,e,s,t);return()=>{s.complete(),s.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(_e(s=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:s})),_e(s=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:s,feature:e}):le(s)),_e(s=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:s,feature:e}):le(s)),_e(s=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:s,feature:e}):le(s)),xt(Jt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),le({}))}setupCollectionListener(e,t,i,a,l){let s=`${i}-${JSON.stringify(l)}`,d=ZD(e,t);if(l?.useCollectionGroup&&(d=iQ(e,t)),l?.useQuery&&l?.firestoreQuery){let b=l?.firestoreQuery??[];d=lQ(d,...b)}let g=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),aQ(d,b=>{try{let E=JSON.parse(JSON.stringify(this.observablesCache[s]?.subject?.getValue()?.data??{})),A=null,M=!1;b?.docChanges()?.length?b.docChanges().forEach(V=>{["allComments","allReactions","allRecorders"].includes(i)&&!g&&V.type!=="removed"&&u.push(V.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:V,cache:this.observablesCache[s]?.subject?.getValue()?.data??{}})||(M=!0,Object.assign(E,this.handleCollectionChange(V,E)),V.type==="removed"&&(A||(A={type:V.type,ids:[]}),A.ids.push(V.doc.id)))}):M=!0,M&&(["allComments","allReactions","allRecorders"].includes(i)&&u?.length&&(this.commonDbUtilsService.resolveAnnotations({data:u,feature:i}),u=[]),this.commonDbUtilsService.modifyAndSetData({feature:i,data:E,subscriber:a,operation:A})),g=!1}catch(E){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,E),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(E,i,a)}},b=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,b),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(b,i,a)})}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,i,a,l){let s=Kb(e,t);return aQ(s,d=>{try{let g=d.data()||{};l?.field&&(g=g?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:g,subscriber:a,operation:null})}catch(g){this.handleListenerError(g,i,a)}},d=>this.handleListenerError(d,i,a))}handleListenerError(e,t,i){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,i){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),le({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let s=t?.rtdbQuery??[];l=Xq(l,...s)}return this.objectValFromChildEvents(l,e).pipe(Jn(s=>(this.loggingService.catch(`RTDB listener error for ${e}:`,s),le({}))),ue(s=>(s===null&&(s={}),s&&typeof s=="object"?Object.entries(s??{}).reduce((g,[u,b])=>(g[u]=this.commonDbUtilsService.addMetadata(b,t),g),{}):this.commonDbUtilsService.addMetadata(s,t))),_e(s=>this.commonDbUtilsService.modifyData({feature:e,data:s})),_e(s=>this.usersService.getUserById$().pipe(ue(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:s}),operation:null})))))}pushData(a){return Q(this,arguments,function*({feature:e,properties:t,data:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${e}`,"color: green;"),this.performDatabaseOperation(e,t,l=>Q(this,null,function*(){if(l.dbRef){let s=C8(l.dbRef);yield Wf(s,JSON.parse(JSON.stringify(l.data)))}}),i)}catch(l){this.loggingService.catch(`Error in pushData for ${e}`,l)}})}streamChildAdded({feature:e,properties:t,afterTs:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${e}`,"color: green;"),new Gt(a=>{let l=null,s=!1,d=({db:g})=>{if(!g||s||!this.authService.getUser())return;let u=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!u)return;let E=Ur(g,u),A=!1,M=ae=>{try{let fe=ae.val();if(A){if(i!=null&&fe?.timestamp!=null&&fe.timestamp<=i)return;a.next(fe)}}catch(fe){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,fe)}},V=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(fe){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,fe)}};Jq(E,M,V);let q=mg(E,()=>{A=!0},V,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),cw(E,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{s=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),le(null)}}objectValFromChildEvents(e,t){return new Gt(i=>{let a={},l=!1,s=null,d=V=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,V),i.error(V)}catch{}},g=V=>{try{if(!Mr(V,s)){let q=JSON.parse(JSON.stringify(V));s=q,i.next(q)}}catch{}},u=V=>{try{V.key&&(a[V.key]=V.val(),l&&g(f({},a)))}catch{}},b=V=>{try{V.key&&(a[V.key]=V.val(),l&&g(f({},a)))}catch{}},E=V=>{try{V.key&&(delete a[V.key],l&&g(f({},a)))}catch{}},A=V=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};s=q,i.next(q),l=!0}}catch{}};Jq(e,u,d),wve(e,b,d),Dve(e,E,d);let M=mg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),cw(e,"child_added",u),cw(e,"child_changed",b),cw(e,"child_removed",E)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(X(sS),X(We),X(rd),X(tr),X(x),X(F_e),X($n),X(Ft),X(ct),X(An),X(rl),X(Hs),X(ol),X(mv))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vv=(()=>{let o=class o{static uniquifySvgIds(e){let t=`v${++o.idCounter}`,i=/\bid="([^"]+)"/g,a=[],l;for(;(l=i.exec(e))!==null;)a.push(l[1]);let s=e;for(let d of a){let g=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;s=s.replace(new RegExp(`\\bid="${g}"`,"g"),`id="${u}"`),s=s.replace(new RegExp(`url\\(#${g}\\)`,"g"),`url(#${u})`),s=s.replace(new RegExp(`href="#${g}"`,"g"),`href="#${u}"`)}return s}constructor(e,t,i){this.domService=e,this.loggingService=t,this.sanitizer=i,this.emojis={},this.emojisSignal=Ae({}),this.rawSvgs={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let l=o.Icons[a];this.rawSvgs[a]=l,this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(l)))}),Object.keys(o.GIF_PATHS).forEach(a=>{let l=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(l))}),this.emojisSignal.set(f({},this.emojis))}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{let t=this.rawSvgs[e];return t?this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(t))):this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let i=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(i=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(i))}catch{return""}}setEmojiList(e){try{this.emojis={},this.rawSvgs={},Object.keys(e).forEach(t=>{let i=e[t];if(i.svg)this.rawSvgs[t]=i.svg,this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(i.svg)));else if(i.url){let a=`<img src="${i.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else i.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(i.emoji)))}),this.emojisSignal.set(f({},this.emojis))}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.idCounter=0,o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
222
+ `+dl),um&&TL([ze,Ge,$r],Ks=>{dl=c3(dl,Ks," ")}),ie&&Ch?ie.createHTML(dl):dl},o.setConfig=function(){let yn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};jC(yn),LC=!0},o.clearConfig=function(){gd=null,LC=!1},o.isValidAttribute=function(yn,Ke,Ut){gd||jC({});let sn=zi(yn),Ho=zi(Ke);return $C(sn,Ho,Ut)},o.addHook=function(yn,Ke){typeof Ke=="function"&&s3(Ue[yn],Ke)},o.removeHook=function(yn,Ke){if(Ke!==void 0){let Ut=cWe(Ue[yn],Ke);return Ut===-1?void 0:dWe(Ue[yn],Ut,1)[0]}return v_e(Ue[yn])},o.removeHooks=function(yn){Ue[yn]=[]},o.removeAllHooks=function(){Ue=C_e()},o}var g3=y_e();var x_e={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Be=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new it,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new it,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new ur),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),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.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let s=[];return l.forEach(d=>{if(!Co(d))if(d instanceof HTMLElement){if(d.className.includes("cdk-overlay-container")||d.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(d.className.includes("cdk-overlay")){let g=!1;d.childNodes.forEach(u=>{Co(u)&&(g=!0)}),g||s.push(d)}else s.push(d)}else s.push(d)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Nr(),on(([s,d])=>{try{let g=d.filter(b=>!s.includes(b)),u=s.filter(b=>!d.includes(b));u.length&&u.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),g.length&&g.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",A=>{let M=this.calculateScreenSize();this.currentScreenSize$.next(M)})})}catch(g){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",g)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?ohe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):ihe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(l){this.loggingService.catch("Error in DomService constructor: ",l)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}setDynamicIdPatterns(e){try{let t=e.map(i=>typeof i=="string"?new RegExp(i):i).filter(Boolean);t.length&&(this.dynamicIdPatterns=t)}catch(t){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",t)}}isLikelyDynamicId(e){try{return e?this.dynamicIdPatterns.some(t=>t.test(e)):!1}catch{return!1}}getStableAttributes(e){try{let t={};if(!e.getAttributeNames)return t;let i=new Set(["id","class","style"]);return e.getAttributeNames().forEach(l=>{if(i.has(l)||l.includes("snippyly")||l.includes("velt"))return;let s=e.getAttribute(l);s&&s.length<=256&&(t[l]=s)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],l=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((d,g)=>{let u=l.findIndex(E=>d.startsWith(E)),b=l.findIndex(E=>g.startsWith(E));return(u===-1?99:u)-(b===-1?99:b)}).slice(0,4).forEach(d=>{let g=CSS.escape(t[d]);a.push(`[${d}="${g}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,s=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),s++,s>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return Wpe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],s=e,d=0;for(;s&&s!==document.documentElement&&d<i;){let E=this.buildRobustXPathSegment(s);if(E&&(l.unshift(E),this.isStrongAnchorSegment(E)))break;s=s.parentElement,d++}if(l.length===0)return;let u=(a?"/":"//")+l.join("/");return l.some(E=>E.includes("[@")||E.includes("[contains(@class"))?u:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),i=e.id;if(i&&!this.isLikelyDynamicId(i)&&document.querySelectorAll(`[id="${CSS.escape(i)}"]`).length===1)return`*[@id=${this.escapeXPathValue(i)}]`;let a=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let E of a){let A=e.getAttribute(E);if(A)return`${t}[@${E}=${this.escapeXPathValue(A)}]`}let l=Array.from(e.attributes).filter(E=>E.name.startsWith("data-")&&!E.name.includes("snippyly")&&!E.name.includes("velt")&&E.value.length<100).sort((E,A)=>E.value.length-A.value.length);if(l.length>0){let E=l[0];return`${t}[@${E.name}=${this.escapeXPathValue(E.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let g=e.getAttribute("name");if(g)return`${t}[@name=${this.escapeXPathValue(g)}]`;let u=e.getAttribute("type");if(u)return`${t}[@type=${this.escapeXPathValue(u)}]`;let b=Array.from(e.classList||[]).filter(E=>E.length>0&&E.length<40&&!E.includes("yui")&&!E.includes("velt")&&!E.includes("snippyly")&&!this.excludeClassList.includes(E)).slice(0,2);if(b.length>0){let E=b.map(A=>`contains(@class, ${this.escapeXPathValue(A)})`).join(" and ");return`${t}[${E}]`}if(e.parentElement){let E=Array.from(e.parentElement.children).filter(A=>A.tagName===e.tagName);if(E.length>1){let A=E.indexOf(e)+1;return`${t}[${A}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(e.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(a=>e.includes(`[@role='${a}']`))||["data-region","data-instanceid","data-activityid"].some(a=>e.includes(`[@${a}=`)))}catch{return!1}}escapeXPathValue(e,t=!0){try{return e.includes("'")?e.includes('"')?`concat(${e.split("'").map(l=>`'${l}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(s=>`'${s}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(e){try{let t=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),i=[];for(let a=0;a<t.snapshotLength;a++){let l=t.snapshotItem(a);l instanceof Element&&i.push(l)}return i}catch{return[]}}generateAnchorRecord(e,t){try{let i=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Zr(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),i&&a){let l=this.generateAnchorRecordForElement(a,t);l&&(i.parent=l)}return i}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",i),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let i=e,a=i.tagName?.toUpperCase();if(!a)return null;let l=i.id&&!this.isLikelyDynamicId(i.id)?i.id:void 0,s=this.getStableAttributes(i),d=this.buildStableElementSelector(i,s),g=this.getVisibleText(i),u=this.hashText(g||""),b=this.generateRobustXPath(i),E=this.getXPath(i),A=this.getXPath(i,!0),M=this.getXPath(i,!0,!0);return{version:"1.0",id:l,tagName:a,elementSelector:d,robustXPath:b||void 0,xPath:E||void 0,fXPath:A||void 0,cfXPath:M||void 0,contentHash:u?{value:u,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",i),null}}resolveAnchorRecord(e){try{let t=[],i=null,a=(u,b,E=0)=>{let A=[],M=E;if(A.push({method:b,score:E}),e.tagName&&u.tagName?.toUpperCase()===e.tagName&&(M+=10,A.push({method:"tagName-match",score:10})),e.contentHash?.value){let V=this.getVisibleText(u);this.hashText(V)===e.contentHash.value&&(M+=30,A.push({method:"contentHash-match",score:30}))}t.push({el:u,score:M,by:b,scoreBreakdown:A})};if(e.id){let u=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(u.length===1)return{element:u[0],matchedBy:"id",score:90};u.length>1&&u.forEach(b=>a(b,"id-duplicate",70))}if(e.elementSelector){let u=document.querySelectorAll(e.elementSelector);if(u.length===1)return{element:u[0],matchedBy:"element-selector",score:80};u.forEach(b=>a(b,"element-selector-duplicate",60))}e.robustXPath&&this.getAllElementsFromRobustXPath(e.robustXPath).slice(0,20).forEach(A=>a(A,"robustXPath",50)),e?.parent&&(i=this.resolveAnchorRecord(e.parent),i.element&&i.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(b=>a(b,"parent+tag",40)));let l=(u,b,E)=>{if(!u)return;let A=this.getElementFromXPath(u);A&&a(A,b||"xpath",E||30)};if(l(e.xPath,"xPath",30),l(e.cfXPath,"cfXPath",30),l(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let b=E=>{let A=0;for(let M=0;M<E.length&&A<400;M++){let V=E[M];if(A++,!this.isElementVisible(V))continue;let q=this.getVisibleText(V),ae=this.hashText(q);ae&&ae===e.contentHash?.value&&a(V,"contentHash",15)}};if(i?.element&&i?.element instanceof Element){let E=i?.element?.querySelectorAll("*");b(E)}}if(!t.length)return{element:null};t.sort((u,b)=>b.score-u.score);let s=t[0].score,d=t.filter(u=>u.score===s);if(d.length>1){let u=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let b of u)if(b.path){let E=this.getElementFromXPath(b.path);if(E){let A=d.find(M=>M.el===E);if(A)return{element:A.el,matchedBy:`${A.by}+position`,score:A.score,scoreBreakdown:A.scoreBreakdown}}}}let g=t[0];return{element:g.el,matchedBy:g.by,score:g.score,scoreBreakdown:g.scoreBreakdown}}catch(t){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",t),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ue(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.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.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),this.onDocumentClick()}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(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}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.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let i=t.filter(a=>a.type==="childList").filter(a=>{let l=a.target;return a.removedNodes.forEach(s=>{let d=s;if(typeof d.getAttribute=="function"){let g=d.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(g!==null&&g!==""){let u=this.xpathCacheId.get(g);u!==void 0&&(this.xpathCacheId.delete(g),this.xpathCache.delete(u))}}}),Co(l)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(i.filter(a=>!this.isAnimatingElement(a.target))):this.childListMutation$.next(i),i.push(...t.filter(a=>a.type==="attributes").filter(a=>!Co(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let l=a.target;return l?.classList?.contains("snippyly-sidebar-panel")?!1:l?!l.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),i=i.filter(a=>{let l=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(s=>{a.target?.closest(s)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Zr(a.target)),this.animationFilterEnabled&&(i=i.filter(a=>!this.isAnimatingElement(a.target))),i.length&&this.mutation$.next(i)}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let e=window;return e.gsap||e.TweenMax||e.TweenLite||e.TimelineMax||e.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):e.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):e.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):e.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):e.lottie||e.Lottie||e.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(e){try{if(!e||typeof e.closest!="function")return!1;let t=window;if(t.gsap&&typeof t.gsap.isTweening=="function"){if(t.gsap.isTweening(e))return!0;if(typeof t.gsap.getTweensOf=="function")try{if(t.gsap.getTweensOf(e).length>0)return!0}catch{}}else if(t.TweenMax&&typeof t.TweenMax.isTweening=="function"){if(t.TweenMax.isTweening(e))return!0;if(typeof t.TweenMax.getTweensOf=="function")try{if(t.TweenMax.getTweensOf(e).length>0)return!0}catch{}}let i=e.style?.cssText||"";if(i){let d=i.includes("transform")||i.includes("translate3d")||i.includes("translate(")||i.includes("scale3d")||i.includes("rotate"),g=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(g||u))return!0}if(e.style&&(e.style.animation!==""&&e.style.animation!=="none"||e.style.transition!==""&&e.style.transition!=="none")||e.classList?.contains("animate")||e.classList?.contains("animating")||e.classList?.contains("animated")||e.classList?.contains("animation"))return!0;let a=this.staticAnimationCache.get(e);if(a!==void 0)return a;let l=!1,s=e.className||"";return typeof s=="string"&&(s.includes("slider")&&(s.includes("bullet")||s.includes("pagination"))&&(l=!0),s.includes("swiper-pagination")&&(l=!0)),!l&&(e.hasAttribute("data-aos")||e.hasAttribute("data-motion"))&&(l=!0),!l&&e.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(l=!0),this.staticAnimationCache.set(e,l),l}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{Ro(Or(window,"offline").pipe(ue(()=>!1)),Or(window,"online").pipe(ue(()=>!0)),new Gt(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 t=this.calculateScreenSize();this.deviceInfo$.next(new ur),this.currentScreenSize$.next(t)})}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 t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}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 Or(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Mc}}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 t=this.getXPath(e.target),i=e.target;if(t?.includes("name()='svg'")){let u=this.getXPath(t);u&&(i=u.iterateNext()||e.target)}let a=i.getBoundingClientRect(),l=e.clientX-a.x,s=e.clientY-a.y,d=l*100/(a.width||1),g=s*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:g,leftPercentage:d}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,i=!1,a=!0,l,s=!0,d){try{let g=e,u=g?.touches?.length?g.touches[0]?.clientX:g?.clientX,b=g?.touches?.length?g.touches[0]?.clientY:g?.clientY;d&&(u=d.clientX,b=d.clientY);let E=this.getBackgroundElement(u,b,t,i);if(E&&l&&typeof l=="function"&&(E=l(E)),E){let A=this.getXPath(E),M=this.getXPath(E,!0),V=E.getBoundingClientRect(),q=u-V.x,ae=b-V.y,fe=q*100/(V.width||1),ie=ae*100/(V.height||1),Ce={xpath:A,fXpath:M,leftPercentage:fe,topPercentage:ie};if(a){let xe=this.getXPath(E,!0,!0);Ce.cfXpath=xe}if(s){let xe=this.generateAnchorRecord(E);xe&&(Ce.anchor=xe)}return Ce}else return null}catch(g){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",g),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),s=[];l.forEach(g=>{Co(g)?s=[]:Zr(g)&&s.push(g)}),a&&(s=s.filter(g=>this.isElementVisibleOnScreen(g)));let d=0;return i||s?.forEach((g,u)=>{g.tagName.toLowerCase()==="svg"&&(d=u)}),s[d]}catch(l){return this.loggingService.catch("Error in DomService getBackgroundElement: ",l),null}}getBackgroundVeltElement(e,t){try{let i=document.elementsFromPoint(e,t),a=[];return i.forEach(l=>{Co(l)&&Zr(l)&&a.push(l)}),a[0]}catch(i){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",i),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(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}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(),t=this.currentMousePosition?.pageX||e.x+200,i=Math.min(t,e.width/2),a=Math.abs(e.y),l=e.y-20;return a>50&&(l=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(i),this.loggingService.log(l),{topPositionX:i,topPositionY:l}}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,t,i){if(e){if(!i&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),l=e.style.getPropertyPriority("cursor"),s=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,s?JSON.stringify(s):""),e.style.setProperty("cursor",t,"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 t=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,i,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"),t&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,t),i&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,i))}catch(l){this.loggingService.catch("Error in DomService highlightUserElement: ",l)}}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(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,i=!1,a){try{let l=this.calculateXPath(e,t,i,a);if(l&&typeof l=="string"&&l.includes("/svg")){let s=l.split("/"),d=!1;s.forEach((g,u)=>{g.includes("svg")&&(d=!0),d&&(s[u]="svg:"+g)}),l=s.join("/")}return l}catch(l){this.loggingService.catch("Error in DomService getXPath:",l)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,i,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&&!t)return"//*[@id='"+e.id+"']";if(i&&e.className&&e.className.split){let s=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(s){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),g=Array.from(e.parentNode?.children||[]).filter(u=>u.nodeType===1&&u.tagName===e.tagName?u.className?.split(" ")?.filter(E=>E?.includes("snippyly")||E?.includes("velt")||["show-pin-cursor"].includes(E))[0]===s:!1);if(g.length>1){let u=g.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(s){return s.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,i)+"/"+e.tagName.toLowerCase()+(l.length>1?"["+([].indexOf.call(l,e)+1)+"]":"")}}catch(l){this.loggingService.catch("Error in DomService calculateXPath:",l)}}getElementFromXPath(e,t=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 i=this.getXPath(e,!1,!1,t);if(i){let a=i?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let l=ot();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,l),this.xpathCacheId.set(l,e)}return this.xpathCache.set(e,a),a}return null}catch(i){return this.loggingService.catch("Error in DomService getElementFromXPath:",i),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let i=this.resolveAnchorRecord(e.anchor);i?.element&&(t=i.element)}else e?.xpath?t=this.getElementFromXPath(e.xpath):e?.cfXpath?t=this.getElementFromXPath(e.cfXpath):e?.fXpath&&(t=this.getElementFromXPath(e.fXpath));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",t),null}}getElementFromTargetTextRange(e){try{let t=null;if(e?.commonAncestorContainerAnchor){let i=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);i?.element&&(t=i.element)}else e?.commonAncestorContainer&&(t=this.getElementFromXPath(e.commonAncestorContainer));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",t),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],t=[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 i=new r3;return i.screenWidth=Math.max(...t),i.screenHeight=Math.max(...e),i.screenScrollHeight=this.pageScrollHeight,i}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new r3}}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 i=new DOMParser().parseFromString(e,"text/html");i.querySelectorAll("[data-snippyly-cache-id]").forEach(b=>{b.removeAttribute("data-snippyly-cache-id")}),i.querySelectorAll("[data-velt-cache-id]").forEach(b=>{b.removeAttribute("data-velt-cache-id")}),i.querySelectorAll(".comment-text-highlight").forEach(b=>{b?.parentNode?.insertBefore(document.createTextNode(b?.textContent),b),b.remove()});let d=document.createNodeIterator(i,NodeFilter.SHOW_COMMENT),g;for(;g=d.nextNode();)g?.remove();return this.mergeAdjacentTextNodes(i.body),this.sanitizeHtml(i.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let i=t.nextSibling;for(;i&&i.nodeType===Node.TEXT_NODE;)t.textContent+=i.textContent,i.remove(),i=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let i=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(i,this.pageScrollHeight),this.nodeMap[i]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let i=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];i.push(...a),i=Array.from(new Set(i));let l=i.map(u=>u.classList.contains("velt-annotation-draft-checked")?(u.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(u,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(u,"velt-comment-dialog-shake"),u.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||u.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(u,"velt-annotation-draft-checked")},100),u.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(u=>u),s=Object.keys(this.getRecordingInProgress()||{});l=[...l,...s];let d=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let u=[];Object.keys(d).forEach(b=>{if(d[b]?.type==="tag"){let E=d[b];E?.to?.length||l.includes(b)||u.push(E)}else d[b]?.comments?.length||l.includes(b)||u.push(d[b])}),this.deleteAnnotations$.next(u),this.deleteAnnotations$.next([])}let g={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(g[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(g[u]=d[u]);break;default:d[u]?.type!==t&&(g[u]=d[u]);break}}),Object.keys(g).forEach(u=>{let b=g[u]?.multiThreadAnnotationId;b&&!g[b]&&(g[b]={annotationId:b,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(g)&&this.selectedAnnotationsMap$.next(g),this.setDialogOpenedInSidebar(!1)}catch(i){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",i)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(k(f({},this.recordingInProgress$.value),{[e]:t}));else{let i=this.recordingInProgress$.value;delete i[e],this.recordingInProgress$.next(i)}}catch(i){this.loggingService.catch("Error in DomService setRecordingInProgress: ",i)}}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=[],t=Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),i=Array.from(document.querySelectorAll(`${U.TAGS.VELT_COMMENT_DIALOG}`));return[...t,...i].forEach(l=>{if(l?.shadowRoot){let s=l.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=l.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(s?.shadowRoot){let d=s.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}else{let d=l.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let i={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(i[a]=t[a]);break;default:t[a].type===e&&(i[a]=t[a]);break}}),i}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ue(t=>{if(e){let i={};return Object.keys(t).forEach(a=>{t[a].type===e&&(i[a]=t[a])}),i}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ue(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,t,i,a=!1,l){try{i==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));s[e.annotationId]&&!a?delete s[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(s[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(s),Object.keys(d).forEach(g=>{s[g]||delete d[g]}),this.selectedAnnotationsLocationMap$.next(d)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,t){try{let i=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));i?.[e]!==t&&(i[e]=t,this.selectedAnnotationsLocationMap$.next(i))}catch(i){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",i)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(i=>{t[i.annotationId]&&(t[i.annotationId]=i)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),le([])}}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(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),le([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let i={offsetTop:0,offsetLeft:0},a=e;if(a===t){let l=window.getComputedStyle(e);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(i.offsetLeft=e?.offsetLeft||0,i.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let s=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let g=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-g.left,i.offsetTop+=u.top-g.top}}else s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let d=window.getComputedStyle(a);d.position==="static"&&d.transformStyle!="preserve-3d"&&d.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0)}}else{let s=window.getComputedStyle(a);s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop)}return i}catch(i){return this.loggingService.catch("Error in DomService getElementOffset: ",i),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:i,top:a,bottom:l}=e?.getBoundingClientRect();return t>0||i>0||a<window.innerHeight&&l>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,i=window.getComputedStyle(t);return!(i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Gt(e=>{let t=Or(document,"mousedown").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=Or(document,"mousemove").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=Or(document,"mouseup").pipe(ue(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),s=t.pipe(_e(d=>i.pipe(Nr(),ue(([g,u])=>({startPoint:d,prevPoint:g,curPoint:u})),zo(a)))).subscribe(e);return()=>s.unsubscribe()})}drawRectangle(e,t){let i=document.querySelector(".rectangle");i||(i=document.createElement("div"),this.addClassToElement(i,"rectangle"),i.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),i.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(i));let a=Math.abs(t.x-e.x),l=Math.abs(t.y-e.y),s=Math.min(e.x,t.x),d=Math.min(e.y,t.y);return i.style.width=`${a}px`,i.style.height=`${l}px`,i.style.left=`${s}px`,i.style.top=`${d}px`,i.style.position="absolute",i.style.border="2px dashed #f00",i.style.pointerEvents="none",i.style.zIndex="2147483577",i}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 t={},i=e.commonAncestorContainer;i?.nodeType===Node.TEXT_NODE&&(i=i.parentElement);let a=document.body;if(i){let s=this.getTextXPath(i);this.isXpathWithId(s)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let s=this.getElementFromXPath(t.commonAncestorContainer);if(s){t.commonAncestorContainerFXpath=this.getXPath(s,!0),t.commonAncestorContainerCFXpath=this.getXPath(s,!0,!0);let d=this.generateAnchorRecord(s);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=a0(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,i=e.previousSibling;for(;i;)i.nodeType===Node.TEXT_NODE&&t++,i=i.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let i=e?.closest("picture");return i?i?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,elementQuerySelectors:i}){try{let a=[];if(e?.length)for(let l=0;l<e.length;l++){let s=document.getElementById(e[l]);s&&a.push(s)}if(t?.length)for(let l=0;l<t.length;l++){let s=document.getElementsByClassName(t[l]);for(let d=0;d<s.length;d++){let g=s[d];g&&g instanceof HTMLElement&&a.push(g)}}if(i?.length)for(let l=0;l<i.length;l++){let s=document.querySelectorAll(i[l]);for(let d=0;d<s.length;d++){let g=s[d];g&&g instanceof HTMLElement&&a.push(g)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementById(t[i]);if(a&&a.contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",i),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementsByClassName(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",i),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.querySelectorAll(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",i),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(i){this.loggingService.catch("Error in DomService addClassToElement: ",i)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(i){this.loggingService.catch("Error in DomService removeClassFromElement: ",i)}}isElementInsideParentWithAttribute(e,t,i){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===i)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(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}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(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}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),le(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let i=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(i&&i.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.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(t?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let i=t.innerHTML;return i=i.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),i}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(l){return i.test(l.innerHTML)};var t=a;let i=/^\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(i){this.loggingService.catch("Error in DomService removeEmptyElements: ",i)}}normalizeWhitespace(e){try{e.childNodes.forEach(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),g3.sanitize(e,x_e)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return g3.sanitize(e,x_e)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ur;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),le(new ur)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID);!e&&this.tabId&&(e=this.tabId,sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e)),!this.tabId&&e&&(this.tabId=e);let t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=ot(),this.tabId=e,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(t){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",t)}}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 ur}}isMobileDevice(){try{return new ur().getDeviceType()===Bi.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ur().getDeviceType()===Bi.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ur().getDeviceType()===Bi.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(i=>{t.setAttribute(i.nodeName,i.nodeValue)}),e.childNodes.forEach(i=>{i.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(i)):i.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(i.nodeValue))}),t}catch(i){return this.loggingService.catch("Error in DomService deepCloneElement: ",i),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(i=>{if(this.removeWireframeSuffixFromTags(i),i.tagName.toLowerCase().endsWith("-wireframe")){let a=i.tagName.toLowerCase().replace("-wireframe",""),l=document.createElement(a);for(Array.from(i.attributes).forEach(s=>{l.setAttribute(s.name,s.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new ur().getDeviceType()===Bi.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(X(lt),X(ki),X(x),X(Rd))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var We=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=s,this.analyticsService=d,this.loggingService=g,this.user$=new Se(null),this.userOptions$=new Se(null),this.userContacts$=new Se(null),this.userOrganization$=new Se(null),this.isPrivateCommentsEnabled$=new Se(!1),this.providedUser=new ra,this.firebaseConfig$=new Se(null),this.advancedQueries$=new Se(null),this.planDetails$=new Se(null),this.signOutPreviousUser$=new Se(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.onRetrySubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{try{let u=this.configService.getAuthProxyHost();if(u){let b=this.afAuth?.config;b&&(b.apiHost=u,b.tokenApiHost=u)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(u=>{this.config=u}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=fr(this.afAuth).pipe(yo(this.afAuth.currentUser),Nr(),_e(([u,b])=>this.domService.onNetworkStatusChange$().pipe($e(E=>E),ut(1),ue(()=>({previousUser:u,currentUser:b}))))).subscribe(E=>Q(this,[E],function*({previousUser:u,currentUser:b}){if(!b&&u){let A=u?.stsTokenManager?.expirationTime,M=new Date().getTime(),V=A-M;M>A&&(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&u?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(K.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:V,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),u=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",u)}),this.getUser$().pipe(xt(Jt)).subscribe(u=>{let b=Uo(u);this.coreActionsService.triggerAction(Qe.USER_UPDATE,b),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:Qe.USER_UPDATE,payload:{user:b}})})}catch(u){this.loggingService.catch("Error in AuthService constructor: ",u)}}setApiKey(e,t){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),t||(t=new gL),this.configService.initConfig(t);let i=this.configService.getProxyConfig();if(i?.authHost)try{let a=this.afAuth?.config;a&&(a.apiHost=i.authHost,a.tokenApiHost=i.authHost)}catch(a){this.loggingService.catch("Error setting auth proxy config: ",a)}t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||fr(this.afAuth).pipe(ut(1)).subscribe(a=>Q(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Hm(a,!0).catch(s=>null);if(l){let{user:s}=l?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?k(f({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(i){this.loggingService.catch("Error in setApiKey: ",i)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setActivityService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setActivityService","color: green;"),this.activityService=e}catch(t){this.loggingService.catch("Error in setActivityService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}setCrdtService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCrdtService","color: green;"),this.crdtService=e}catch(t){this.loggingService.catch("Error in setCrdtService: ",t)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(K.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")}setVeltAuthProvider(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;if(!e.user)return null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let i=yield eZ(()=>window.Velt.identify(e.user,f(f({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}).catch(a=>(e.onError&&typeof e.onError=="function"&&e.onError(a),Promise.reject(a))),e.retryConfig||{retryCount:0,retryDelay:0});return i&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(Qe.ERROR).pipe($e(a=>a.code==="token_expired"),ut(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(E=>({id:E.clientDocumentId}))??[],s=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],g=this.docService?.getLocation();g&&d.push(g.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(E=>{d.push(E.location)}),(yield eZ(()=>Q(this,null,function*(){try{let E=yield e.generateToken?.();return E?window.Velt.identify(e.user,f(f({},e.options||{}),E&&{authToken:E}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:l,options:s,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!g}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return Q(this,null,function*(){try{if(e){let t=yield hc(e,e?.userId??"");localStorage.setItem(U.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return Q(this,null,function*(){try{let t=localStorage.getItem(U.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield Q1(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}setIsPrivateCommentsEnabled(e){try{this.isPrivateCommentsEnabled$.next(e)}catch(t){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",t)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),i=yield this.getUserFromStorage(t);return!i||Object.keys(i).length===0?(delete t?.color,delete t?.textColor,t):(i?.color&&(t.color=i?.color),i?.textColor&&(t.textColor=i?.textColor),t)}catch(t){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",t),e}})}updateUserIfRequired(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let t=yield this.getUserFromStorage(e),i={};e.color&&e.color!==t?.color&&(i.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(i.textColor=e.textColor),Object.keys(i).length>0&&e.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:e.clientOrganizationId,user:k(f({},i),{userId:e.userId})})}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,i,a,l){return Q(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=Qc(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let s=yield fr(this.afAuth).pipe(ut(1)).toPromise().catch(g=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),s){let g=yield Hm(s,!0).catch(A=>null);if(!g)return;let{user:u,firebaseConfig:b,advancedQueries:E}=g.claims;s?.uid!==e?.userSnippylyId||e?.groupId!==u?.groupId||e?.organizationId!==u?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,b)||this.forceReLoginRequiredForCommentViews(e)?(localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal")):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(b),this.setAdvancedQueries(E),u&&(this.providedUser.isAdmin=!!u.isAdmin),this.initializeSignedInUser(s,a,e),d=!1,this.analyticsService.trackEvent(K.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:l}))}if(d){this.analyticsService.trackEvent(K.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:l},!0,e.userSnippylyId,e.userId);let g=Gr(this.functions,Wr({url:En.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=fa(),b=(yield g({apiKey:this.apiKey,user:e,version:u,authToken:t?.authToken}))?.data;if(b.error){if(this.analyticsService.trackEvent(K.Events.Core.SDK_VALIDATE_CLIENT_FAILED,k(f({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:b.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},b),{source:l}),!0,e.userSnippylyId,e.userId),b.error&&typeof b.error=="string")if(b.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let E={code:"token_expired",message:"Token expired",error:b?.error,source:b?.source};this.coreActionsService.triggerAction(Qe.ERROR,E)}else{let E={code:"too_many_retries",message:"Token expired. Too many retries.",error:b?.error,source:b?.source};this.coreActionsService.triggerAction(Qe.ERROR,E),this.analyticsService.trackEvent(K.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:l},!0,e.userSnippylyId,e.userId)}else{let E=b;this.coreActionsService.triggerAction(Qe.ERROR,E)}throw b}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(K.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:l},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),b.firebaseConfig){this.setFirebaseConfig(b.firebaseConfig),yield this.signInWithCustomToken(e,b.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let E=yield Hm(this.afAuth.currentUser,!0).catch(V=>null);if(!E)return;let{user:A,advancedQueries:M}=E.claims;this.setAdvancedQueries(M),this.providedUser.isAdmin=!!A?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:i,autoLogin:a},this.checkForPendingLogin()}return e}catch(s){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",s),t?.throwError?Promise.reject(s):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=fa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=fa();if(e){let t=e.split("."),i=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),l=parseInt(t[2]||"0");if(i>=4&&a>=5)return i===4&&a===5&&l===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),i=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(i=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),i=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(i=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",i),!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:f(f({},En.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}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(t){this.loggingService.catch("Error in setAdvancedQueries: ",t)}}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 pn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ue(()=>this.getAdvancedQueriesEnabled()),Jn(()=>le(!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;"),fr(this.afAuth).pipe(_e(e=>e?this.user$.asObservable():le(null)),xt(Jt))}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 t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=f(f({},this.providedUser),e),t){let i=f(f({},t),e);this.updateUserInternally(i)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,i="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return bde(this.afAuth,t).then(a=>(this.analyticsService.trackEvent(K.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(K.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,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)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.setIsPrivateCommentsEnabled(!1),this.activityService?.setActivityFeatureConfig({immutable:!1,isEnabled:!1})}catch(e){this.loggingService.catch("Error in clearCache: ",e)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),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,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new ra;a.userSnippylyId=e.uid,a.type="signedIn",i&&(a=f(f({},a),i)),this.setUserToStorage(a),this.mergeUserWithProvidedUserData(a,t)}catch(a){this.loggingService.catch("Error in initializeSignedInUser: ",a)}}mergeUserWithProvidedUserData(e,t){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let i=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=ot(),l=xc.IDENTIFY;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:gi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let s=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});s&&s[e.userId]&&(i=JSON.parse(JSON.stringify(s[e.userId]||{}))),e=f(f({},e),i||{})}e.name=i?i?.name:this.providedUser?.name||e.name,e.clientUserName=i?i?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=i?i?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=i?i?.email:this.providedUser?.email||e.email,e.color=i?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=i?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=i?.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(i){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",i)}})}updateUserInternally(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||this.getPlanDetailsFromDb();let i=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=_l({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let g=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:ro.IDENTIFY,organizationId:e.clientOrganizationId}}],u=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:g}}),l=this.userPermissionService?.onResourceAccessRequired({requests:g,uniqueId:u,userId:e.userId,methodName:ro.IDENTIFY,fromCache:!1})??Promise.resolve()}let[s,d]=yield Promise.allSettled([a,l]);s.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!s.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(s.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",s.reason),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),i=k(f({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return Q(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield Gr(this.functions,Wr({url:En.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:fa(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(K.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}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($e(e=>!!e),ue(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreSignOutFuction: ",i)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(_e(e=>e?this.userOrganization$.asObservable().pipe(ue(t=>t?.metadata?.organizationId===e.organizationId?t:null)):le(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(K.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 t=yield fr(this.afAuth).pipe(ut(1)).toPromise().catch(i=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[i,a]of this.preSignOutFunctions)try{yield a(t)}catch(l){this.loggingService.catch(`Error in signOutUser ${i} function: `,l)}return this.user$.next(null),yield Hu(1e3),Sde(this.afAuth).catch(i=>{this.loggingService.catch("Error in signOutUser:",i)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return Ao(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return Uo(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Qn(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(Ft),X(sv),X(tr),X(Be),X(Do),X(lt),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $n=(()=>{let o=class o{constructor(e,t,i){this.authService=e,this.configService=t,this.loggingService=i,this.db$=new Se(null);try{this.authService.getFirebaseConfig$().subscribe(a=>{if(a){let l=this.configService.getProxyConfig(),s=a.firebaseOptions.databaseURL;l?.v1DbHost&&s&&(s=kN(s,l.v1DbHost),l?.forceLongPolling&&Hq());let d=x1(void 0,s);l?.v1DbHost&&s&&this.lockDatabaseHost(d),this.db$.next(d)}},a=>{this.loggingService.catch("Error in DatabaseService constructor: ",a)})}catch(a){this.loggingService.catch("Error in DatabaseService constructor:",a)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(e){try{let i=e?._repo?.repoInfo_;if(i){let a=i.host;Object.defineProperty(i,"host",{get:()=>a,set:()=>{},configurable:!0}),i.internalHost=a}}catch(t){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",t)}}};o.\u0275fac=function(t){return new(t||o)(X(We),X(Ft),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var OL=class{};var rl=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=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 Se(null),this.commentAnnotationById$=new Se({}),this.fieldsToRemove=[],this.additionalFields=[],this.getCommentAnnotationById=a=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",l);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]))})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",a)}}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(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:e}}),b(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],V=k(f({},e),{commentAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.commentAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.commentAnnotationById$.next(f(f({},this.commentAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return Q(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 a=t||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=f(f({},l),e.commentAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return 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 s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let a=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let l=this.commentAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.commentAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:g,event:Io.COMMENT_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:g,event:Io.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:E,commentAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:s}}),{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()):le(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",t);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",e),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.commentAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=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 Se(null),this.reactionAnnotationById$=new Se({}),this.getReactionAnnotationById=a=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",l);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",a)}}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(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:e}}),b(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],V=k(f({},e),{reactionAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.reactionAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.reactionAnnotationById$.next(f(f({},this.reactionAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return Q(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 a=t||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=f(f({},l),e);let s={reactionAnnotation:e,event:Io.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Ai(()=>i?.config?.saveConfig?.url?ji(i.config.saveConfig.url,i.config.saveConfig.headers,s,!1):i?.save?.(s)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return d&&d.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(d?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:d,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:s.event}),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let a=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=t??l?.[e]?.metadata,d=s?ti(s):void 0,g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.reactionAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:g,event:Io.REACTION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:g,event:Io.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:E,reactionAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:s}}),{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()):le(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(a){this.loggingService.catch("Error in AttachmentResolverService constructor:",a)}}getProvider(e){try{let t=e||"default";return this.providers.get(t)||void 0}catch(t){this.loggingService.catch("Error in AttachmentResolverService getProvider:",t);return}}getRetrySaveConfig(e){let t=e||"default";return this.retrySaveConfigs.get(t)||this.defaultRetryConfig}getRetryDeleteConfig(e){let t=e||"default";return this.retryDeleteConfigs.get(t)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(e,t,i,a){return Q(this,null,function*(){try{let l=new FormData;l.append("file",i);let s={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(s));let d={};t&&Object.entries(t).forEach(([b,E])=>{b.toLowerCase()!=="content-type"&&(d[b]=E)});let g=yield fetch(e,{method:"POST",headers:d,body:l});return g.ok?{data:(yield g.json())?.data??{},success:!0,statusCode:200}:(at.catch(`Error in makeAttachmentConfigBasedRequest: ${g.status} ${g.statusText}`),{data:{},success:!1,statusCode:g.status})}catch(l){return at.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let a=this.getProvider(i);if(!this.attachmentDataProviderAvailable(i))throw new Error("Attachment save data provider not available");let l=this.getRetrySaveConfig(i),s=t||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Ai(()=>Q(this,null,function*(){if(a?.config?.saveConfig?.url){let g=e.attachment,{file:u}=g,b=Dh(g,["file"]);return this.makeAttachmentConfigBasedRequest(a.config.saveConfig.url,a.config.saveConfig.headers,u,{attachment:b,event:e.eventType,metadata:e.attachment.metadata})}return a?.save?.({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",l);if(d?.statusCode!==200){this.loggingService.catch(d?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{error:d,request:e}});return}return this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:kc.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,s,d){return Q(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let g=this.getProvider(a);if(!this.attachmentDataProviderAvailable(a))throw new Error("Attachment delete data provider not available");let u=t?f({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0,b=this.getRetryDeleteConfig(a),E=i||ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Ai(()=>{if(g?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE};return ji(g.config.deleteConfig.url,g.config.deleteConfig.headers,M,!1)}return g?.delete?.({attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",b);return A?.statusCode!==200?(this.loggingService.catch(A?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{error:A,attachmentId:e,metadata:u}}),{revertOnFailure:b.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:E,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:b.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:b.revertOnFailure,isSuccess:!0})}catch(g){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",g);let u=this.getRetryDeleteConfig(a),b=i||ot(),E=t?f({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0;return this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{error:g,attachmentId:e,metadata:E}}),{revertOnFailure:u.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e,t="default"){try{if(e){this.loggingService.log(`Setting attachment data provider for scope: ${t}`);let i=e.config,a=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],l=[];if(a.forEach(({method:s,configKey:d})=>{let g=i?.[d]?.url,u=s in e&&typeof e[s]=="function";!g&&!u&&l.push(s)}),l.length>0){let s=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(s);return}else this.providers.set(t,e),e.config?.saveRetryConfig&&this.retrySaveConfigs.set(t,e.config.saveRetryConfig),e.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(t,e.config.deleteRetryConfig)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(e){try{let t=e||"default";return this.providers.has(t)}catch(t){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",t),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ol=(()=>{let o=class o{constructor(e,t,i,a){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.attachmentResolverService=a,this.resolveTimeout=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.recorderAnnotationDataProvider$=new Se(null),this.recorderAnnotationById$=new Se({}),this.additionalFields=[],this.uploadChunks=!1,this.getRecorderAnnotationById=l=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[l]:void 0}catch(s){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",s);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(l=>{l&&(l.config?.resolveTimeout&&(this.resolveTimeout=l.config.resolveTimeout),l.config?.saveRetryConfig&&(this.retrySaveConfig=l.config.saveRetryConfig),l.config?.deleteRetryConfig&&(this.retryDeleteConfig=l.config.deleteRetryConfig),l.config?.getRetryConfig&&(this.retryGetConfig=l.config.getRetryConfig),l.config?.additionalFields&&(this.additionalFields=l.config.additionalFields||[]),this.uploadChunks=l.uploadChunks??!1)})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",l)}}getProvider(){try{let e=this.recorderAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",e)}}resolveRecorderAnnotations(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:e}}),b(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],V=k(f({},e),{recorderAnnotationIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.recorderAnnotationById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.recorderAnnotationById$.next(f(f({},this.recorderAnnotationById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let i=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let a=t||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=f(f({},l),e.recorderAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(e.recorderAnnotation),eventType:e.eventType}),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let a=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let l=this.recorderAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),g=d?f({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:g}});let b=f({},l);delete b?.[e],this.recorderAnnotationById$._value=b;let E=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:g,event:Io.RECORDER_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:g,event:Io.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return E&&E.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(E?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:E,recorderAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:e.toString()}),this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:g}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||ot(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),le(void 0)}}getAnnotationById(e){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",t);return}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting recorder annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else e.storage&&this.attachmentResolverService.setAttachmentDataProvider(e.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",t)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt),X(Gs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=s,this.commentResolverService=d,this.reactionResolverService=g,this.recorderResolverService=u,this.coreActionsService=b,this.functions=E,this.documentPaths$=new Se(null),this.docContext$=new Se(null),this.documentIds$=new Se([]),this.organizationConfig$=new Se(null),this.firestorePaths$=new Se(null),this.location$=new Se(null),this.excludedLocationIds$=new Se([]),this.organizationMetadata$=new Se(null),this.documentMetadata$=new Se(null),this.locationMetadata$=new Se(null),this.customerMetadata$=new Se(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Se({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Se({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new it,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(PB(()=>Js(this.currentDebounceTime))).subscribe({next:A=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(A.documentId,A.clientOrganizationId,A.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:A=>{this.loggingService.catch("Error in setDocumentId subscription:",A),this.queueSize--}}),this.databaseService.getDb().pipe($e(A=>!!A),ut(1)).subscribe(A=>{A&&(this.db=A)}),this.configService.getApiKey$().subscribe(A=>{if(this.apiKey=A,this.apiKey){if(!this.isCustomDocId){let M=AN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>Q(this,null,function*(){if(A&&(this.analyticsService.updateDefaultProperties({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&A?.organizationId&&this.documentPaths$.value?.organizationId!==A?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(M=>({id:M.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),A?.organizationId&&A?.clientOrganizationId)){let M={organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),yield this.updateOrganizationMetadata(M)}})),this.documentPaths$.subscribe(A=>{let M={documentId:A?.documentId,clientDocumentId:A?.clientDocumentId,folderId:A?.folderId,allDocuments:A?.allDocuments,veltFolderId:A?.veltFolderId};A?.organizationId&&(M.organizationId=A.organizationId,M.clientOrganizationId=A.clientOrganizationId),this.analyticsService.updateDefaultProperties(M),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(A=>{this.analyticsService.updateDefaultProperties({clientLocation:A?.location,locationId:A?.locationId})}),this.organizationMetadata$.subscribe(A=>{this.authService.setUserOrganization(A?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe($e(A=>!!A),ut(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(A){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}},A=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(A){this.loggingService.catch("Error in DocService constructor:",A)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(e=>({id:e.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setUsersService(e){try{this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService:",t)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=AN(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=AN(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(l){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:i,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:a,payload:{documentId:e,documentMetadata:t,options:i}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:f({organizationId:t?.organizationId},i??{}),source:a})}catch(s){this.loggingService.catch("Error in DocService setDocument:",s)}})}shouldSetDocumentsAgain(e,t={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&e.length===this.pendingDocumentIds.length&&e.every(u=>this.pendingDocumentIds.includes(u.id))&&Mr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(g=>g.clientDocumentId),s=ON(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(g=>l.includes(g.id))||!Mr(s,t)||i!==a}catch(i){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",i),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let i=[];return e.forEach(a=>{let l=a.id,s=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:s,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return Q(this,arguments,function*({documents:e,options:t,source:i="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(i){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:yl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(s=>s.clientDocumentId);if(!l.includes(e.id)){let s=[...l.map(g=>({id:g})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:s,setClientDocumentMetadataMap:!0});this.documentIds$.next(d)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocContext(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let t=JSON.parse(JSON.stringify(e??null));this.docContext$.next(t)}catch(t){this.loggingService.catch("Error in setDocContext: ",t)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(xt(Jt))}getProcessedDocContext(){return Che(this.getDocContext())}filterRelevantDocuments(a){return Q(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:i=!1}){try{let l=this.authService.getUser();return!l||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,l),yield this.handlePermissionProvider(e,t,l),t=yield this.filterDocumentsByPermissions(e,t,l,i),t=t.slice(0,50)),t}catch(l){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",l),t}})}fetchDocumentsFromFolder(e,t,i){return Q(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield _l({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(s=>{t.find(d=>d.clientDocumentId===s.id)||t.push({documentId:mi(s.id),clientDocumentId:s.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,i){try{let a=[];return e.organizationId&&e.organizationId!==i.clientOrganizationId&&a.push({userId:i.userId,resource:{id:e.organizationId,type:oa.ORGANIZATION,source:ro.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}}),t&&t.forEach(l=>{a.push({userId:i.userId,resource:{id:l.clientDocumentId,type:oa.DOCUMENT,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&FN({input:e?.context}).forEach(s=>{let d=JSON.stringify(s.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:ro.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:s}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let i=e.data.filter(a=>a.type===oa.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(i??"nil"))),i?.length){let a=t.filter(s=>i.includes(s.resource.id)).map(s=>s.resource.context).filter(s=>!!s),l=_he({input:a});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(l??"nil"))),l?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(l??"nil"))),this.setDocContext(l))}}catch(i){this.loggingService.catch("Error in processAccessibleContexts:",i)}}handlePermissionProvider(e,t,i){return Q(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil")));let a=this.buildPermissionRequests(e,t,i),l=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let s=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:ro.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(s??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(s,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return Q(this,null,function*(){if(a)return t;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil"))),!(e?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(e,t,i);let s=this.currentValidationToken,d=[...t];return s&&this.validatePermissionsInBackground(e,t,i,s),d})}validateAndFilterPermissions(e,t,i){return Q(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(g=>g.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),e?.folderId&&l?.[i.userId]?.folders?.[e?.folderId]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let s=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([g,u])=>{u?.errorCode===_o.PERMISSION_DENIED&&s.add(g)}),s.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...s].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...s],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(g=>!s.has(g.clientDocumentId));return d.length===0&&t.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),d}catch(a){return this.loggingService.catch("Error in validateAndFilterPermissions:",a),t}})}validatePermissionsInBackground(e,t,i,a){let l=e?.organizationId??i?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:l,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let d=[];Object.entries(s?.[i.userId]?.documents??{}).forEach(([g,u])=>{u?.errorCode===_o.PERMISSION_DENIED&&d.push(g)}),l&&s?.[i.userId]?.organization?.[l]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&s?.[i.userId]?.folders?.[e?.folderId]?.errorCode===_o.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0),d.length>0&&(this.loggingService.catch(`User does not have access to documents: ${d.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(d,i,a))}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,i){try{if(this.currentValidationToken!==i)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:e,userId:t.userId,timestamp:new Date().getTime()});let l=this.documentIds$.value||[],s=l.filter(d=>!e.includes(d.clientDocumentId));s.length!==l.length&&(s.length>0?this.setDocuments({documents:s.map(d=>({id:d.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(Qe.ERROR,{event:K.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:e,userId:t.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(a){this.loggingService.catch("Error in handleDeniedDocumentAccess:",a)}}addUserInfoToOrganization(l){return Q(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let s=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield _l({data:f({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:s,userId:a??t?.userId??""})}catch(s){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",s)}})}setDocumentsImpl(l){return Q(this,arguments,function*({documents:e,options:t,source:i,skipPermissionValidation:a=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(e??"nil")),"options:",JSON.parse(JSON.stringify(t??"nil"))),!this.shouldSetDocumentsAgain(e,ON(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let s=ot();this.currentValidationToken=s;let d=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(d?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let g=this.authService.getUser();if(!g){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(b=>b.id),this.pendingOptions=ON(t)??{},this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let u=t?.organizationId??g?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:g}),d=yield this.filterRelevantDocuments({options:t,documentIds:d,skipPermissionValidation:a}),this.documentIds$.next(d),d?.length){let b=d[0]?.clientDocumentId;t?.rootDocumentId&&d.find(E=>E.clientDocumentId===t?.rootDocumentId)&&(b=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:b,clientOrganizationId:t?.organizationId,options:t})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(s){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENT_ID,source:i,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:i})}catch(l){this.loggingService.catch("Error in setDocumentId:",l);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:i}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let l=i?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=l;let s=Date.now(),d=s-this.lastSetDocumentIdCallTime,g=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&g>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:i??void 0});return}catch(l){this.loggingService.catch("Error in debounceSetDocuments:",l)}})}setDocumentIdImpl(e,t,i){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let l=this.currentDocumentId;if(this.apiKey){let s=`${Qn(e)}`,d=i?.folderId,g=i?.folderId?Pr(i?.folderId):void 0,u=i?.locationId,b=i?.allDocuments,E=a?.organizationId?t?It(t):a?.organizationId:void 0,A=ot(),M=Jb.SET_DOCUMENTS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let V=ot(),q=Xb.SET_DOCUMENTS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,moduleName:q,methodName:ri.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=ot(),fe=Qb.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ae,moduleName:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:V,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(ie=>ie.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:fe})]),this.currentDocumentId!==s||this.documentPaths$.value?.organizationId!==E){this.loggingService.log("setting new docid"),this.currentDocumentId=s;let ie=new hL,Ce=new OL;ie.clientDocumentId=e,Ce.clientDocumentId=e,ie.folderId=d,Ce.folderId=d,ie.locationId=u,Ce.locationId=u,ie.allDocuments=b,Ce.allDocuments=b,ie.veltFolderId=g,Ce.veltFolderId=g,ie.documentId=s,Ce.documentId=s,E&&(ie.organizationId=E,ie.clientOrganizationId=t??a?.clientOrganizationId,Ce.organizationId=E,Ce.clientOrganizationId=t??a?.clientOrganizationId);let xe=`${this.apiKey}`,ke=`apiKey/${this.apiKey}`;E&&(xe=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${ie.organizationId}`,ke=`${ke}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${ie.organizationId}`),Ce.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,Ce.document=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,ie.presence=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,ie.cursor=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,ie.comment=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,Ce.comment=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,ie.multiThread=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,Ce.multiThread=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,ie.tag=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,ie.area=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,Ce.area=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AREA}`,ie.arrow=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,ie.selection=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,ie.audioHuddle=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,ie.huddle=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,ie.recorder=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,Ce.recorder=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,ie.flock=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,ie.syncVideoPlayer=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,ie.liveState=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,ie.liveStateSingleEditorMode=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,ie.reaction=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,Ce.reaction=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,ie.crdt=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,Ce.crdt=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,ie.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,ie.views=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,Ce.notificationViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,Ce.documentViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,Ce.locationViews=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,ie.notifications=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,ie.metadata=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,ie.users=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,ie.documentIam=`${xe}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.groupContacts=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,ie.globalContacts=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,ie.logins=`${xe}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,ie.userFeedback=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,ie.userReportBugs=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,ie.userContactUs=`${xe}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,E&&(ie.organizationMetadata=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,ie.organizationIam=`${xe}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,ie.organizationGroups=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,ie.organizationNotifications=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,s&&(ie.organizationNotificationsWithDocumentId=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/`,ie.heartbeatByDocument=`${xe}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${s}/`),ie.organizationNotificationsLastNotificationTimestamp=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,ie.organizationNotificationsUsers=`${xe}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,ie.heartbeat=`${xe}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),Ce.organizationUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,Ce.users=`${ke}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,Ce.documentUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,Ce.notificationDocs=`${ke}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,Ce.notificationUsers=`${ke}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(ie),this.firestorePaths$.next(Ce),ie?.clientOrganizationId&&ie?.organizationId&&!(ie?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&ie?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:ie?.organizationId,clientOrganizationId:ie?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),l&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:s,clientDocumentId:e}}),this.analyticsService.trackEvent(K.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:s,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:yl.UNSET_DOCUMENT_ID,source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let i=JSON.parse(JSON.stringify(this.documentIds$.value??[])),a=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),l=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:i,folderId:a,context:l}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(K.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{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())}catch(i){this.loggingService.catch("Error in unsetDocumentImpl: ",i)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:yl.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",i)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,i]of this.preDocumentIdChangeFunctions)try{yield i(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig()),this.db&&e?.organizationId){let t=e?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:t,field:"metadata"}}).then(i=>{i&&!i?.errorCode&&this.organizationMetadata$.next(k(f({},this.organizationMetadata$.value),{[t]:i}))}).catch(i=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)})}}catch(t){this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)}})}fetchDocumentMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentMetadata$.value;if(e=e.filter(a=>!i?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,l=[],s={organizationId:t?.clientOrganizationId,folderId:a},d=[],g=20;for(let b=0;b<e.length;b+=g)d.push(e.slice(b,b+g));d.forEach(b=>{let E=JSON.parse(JSON.stringify(s));E.documentIds=b.map(A=>A.clientDocumentId),l.push(this.fetchDocuments(E))});let u={};l.length>0&&(yield Promise.all(l).then(b=>{b?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.setAllDocumentMetadata(f(f({},this.documentMetadata$.value),u))}).catch(b=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",b)}))}else i?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.setDocumentMetadata(a.documentId,a)}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,i=e?.folderId,a=e?.allDocuments,l=[],s={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],g=20;for(let b=0;b<t.length;b+=g)d.push(t.slice(b,b+g));d.forEach(b=>{let E=JSON.parse(JSON.stringify(s));E.documentIds=b.map(A=>A.clientDocumentId),l.push(this.fetchLocations(E))});let u=this.locationMetadata$.value??{};l.length>0&&Promise.all(l).then(b=>{b?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=k(f({},u?.[A.metadata.documentId]??{}),{[A.location.id]:A}))})}),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}).catch(b=>{this.loggingService.catch("Error in fetchLocationMetadata: ",b)})}}catch(e){this.loggingService.catch("Error in fetchLocationMetadata: ",e)}})}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Jn(t=>le(null))).subscribe(t=>{this.customerMetadata$.next(t?.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(ue(e=>e?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}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`${Qn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${It(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(i){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:yl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return Q(this,arguments,function*({locations:e,options:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:i}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.SET_LOCATIONS,source:i,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(l){this.loggingService.catch("Error in setLocations: ",l)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(i=>{if(i&&typeof i=="object"){let a=!0;i?.version&&(!i?.version?.id||!i?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${i?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(i)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(i){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:yl.SET_ROOT_LOCATION,source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(l=>l.location).filter(l=>String(l.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=k(f(f({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=f(f({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),l=[],s=[];this.location$.value?.location.id&&s.push(this.location$.value?.location.id),s=[...s,...Object.values(this.locations$.value).map(u=>u.location.id)].filter(u=>u!==void 0);let d;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(d=a.find(u=>u.id===t?.rootLocationId),!d)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(d){let u=Oi(d),b=Qn(JSON.stringify(u));u.id&&l.push({locationId:b,location:u}),this.location$.next({locationId:b,location:u})}}else{d||(d=a[0]);let u=Oi(d),b=Qn(JSON.stringify(u));u.id&&l.push({locationId:b,location:u}),this.location$.next({locationId:b,location:u})}let g=[];return a.slice(t?.appendLocation?0:1).forEach(u=>{if(u.id!==this.location$.value?.location.id){let b=f({},u),E=this.locations$.value;u?.id&&Object.keys(E).forEach(q=>{let ae=E[q];ae.location?.id===u.id&&(b=f(f({},ae.location),u),delete E?.[q])});let A=this.genarateLocationId(b),M={locationId:A,location:b};b.id&&l.push({locationId:A,location:b}),g.push(M);let V=k(f({},E),{[A]:M});this.locations$.next(V)}}),this.updateDocumentLocationMetadata(l),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:yl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(K.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),g}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.ADD_LOCATION,source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(i){this.loggingService.catch("Error in DocService addLocation:",i);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:yl.REMOVE_LOCATION,payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:yl.REMOVE_LOCATIONS,source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(i){this.loggingService.catch("Error in removeLocations: ",i)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(i=>{let a=this.genarateLocationId(i);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==i.id))),this.removeCustomLocation(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:yl.UNSET_LOCATION_IDS,source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(K.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(i=>{this.getLocation()?.location.id===i&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==i))),this.removeCustomLocationId(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(Qe.INIT_UPDATE,{event:K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:yl.REMOVE_LOCATIONS_SUCCESS,source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetLocationIds: ",i)}}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(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),le([])}}updateOrganizationMetadata(e){return Q(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,i=this.documentPaths$.value;if(this.db&&t&&i?.documentId){if(this.organizationMetadata$.value?.[t])return;let l=new kL;l.apiKey=this.configService?.getApiKey()??"",l.organizationId=t,l.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:t,documentId:i?.documentId??""}})),yield this.fetchOrganizationMetadata(e)}}catch(t){this.loggingService.catch("Error in updateOrganizationMetadata: ",t)}})}updateFolderMetadata(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let i={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield _l({methodName:"createFolder",data:{type:"createFolder",metadata:i},getSdkProxy:a,userId:this.authService.getUser()?.userId??""})}}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let i=t.map(a=>Q(this,null,function*(){let l=new pL;this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(l=f(f({},this.clientDocumentMetadataMap[a.clientDocumentId]),l)),l.apiKey=this.configService?.getApiKey()??"",l.documentId=a.documentId,l.clientDocumentId=a.clientDocumentId,l.organizationId=e.organizationId,l.clientOrganizationId=e.clientOrganizationId,l.pageInfo=to();let s=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let g=!0,u=this.documentMetadata$.value?.[a.documentId];if(s&&d){let b=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));b?.clientDocumentId&&!b?.errorCode?b?.folderId&&(b?.folderId!==s||b?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),g=!1):b?.folderId===s?(s&&(l.folderId=s),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${s??""}`),g=!1):(s&&(l.folderId=s),d&&(l.veltFolderId=d))}if(u){let b={};Object.entries(l).forEach(([E,A])=>{b[E]=A}),Mr(b,u)&&(g=!1)}g&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(i),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(a=>a.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of i){let l=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});l?.errorCode&&(l={});let s=[];for(let d of e){let g=new bL;g.locationId=d?.locationId,g.veltLocationId=$K(d?.location?.id??""),g.location=d?.location,g.pageInfo=to(),g?.pageInfo?.deviceInfo&&delete g?.pageInfo?.deviceInfo;let u=k(f({},l),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:k(f({},l[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:g})});this.commonDbService?.shouldUseFirestore()||s.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let b=this.locationMetadata$.value;if(b||(b={}),d?.location?.id){let E=b?.[a.documentId],A=E?.[d?.location?.id??""];b&&(E||(b[a.documentId]={}),A||(b[a.documentId][d?.location?.id??""]={}),b[a.documentId][d?.location?.id??""]=k(f({},A),{location:d?.location})),Object.keys(b||{}).length>0&&this.locationMetadata$.next(b)}}yield Promise.allSettled(s)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Oi(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let i=this.genarateLocationId(e),a=this.locations$.value;a[i]&&(delete a[i],this.locations$.next(f({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==e.id)))}catch(i){this.loggingService.catch("Error in DocService removeLocation:",i)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let i=this.locations$.value;Object.entries(i).forEach(([a,l])=>{l.location.id===e&&(delete i[a],this.locations$.next(f({},i)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e)))})}catch(i){this.loggingService.catch("Error in DocService removeCustomLocationId:",i)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let i=this.getLocations();Object.keys(i).forEach(a=>{let l=i[a];l.location?.id===e&&(t=l.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i=[];t.forEach(a=>{let l=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(l){let s=JSON.parse(l),d=this.genarateLocationId(s);i.push(d)}}),Object.keys(e).forEach(a=>{let l=e[a];i.includes(l.locationId)||delete e[a]}),this.locations$.next(f({},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),le({})}}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 t=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),t){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(i){let a=JSON.parse(i);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),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(i=>{if(i.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(i);a?.locationId&&(e[a.locationId]={element:i,location:a})}else if(i.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=i.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let l=this.getLocationByClientLocationId(a);l?.locationId&&(e[l.locationId]={element:i,location:l});let s={id:a},d=this.genarateLocationId(s);e[a]={element:i,location:{locationId:d,location:s}}}}}),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 t;if(t=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(i)return JSON.parse(i)}else if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let i=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(i)return{id:i}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(t){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",t),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadata:",t),null}}getAllDocumentMetadata$(e){return this.getAllDocumentMetadataMap$().pipe(ue(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),xt(Jt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ue(e=>e||{}),xt(Jt))}getAllDocumentMetadataMap(){try{return 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||{},t={},i=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(i&&a)Object.values(e).forEach(l=>{l?.documentId&&l?.veltFolderId===i&&(t[l.documentId]=l)});else{let l=this.documentIds$.value;if(l?.length)l.forEach(s=>{let d=e?.[s.documentId];d&&(t[s.documentId]=d)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(t[this.documentPaths$.value?.documentId]=s)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ue(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),xt(Jt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let i=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));i[e]=t,this.documentMetadata$.next(i)}catch(i){this.loggingService.catch("Error in DocService setDocumentMetadata:",i)}}setAllDocumentMetadata(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(e)}catch(t){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",t)}}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ue(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ue(e=>e||{}),xt(Jt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(xt(Jt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(i){this.loggingService.catch("Error in DocService getMetadataFromType:",i);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let i=this.documentPaths$.value;if(!i)return;let a=e||i.clientDocumentId,l=t||i.documentId,s=this.getDocumentMetadata(l);if(!s)return;let d=s?.folderId,g=s?.veltFolderId;return f(f({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),g?{veltFolderId:g}:{})}catch(i){this.loggingService.catch("Error in DocService getDefaultMetadata:",i);return}}getBaseMetadata(e,t){try{let i,a;t?.element?i=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(i=t.clientDocumentId),i&&(a=this.generateDocumentId(i));let l=this.getMetadataFromType(e,t),s=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||s||{};return d.sdkVersion=fa(),d}catch(i){return this.loggingService.catch("Error in DocService getBaseMetadata:",i),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(i){return this.loggingService.catch("Error in DocService getServerId:",i),null}}fetchDocuments(e){return Q(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 i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return Q(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 i=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return Q(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,documents:a,folderId:l}=e;if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let s=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],g=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=s,u.clientOrganizationId=i,u.clientDocumentId=u.documentId;let b=mi(u.documentId);u.documentId=b,u.apiKey=this.configService.getApiKey()??void 0,(l||this.documentPaths$.value?.folderId)&&(u.folderId=l||this.documentPaths$.value?.folderId,u.veltFolderId=Pr(l||this.documentPaths$.value?.folderId||""));let E=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=g?.[b];M?g[b]=f(f({},M),u):g[b]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:b,organizationId:s,field:"metadata"}});if(A?.errorCode&&(A={}),A&&A.apiKey&&A.folderId&&l&&A.folderId!=u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists with different folderId: ${A.folderId}`);continue}if(A&&A.apiKey&&!A.folderId&&u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists, move this document to folder with REST API`);continue}E(),u&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:u?.documentId??""})&&d.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{organizationId:s,documentId:b}}))}yield Promise.all(d),this.setAllDocumentMetadata(g)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return Q(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:i,locations:a,documentIds:l}=e;if((!l||l.length===0)&&(l=this.documentIds$.value.map(u=>u.clientDocumentId)??[],l.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))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 s=l.map(u=>mi(u)),d=[],g=this.locationMetadata$.value;g||(g={}),s.forEach(u=>{a.forEach(b=>{let E=this.location$.value;if(b?.id===E?.location?.id&&this.location$.next({locationId:E?.locationId,location:b}),b?.id){delete b?.metadata;let A=$K(b.id),M=g?.[u],V=M?.[b.id];g&&(M||(g[u]={}),V||(g[u][b.id]={}),g[u][b.id]=k(f({},V),{location:b})),b&&this.commonDbService&&d.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:b})),properties:{organizationId:Pa(i),documentId:u,id:A}}))}})}),yield Promise.all(d),Object.keys(g||{}).length>0&&this.locationMetadata$.next(g)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return Q(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 i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],l=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let s=Pr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}}),i&&(i=[i]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ft("metadata.veltParentFolderId","==",s)],folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}})}else i=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}});return{data:i,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(_e(e=>e?this.documentPaths$.pipe(_e(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ue(i=>i?.data?.docIamConfig??i?.data),xt((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):le(null))):le(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?zr.RESTRICTED:zr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:zr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),zr.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(i?.errorCode)return;switch(delete i.documentAccessType,i.features||(i.features={}),i.features.all||(i.features.all={}),e){case zr.PUBLIC:i.features.all.restricted=!1;break;case zr.RESTRICTED:i.features.all.restricted=!0,i.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(i)),properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(f(f({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X($n),X(Be),X(Ft),X(x),X(rl),X(Hs),X(ol),X(tr),X(Do))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var An=(()=>{let o=class o{constructor(e,t,i,a,l){this.analyticsService=e,this.authService=t,this.coreActionsService=i,this.docService=a,this.loggingService=l,this.resolveOrganizationUsers=new Se(!0),this.resolveFolderUsers=new Se(!0),this.resolveDocumentUsers=new Se(!0),this.unresolvedUsers=new Se([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Bn,this.userDataProvider$=new Se(null),this.anonymousUserDataProvider$=new Se(null),this.userIdByEmailCache={},this.userById$=new Se({}),this.userByIdCalled$=new Se({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(d){this.loggingService.catch("Error in UsersService getUserById:",d);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe($e(s=>!!s),_e(()=>this.getUnresolvedUsers$().pipe($e(s=>s.length>0),Qr(300),ut(20),_e(s=>{let d=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:d,isCollection:!0,useQuery:!0,firestoreQuery:[_r(ft("user.userId","in",s.slice(0,20)))]}}).pipe(ue(g=>g?.data),on(g=>{if(g&&typeof g=="object"){delete g.undefined,delete g.null;let u=Object.values(g??{});this.setUserByIds(u.map(E=>E.user));let b=s.filter(E=>!u.some(A=>A.user.userId===E));b.length!==s.length&&this.setUnresolvedUsers(b)}})):le([])})))).subscribe()}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in UsersService setCommonDbService:",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in UsersService setContactService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(g){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:s,moduleName:d}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let u=!1;if(i&&(u=this.isResolverForFeatureDisabled(i)),u)return{};{let b={},E=[],A={};if(e?.forEach(M=>{let V=this.getUserById(M);V?b[M]=V:this.userByIdCalled$.getValue()[M]?t&&E.push(M):(E.push(M),this.userByIdCalled$.next(k(f({},this.userByIdCalled$.getValue()),{[M]:!0})))}),E.length>0){let M=s||ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:gi.RESOLVE_USERS,source:"internal",payload:{userIds:E,organizationId:a,feature:i,forceResolve:t,skipUserCheck:l,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let V={};try{let q,ae=new Promise((fe,ie)=>{q=setTimeout(()=>{ie(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});V=yield Promise.race([this.getUsersFromDB({userIds:E,organizationId:a,skipUserCheck:l}).finally(()=>{clearTimeout(q)}),ae]),this.analyticsService.trackEvent(K.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:E}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{result:V,userIds:E,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(q){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",q,{userIds:E}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:q,userIds:E,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{E?.forEach(q=>{if(!V[q]){let ae=new Set([...this.getUnresolvedUsers(),q]);this.unresolvedUsers.next(Array.from(ae)),V[q]={userId:q,name:`User ${q}`}}})}Object.entries(V).forEach(([q,ae])=>{ae&&(b[q]=V?.[q],A[q]=V?.[q])})}return Object.keys(A).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(A)),this.userById$.next(f(f({},this.userById$.getValue()),A))),b}}catch(u){this.loggingService.catch("Error in UsersService resolveUsers:",u);let b=s||ot();return this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:u,userIds:e,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(e){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",e),[]}}setUnresolvedUsers(e){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(e)){let t=JSON.parse(JSON.stringify(e));this.unresolvedUsers.next(t)}}catch(t){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",t)}}getUsersFromDB(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let l=this.userDataProvider$.getValue();if(l){if(l.config?.getConfig?.url){if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let u={organizationId:t,userIds:e},b=yield ji(l.config.getConfig.url,l.config.getConfig.headers,u,!0);return b.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${b.statusCode}. Message: ${b.message||"Unknown error"}`),{}):b.data??{}}let g=yield l.get(e);if(g&&typeof g=="object"&&"success"in g&&"statusCode"in g&&typeof g.success=="boolean"&&typeof g.statusCode=="number"){let u=g;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return g}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let s=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(s.flat());let d={};return s.forEach(g=>{g.forEach(u=>{u?.user?.userId&&(d[u.user.userId]=u.user)})}),d}catch(l){return this.loggingService.catch("Error in UsersService getUsersFromDB:",l),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let g=0;g<e.length;g+=30)l.push(e.slice(g,g+30));let s=l.map((g,u)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",g)],skipUserCheck:i}}))||[]}catch(b){return this.loggingService.catch(`Error in batch ${u+1}:`,b),[]}}));return yield Promise.all(s)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:i}){try{if(!e?.length||!i?.length)return[];let l=[];for(let M=0;M<e.length;M+=30)l.push(e.slice(M,M+30));let s=[];for(let M=0;M<i.length;M+=30)s.push(i.slice(M,M+30));let d=[],g=0,u=(M,V)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_r(ft("userId","in",M),ft("veltResourceId","in",V))]}}))??[])||[]}catch(q){return this.loggingService.catch(`Error in batch ${g+1}:`,q),[]}});for(let M of l)for(let V of s)d.push(u(M,V)),g++;return(yield Promise.all(d)).flat().filter((M,V,q)=>V===q.findIndex(ae=>ae.userId===M.userId&&ae.resourceId===M.resourceId))}catch(l){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",l),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(xt(Jt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),le({})}}setUserByIds(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;");let t=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));e.forEach(i=>{t[i.userId]=f(f({},t?.[i.userId]??{}),i)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let t=e.config?.getConfig?.url,i="get"in e&&typeof e.get=="function";if(!t&&!i){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}setAnonymousUserDataProvider(e){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in e)||typeof e.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",t)}}resolveUserIdsByEmail(i){return Q(this,arguments,function*({emails:e,uniqueId:t}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!e?.length)return{};let a=this.anonymousUserDataProvider$.getValue();if(!a||typeof a.resolveUserIdsByEmail!="function")return{};let l=[...new Set(e.filter(ie=>!!ie))];if(l.length===0)return{};let s={},d=[];if(l.forEach(ie=>{let Ce=this.userIdByEmailCache[ie];Ce?s[ie]=Ce:d.push(ie)}),d.length===0)return s;let g=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",b=this.docService.getDocumentPaths()?.folderId||"",E={organizationId:g,documentId:u,folderId:b,emails:d},A=t||ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:g,documentId:u,folderId:b}});let M=a.config?.resolveTimeout||this.resolveTimeout,V,q=new Promise((ie,Ce)=>{V=setTimeout(()=>{Ce(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},fe=Q(this,null,function*(){try{let ie=yield Ai(()=>a.resolveUserIdsByEmail(E),"resolveUserIdsByEmail",ae);return ie?.statusCode===200&&ie?.data?ie.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${ie?.statusCode}. Message: ${ie?.message||"Unknown error"}`),{})}finally{clearTimeout(V)}});try{let ie=yield Promise.race([fe,q]);return Object.entries(ie).forEach(([Ce,xe])=>{xe&&(this.userIdByEmailCache[Ce]=xe,s[Ce]=xe,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:xe,name:Ce,email:Ce},currentUserId:this.authService.getUser()?.userId??""}).catch(ke=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",ke)}))}),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:ie,emails:d}}),s}catch(ie){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",ie),this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:ie,emails:d}}),s}}catch(a){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",a),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",e),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(tr),X(ct),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return at.error("Error in isTestingDb:",r),!1}}};var cv=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=s,this.attachmentResolverService=d,this.coreActionsService=g,this.notificationActionTypeMap={[At.NEWLY_ADDED]:Io.COMMENT_ANNOTATION_ADD,[At.ADDED]:Io.COMMENT_ADD,[At.UPDATED]:Io.COMMENT_UPDATE,[At.DELETED]:Io.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let i of e){if(i?.from?.userId&&t.add(i?.from?.userId),i?.comments)for(let a of i?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let l of a?.to)l?.userId&&t.add(l?.userId);if(a?.taggedUserContacts)for(let l of a?.taggedUserContacts)l?.userId&&t.add(l?.userId)}if(i?.assignedTo?.userId&&t.add(i?.assignedTo?.userId),i?.resolvedByUserId&&t.add(i?.resolvedByUserId),i?.subscribedUsers)for(let a of Object.values(i?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(i?.unsubscribedUsers)for(let a of Object.values(i?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let l=this.usersService.getUserById(a?.userId);if(l)return f(f({},a),l)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let l=this.usersService.getUserById(a?.contact?.userId);l&&(a.contact=l,(l?.name||l?.email)&&(a.text=`@${l?.name||l?.email}`))}return a}));let i=t?.taggedUserContacts?.filter((a,l,s)=>s.findIndex(d=>d.text===a.text)===l)||[];i.sort((a,l)=>(l.text?.length||0)-(a.text?.length||0)),i.forEach(a=>{if(a?.text){let l=new RegExp(Xc(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(Xc(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(l,a.text),t.commentHtml=t.commentHtml?.replaceAll(l,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.resolvedByUserId){let t=this.usersService.getUserById(e?.resolvedByUserId);t&&(e.resolvedByUser=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=i)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=i)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.isCommentTextAvailable=!0)}),e?.viewedBy&&delete e.viewedBy,e?.unread!==void 0&&delete e.unread,e?.resolvedByUser!==void 0&&delete e.resolvedByUser,e?.comments&&e.comments.forEach(t=>{t?.reactionAnnotations&&delete t.reactionAnnotations}),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 t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(l=>{let s=t?.comments?.[l?.commentId];if(s){l.commentHtml=s?.commentHtml,l.commentText=s?.commentText;let d=s?.attachments;i&&d&&l.attachments?.forEach(g=>{let u=g?.attachmentId;d?.[u]&&(g.name=d?.[u]?.name,g.url=d?.[u]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(l=>{t?.[l]&&(e[l]=t[l])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let i=e?.location?.id,a=e?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.location=l?.location),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",i),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let i=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",i),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new yc;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(s=>(s.isAttachmentResolverUsed=!0,delete s?.name,delete s?.url,s));a.attachments=l}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}resolveTaggedUserEmails(e){return Q(this,null,function*(){try{let t=new Set;if(e.comments?.forEach(i=>{i.taggedUserContacts?.forEach(a=>{a?.contact?.email&&!a?.userId&&t.add(a.contact.email)}),i.to?.forEach(a=>{a?.email&&!a?.userId&&t.add(a.email)})}),t.size>0){let i=ot();this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(t)}});let a=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(t),uniqueId:i});Object.keys(a).length>0&&e.comments?.forEach(l=>{l.taggedUserContacts?.forEach(s=>{if(s?.contact?.email&&!s?.userId){let d=a[s.contact.email];if(d){let g=s.text;if(g){let u=Xc(g),b=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(b,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(b,`{{${d}}}`))}s.userId=d,s.contact.userId=d,delete s.contact?.email,delete s.contact?.visibility,s.text=""}}}),l.to=l.to?.map(s=>{if(s?.email&&!s?.userId){let d=a[s.email];if(d)return delete s?.email,delete s?.visibility,k(f({},s),{userId:d})}return s})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return Q(this,arguments,function*({data:e,actionType:t,commentId:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),e=yield this.resolveTaggedUserEmails(e),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let l=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),g;t&&(g=this.notificationActionTypeMap?.[t]);let u={},b=null,E=!1;if(e&&e.annotationId){let M=e.annotationId;if(u[M]=f(f(f(f({annotationId:M,metadata:ti(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,s?.length>0&&s.forEach(q=>{e?.[q]&&(u[M][q]=e[q],delete e[q])}),d?.length)for(let q of d)e?.[q]!==void 0&&(u[M][q]=JSON.parse(JSON.stringify(e[q])));e.comments?.forEach(q=>{if(q.commentId){let ae;l&&(ae={},q.attachments?.forEach(fe=>{ae[fe.attachmentId]={attachmentId:fe.attachmentId,name:fe.name,url:fe.url}})),u[M].comments[q.commentId]=f(f(f(f(f(f({commentId:q.commentId},q?.commentHtml&&{commentHtml:q?.commentHtml}),q?.commentText&&{commentText:q?.commentText}),ae&&{attachments:ae}),q?.from&&{from:q?.from}),q?.to&&{to:q?.to}),q?.taggedUserContacts&&{taggedUserContacts:q?.taggedUserContacts})}}),E=this.isCommentsDataChanged(u[M],M);let V=new Br;Object.assign(V,e),V.comments=e.comments?.map(q=>this.stripCommentsFromAnnotationData({comment:q}))||[],b=V}let A=b?.comments?.find(M=>M.commentId===i);return A?.isDraft&&(g=b?.comments?.length&&b?.comments?.length>0?Io.COMMENT_ADD:Io.COMMENT_ANNOTATION_ADD),{strippedData:E&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:b,eventType:g}}catch(l){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",l),{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(i=>i?.userId?{userId:i.userId}:i)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(i=>i?.contact?.userId?k(f({},i),{contact:{userId:i.contact.userId}}):i));let t=e?.taggedUserContacts?.filter((i,a,l)=>l.findIndex(s=>s.text===i.text)===a)||[];t.sort((i,a)=>(a.text?.length||0)-(i.text?.length||0)),t.forEach(i=>{if(i?.text&&i?.contact?.userId){let a=new RegExp(Xc(i.text),"g");e.commentText=e.commentText?.replaceAll(a,l=>`{{${i.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,l=>`{{${i.userId}}}`)}}),t.forEach(i=>{i?.text&&i?.contact?.userId&&(i.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}getDeniedForYouUsers(t){return Q(this,arguments,function*({extraData:e}){try{let i=Object.values(e?.annotationData?.subscribedUsers||{}).map(l=>l.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&i.length){let l=e?.metadata?.clientDocumentId,s=e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?e?.annotationData?.context?.access:null,d=[];i.forEach(b=>{if(d.push({userId:b,resource:{id:l,type:oa.DOCUMENT,source:ro.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:s?{access:s}:void 0}}),s){let E=JSON.stringify(s);d.push({userId:b,resource:{id:E,type:oa.CONTEXT,source:ro.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:s}}})}});let g=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:ro.SET_NOTIFICATIONS,uniqueId:g,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:g,methodName:ro.SET_NOTIFICATIONS});u?.success&&u?.data?.length&&u.data.forEach(b=>{b.hasAccess||a.push(b.userId)})}return a}catch(i){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",i),[]}})}handleCommentEncryption(s){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let d=IN(this.authService.getFirebaseConfig()?.firebaseOptions),g=Gr(this.functions,Wr({url:En.cloudFunction?.[d]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(i){i=this.notificationService?.processNotificationData(i),i.annotationData=e;let M=i?.targetAnnotationData?.commentId;if(M){let V=e?.comments?.find(q=>q?.commentId===M);V&&(i.targetAnnotationData=V)}try{let V=yield this.stripCommentAnnotationData({data:i.annotationData,actionType:i?.actionType??At.NEWLY_ADDED});V?.originalData&&(i.annotationData=this.formatCommentData(V.originalData)),i?.targetAnnotationData&&(i.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:i.targetAnnotationData})))}catch(V){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",V)}}let u=Cp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),b=yield this.getDeniedForYouUsers({extraData:i}),E={path:t??"",data:e??{},dbId:u??"",notificationData:i||void 0,notificationURL:En.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:fa(),deniedForYouUsers:b,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield hc(E,this.authService.getUser()?.userId??"");yield g({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(We),X(Do),X(Ft),X(rl),X(Gs),X(tr))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var AL=(()=>{let o=class o{constructor(e,t,i,a,l,s){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=s}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i?.from?.userId),i?.reactions?.length)for(let a of i?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=IN(this.authService.getFirebaseConfig()?.firebaseOptions),s=Gr(this.functions,Wr({url:En.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=Cp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:fa()},b=yield hc(u,g);yield s({veltData:b})}catch(l){this.loggingService.catch("Error in handleReactionEncryption:",l)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",i),!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 t={};if(e&&e.annotationId){let i=e.annotationId;if(t[i]=f({annotationId:i,metadata:ti(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[i],i))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{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 t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(We),X(Do),X(Ft),X(Hs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _p=(()=>{let o=class o{constructor(e,t,i,a){this.authService=e,this.loggingService=t,this.usersService=i,this.recorderAnnotationsResolverService=a}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId),i?.transcription?.from?.userId&&t.add(i?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?k(f({},e.transcription),{lastUpdated:t}):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(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",i),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield hc(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}stripRecorderAnnotationData({data:e,actionType:t}){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())return{strippedData:null,originalData:e};let i=e?.annotationId;if(!i)return{strippedData:null,originalData:e};let a=this.recorderAnnotationsResolverService.getAdditionalFields(),l={annotationId:i,metadata:ti(e.metadata??{})};if(e?.from&&(l.from=JSON.parse(JSON.stringify(e.from))),e?.transcription&&(l.transcription=JSON.parse(JSON.stringify(e.transcription))),e?.attachment!==void 0&&(l.attachment=e.attachment?JSON.parse(JSON.stringify(e.attachment)):null),e?.attachments?.length&&(l.attachments=JSON.parse(JSON.stringify(e.attachments))),e?.chunkUrls&&Object.keys(e.chunkUrls).length>0&&(l.chunkUrls=JSON.parse(JSON.stringify(e.chunkUrls))),e?.recordingEditVersions){let d={};for(let[g,u]of Object.entries(e.recordingEditVersions)){let b=Number(g),E={};u?.from&&(E.from=JSON.parse(JSON.stringify(u.from))),u?.attachment!==void 0&&(E.attachment=u.attachment?JSON.parse(JSON.stringify(u.attachment)):null),u?.attachments?.length&&(E.attachments=JSON.parse(JSON.stringify(u.attachments))),u?.transcription&&(E.transcription=JSON.parse(JSON.stringify(u.transcription))),Object.keys(E).length>0&&(d[b]=E)}Object.keys(d).length>0&&(l.recordingEditVersions=d)}if(e?.isUrlAvailable!==void 0&&(l.isUrlAvailable=e.isUrlAvailable),a?.length)for(let d of a)e?.[d]!==void 0&&(l[d]=JSON.parse(JSON.stringify(e[d])));if(e?.from?.userId&&(e.from={userId:e.from.userId}),delete e.transcription,e?.attachments?.length&&(e.attachments=e.attachments.map(d=>({attachmentId:d?.attachmentId,name:d?.name,bucketPath:d?.bucketPath}))),e.attachment=null,e?.chunkUrls&&(e.chunkUrls={}),e?.recordingEditVersions)for(let[,d]of Object.entries(e.recordingEditVersions))d?.from?.userId&&(d.from={userId:d.from.userId}),d.attachment=null,d?.attachments?.length&&(d.attachments=d.attachments.map(g=>({attachmentId:g?.attachmentId,name:g?.name,bucketPath:g?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let s;return t===$l.ADDED?s=Io.RECORDER_ANNOTATION_ADD:t===$l.UPDATED?s=Io.RECORDER_ANNOTATION_UPDATE:t===$l.DELETED&&(s=Io.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:s}}catch(i){return this.loggingService.catch("Error in RecorderUtilsService stripRecorderAnnotationData:",i),{strippedData:null,originalData:e}}}mergeStrippedDataWithRecorderAnnotation(e){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e?.annotationId)return e;let t=this.recorderAnnotationsResolverService.getAnnotationById(e.annotationId);if(!t)return e;if(t.from&&(e.from=t.from),t.transcription&&(e.transcription=t.transcription),t.attachments?.length&&(e.attachments=t.attachments),t.attachment!==void 0&&(e.attachment=t.attachment),t.chunkUrls&&Object.keys(t.chunkUrls).length>0&&(e.chunkUrls=t.chunkUrls),t.recordingEditVersions&&e.recordingEditVersions)for(let[i,a]of Object.entries(t.recordingEditVersions)){let l=Number(i);e.recordingEditVersions[l]&&(a.from&&(e.recordingEditVersions[l].from=a.from),a.attachment!==void 0&&(e.recordingEditVersions[l].attachment=a.attachment),a.attachments?.length&&(e.recordingEditVersions[l].attachments=a.attachments),a.transcription&&(e.recordingEditVersions[l].transcription=a.transcription))}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeStrippedDataWithRecorderAnnotation:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(We),X(x),X(An),X(ol))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bp=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Se(null),this.activityById$=new Se({}),this.fieldsToRemove=[],this.getActivityById=a=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ActivityResolverService getActivityById:",l);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove))})}catch(a){this.loggingService.catch("Error in ActivityResolverService constructor:",a)}}getProvider(){try{let e=this.activityDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ActivityResolverService getProvider:",e);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(e){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",e)}}resolveActivities(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let ae=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:e}}),b(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=[...new Set(e.activityIds||[])],V=k(f({},e),{activityIds:M});Q(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:V}});let fe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,V,!0):E?.get?.(V)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(ie=>s?{}:(g(),ie&&ie.statusCode!==200?(this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:ie,request:V}}),this.loggingService.catch(ie?.message??"Error in ActivityResolverService resolveActivities:"),{}):ie?.data)).catch(ie=>{throw g(),ie});try{A=(yield fe)||{},this.analyticsService.trackEvent(K.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let ie={};Object.entries(A).forEach(([Ce,xe])=>{let ke=this.activityById$.value?.[Ce];ke?ke&&JSON.stringify(ke)!==JSON.stringify(xe)&&(ie[Ce]=xe):ie[Ce]=xe}),Object.keys(ie).length>0&&this.activityById$.next(f(f({},this.activityById$.getValue()),ie)),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:ie,request:V}}),u(ie)}catch(ie){let Ce=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ie,request:V}}),s||b(ie),u(A)}}else g(),u({})}catch(ae){g();let fe=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:V}}),b(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:gs.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let i=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let a=t||ot();this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=f(f({},l),e.activity);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(s?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(e.activity),event:e.event}),this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ActivityResolverService saveActivity:",i);let a=t||ot();return this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:gs.SAVE_ACTIVITY,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),le(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",e),this.fieldsToRemove}}setActivityDataProvider(e){try{if(e){this.loggingService.log("Setting activity data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.activityDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",t)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sS=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=s,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=g,this.activityResolverService=u}getActivityDisplayMessage(e){try{switch(e.featureType){case"comment":return this.getCommentDisplayMessage(e);case"recorder":return this.getRecorderDisplayMessage(e);case"reaction":return this.getReactionDisplayMessage(e);case"crdt":return this.getCrdtDisplayMessage(e);case"custom":return e.displayMessageTemplate&&e.displayMessageTemplateData?this.resolveTemplate(e.displayMessageTemplate,e.displayMessageTemplateData):"";default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",t),""}}resolveTemplate(e,t){try{return e.replace(/\{\{([\w.]+)\}\}/g,(i,a)=>{let l=a.split(".").reduce((s,d)=>{if(s!=null&&typeof s=="object")return s[d]},t);return l!=null?String(l):""})}catch(i){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",i),e}}buildActivityDataFromExtraData(e){try{let{feature:t,extraData:i}=e;if(!i?.actionType)return null;switch(t){case"comment":return this.buildCommentActivityData({commentAnnotation:i.annotationData,targetComment:i.targetAnnotationData,actionType:i.actionType,otherFields:i});case"recorder":return this.buildRecorderActivityData(i);case"reaction":return this.buildReactionActivityData(i);default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",t),null}}stripActivityPII(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e));if(delete t.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:t};t.actionUser?.userId&&(t.actionUser={userId:t.actionUser.userId}),t.changes&&this.stripUsersFromChanges(t.changes),t.displayMessageTemplateData&&this.stripUsersFromTemplateData(t.displayMessageTemplateData);let i=this.extractCommentChangesForResolver(t),a=this.extractFeatureEntityDataForResolver(t);yield this.stripFeatureSpecificPII(t);let l=this.extractActivityResolverData(t);return i&&(l?l.changes=f(f({},l.changes),i.changes):l=i),a&&(l?(a.entityData!==void 0&&(l.entityData=a.entityData),a.entityTargetData!==void 0&&(l.entityTargetData=a.entityTargetData)):l=a),l&&(t.isActivityResolverUsed=!0),{strippedActivity:t,activityResolverData:l}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",t),{strippedActivity:e}}})}mergeActivityWithUser(e){try{if(!this.usersService.userDataProviderAvailable())return e;if(e=JSON.parse(JSON.stringify(e)),e.actionUser?.userId){let t=this.usersService.getUserById(e.actionUser.userId);t&&(e.actionUser=t)}return e.changes&&this.rehydrateUsersInChanges(e.changes),e.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(e.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(e),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",t),e}}mergeActivityWithFeatureData(e){try{switch(e.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(e);case"reaction":return this.mergeActivityWithReactionData(e);case"recorder":return this.mergeActivityWithRecorderData(e);default:return e}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",t),e}}getUserIdsToResolveFromActivities(e){try{let t=new Set;for(let i of e){if(i.actionUser?.userId&&t.add(i.actionUser.userId),i.changes)for(let a of Object.values(i.changes))a&&(this.extractUserIdFromValue(a.from,t),this.extractUserIdFromValue(a.to,t));if(i.displayMessageTemplateData)for(let a of Object.values(i.displayMessageTemplateData))this.extractUserIdFromValue(a,t);this.extractFeatureSpecificUserIds(i,t)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",t),[]}}getEntityIdsToResolveFromActivities(e,t){try{let i=new Set;for(let a of e)if(!(t&&a.featureType!==t))switch(a.featureType){case"comment":case"reaction":case"recorder":a.targetEntityId&&i.add(a.targetEntityId);break}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",i),[]}}stripFeatureSpecificPII(e){return Q(this,null,function*(){try{switch(e.featureType){case"comment":yield this.stripCommentPII(e);break;case"reaction":this.stripReactionPII(e);break;case"recorder":this.stripRecorderPII(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",t)}})}extractActivityResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let t={id:e.id},i=!1;if(e.featureType==="custom"){let a=this.activityResolverService.getFieldsToRemove();for(let l of a)l in e&&e[l]!==void 0&&(t[l]=e[l],delete e[l],i=!0)}return e.metadata&&(t.metadata=ti(e.metadata)),i?t:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",t);return}}extractCommentChangesForResolver(e){try{return!this.activityResolverService.activityDataProviderAvailable()||e.featureType!=="comment"||!e.changes?.commentText?void 0:{id:e.id,changes:{commentText:e.changes.commentText},metadata:e.metadata?ti(e.metadata):void 0}}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",t);return}}extractFeatureEntityDataForResolver(e){try{if(!this.activityResolverService.activityDataProviderAvailable()||!e.entityData)return;let t=e.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),i=e.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!t&&!i)return;let a={id:e.id,metadata:e.metadata?ti(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let s=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}if(i){let s=this.reactionUtilsService.stripReactionAnnotationData(l);if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}return a.entityData?a:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",t);return}}mergeActivityWithResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return e;let t=this.activityResolverService.getActivityById(e.id);if(!t)return e;t.changes&&(e.changes||(e.changes={}),Object.assign(e.changes,t.changes)),t.entityData!==void 0&&(e.entityData=t.entityData),t.entityTargetData!==void 0&&(e.entityTargetData=t.entityTargetData),t.displayMessageTemplateData&&(e.displayMessageTemplateData||(e.displayMessageTemplateData={}),Object.assign(e.displayMessageTemplateData,t.displayMessageTemplateData));let i=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[a,l]of Object.entries(t))!i.has(a)&&l!==void 0&&(e[a]=l);return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",t),e}}rehydrateFeatureSpecificUserData(e){try{switch(e.featureType){case"comment":this.rehydrateCommentUserData(e);break;case"reaction":this.rehydrateReactionUserData(e);break;case"recorder":this.rehydrateRecorderUserData(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",t)}}getCommentDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case qr.ANNOTATION_ADD:return`${t} added a comment`;case qr.COMMENT_ADD:return`${t} replied to a comment`;case qr.COMMENT_UPDATE:return`${t} edited a comment`;case qr.COMMENT_DELETE:return`${t} deleted a comment`;case qr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case qr.STATUS_CHANGE:{let i=e.changes?.status,a=i?.from?.name,l=i?.to?.name;return a&&l?`${t} changed status from ${a} to ${l}`:`${t} changed the status`}case qr.PRIORITY_CHANGE:{let i=e.changes?.priority,a=i?.to;if(!a)return`${t} removed the priority`;let l=typeof a=="object"?a?.name:String(a),s=i?.from,d=s&&typeof s=="object"?s?.name:s?String(s):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case qr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case qr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case qr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case qr.APPROVE:return`${t} approved the comment`;case qr.ACCEPT:return`${t} accepted a suggestion`;case qr.REJECT:return`${t} rejected a suggestion`;case qr.REACTION_ADD:return`${t} reacted to a comment`;case qr.REACTION_DELETE:return`${t} removed a reaction`;case qr.SUBSCRIBE:return`${t} subscribed to the thread`;case qr.UNSUBSCRIBE:return`${t} unsubscribed from the thread`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",t),""}}getRecorderDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case XD.RECORDING_ADD:return`${t} added a recording`;case XD.RECORDING_DELETE:return`${t} deleted a recording`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",t),""}}getReactionDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case QD.REACTION_ADD:return`${t} added a reaction`;case QD.REACTION_DELETE:return`${t} removed a reaction`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",t),""}}getCrdtDisplayMessage(e){try{let t=e.actionUser?.name??"Someone",a=e.entityData?.editCount??0,l=e.targetEntityId??"unknown";return`${t} made ${a} edit${a!==1?"s":""} to editor ${l}`}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",t),""}}stripCommentPII(e){return Q(this,null,function*(){try{let t=yield this.commentUtilsService.stripCommentAnnotationData({data:e.entityData,actionType:e.eventType??At.NEWLY_ADDED});t?.originalData&&(e.entityData=this.commentUtilsService.formatCommentData(t.originalData)),e.entityTargetData&&(e.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:e.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&e.changes?.commentText&&delete e.changes.commentText}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",t)}})}rehydrateCommentUserData(e){try{e.entityData&&this.commentUtilsService.mergeCommentWithUser(e.entityData),e.entityTargetData&&(this.rehydrateUserInObject(e.entityTargetData,"from"),this.rehydrateUsersInArray(e.entityTargetData,"to"),this.rehydrateUsersInArray(e.entityTargetData,"taggedUserContacts"))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",t)}}stripReactionPII(e){try{if(!e.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(e.entityData),e.entityData=this.reactionUtilsService.formatReactionData(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",t)}}rehydrateReactionUserData(e){try{if(!e.entityData)return;this.reactionUtilsService.mergeReactionWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",t)}}stripRecorderPII(e){try{if(!e.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.recorderUtilsService.stripRecorderAnnotationData({data:e.entityData});return}let t=e.entityData;if(this.usersService.userDataProviderAvailable()){t.from&&typeof t.from=="object"&&"userId"in t.from&&(t.from={userId:t.from.userId});let i=t.transcription;i?.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",t)}}rehydrateRecorderUserData(e){try{if(!e.entityData)return;this.recorderUtilsService.mergeRecorderWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",t)}}mergeActivityWithCommentAnnotationData(e){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e.targetEntityId);if(!t)return e;let i=e.entityData?.comments;if(Array.isArray(i))for(let a of i){let l=a?.commentId;if(l==null)continue;let s=t.comments?.[String(l)];s&&(s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml))}if(e.targetSubEntityId&&e.entityTargetData){let a=t.comments?.[e.targetSubEntityId];if(a){let l=e.entityTargetData;a.commentText&&(l.commentText=a.commentText),a.commentHtml&&(l.commentHtml=a.commentHtml)}}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",t),e}}mergeActivityWithReactionData(e){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",t),e}}mergeActivityWithRecorderData(e){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",t),e}}buildCommentActivityData(e){try{let{commentAnnotation:t,targetComment:i,actionType:a,otherFields:l}=e,s=t,d=i,g=a===At.DELETED&&l?.isAnnotationDelete?qr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!g)return null;let u=s?.annotationId;if(!u)return null;let b=d?.commentId,E=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:g,targetEntityId:u,eventType:a,targetSubEntityId:b??null,changes:Object.keys(E).length>0?E:void 0,entityData:t,entityTargetData:i??void 0}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",t),null}}mapCommentStatusToActionType(e){try{switch(e){case At.NEWLY_ADDED:return qr.ANNOTATION_ADD;case At.ADDED:return qr.COMMENT_ADD;case At.UPDATED:return qr.COMMENT_UPDATE;case At.DELETED:return qr.COMMENT_DELETE;case At.STATUS_CHANGED:return qr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return qr.PRIORITY_CHANGE;case At.ASSIGNED:return qr.ASSIGN;case At.ACCESS_MODE_CHANGED:return qr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return qr.CUSTOM_LIST_CHANGE;case At.APPROVED:return qr.APPROVE;case At.ACCEPTED:return qr.ACCEPT;case At.REJECTED:return qr.REJECT;case At.REACTION_ADDED:return qr.REACTION_ADD;case At.REACTION_DELETED:return qr.REACTION_DELETE;case At.SUBSCRIBED:return qr.SUBSCRIBE;case At.UNSUBSCRIBED:return qr.UNSUBSCRIBE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",t),null}}buildRecorderActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapRecorderStatusToActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"recorder",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",t),null}}mapRecorderStatusToActionType(e){try{switch(e){case $l.ADDED:return XD.RECORDING_ADD;case $l.DELETED:return XD.RECORDING_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",t),null}}buildReactionActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapReactionActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"reaction",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",t),null}}mapReactionActionType(e){try{switch(e){case"add":return QD.REACTION_ADD;case"delete":return QD.REACTION_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",t),null}}buildCommentChanges(e,t,i){try{let a={};switch(e){case At.NEWLY_ADDED:case At.ADDED:a.commentText={from:null,to:t?.commentText??null};break;case At.UPDATED:a.commentText={from:i?.oldCommentText??null,to:t?.commentText??null};break;case At.DELETED:a.commentText={from:t?.commentText??null,to:null};break;case At.STATUS_CHANGED:a.status={from:i?.oldStatus??null,to:i?.newStatus??null};break;case At.PRIORITY_CHANGED:a.priority={from:i?.oldPriority??null,to:i?.newPriority??null};break;case At.ASSIGNED:{a.assignedTo={from:i?.oldAssignedTo??null,to:i?.newAssignedTo??null};break}case At.ACCESS_MODE_CHANGED:a.accessMode={from:i?.oldAccessMode??null,to:i?.newAccessMode??null};break;case At.CUSTOM_LIST_CHANGED:a.customList={from:i?.oldCustomList??null,to:i?.newCustomList??null};break}return a}catch(a){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",a),{}}}extractFeatureSpecificUserIds(e,t){try{switch(e.featureType){case"comment":this.extractCommentActivityUserIds(e,t);break;case"reaction":this.extractReactionActivityUserIds(e,t);break;case"recorder":this.extractRecorderActivityUserIds(e,t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",i)}}extractCommentActivityUserIds(e,t){try{if(e.entityData){let i=this.commentUtilsService.getUserIdsToResolveFromComments([e.entityData]);for(let a of i)t.add(a)}if(e.entityTargetData){let i=e.entityTargetData;if(this.extractUserIdFromValue(i.from,t),Array.isArray(i.to))for(let a of i.to)this.extractUserIdFromValue(a,t);if(Array.isArray(i.taggedUserContacts))for(let a of i.taggedUserContacts)this.extractUserIdFromValue(a,t)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",i)}}extractReactionActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.reactionUtilsService.getUserIdsToResolveFromReactions([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",i)}}extractRecorderActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.recorderUtilsService.getUserIdsToResolveFromRecorders([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",i)}}stripUsersFromChanges(e){try{for(let t of Object.keys(e)){let i=e[t];i&&(i.from=this.stripUserIfPresent(i.from),i.to=this.stripUserIfPresent(i.to))}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",t)}}stripUserIfPresent(e){try{return e&&typeof e=="object"&&"userId"in e?{userId:e.userId}:e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",t),e}}stripUsersFromTemplateData(e){try{for(let t of Object.keys(e)){let i=e[t];i&&typeof i=="object"&&"userId"in i&&(e[t]={userId:i.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",t)}}rehydrateUsersInChanges(e){try{for(let t of Object.values(e))t&&(t.from=this.rehydrateIfUser(t.from),t.to=this.rehydrateIfUser(t.to))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",t)}}rehydrateIfUser(e){try{if(e&&typeof e=="object"&&"userId"in e){let t=e.userId;return this.usersService.getUserById(t)??e}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",t),e}}rehydrateUsersInTemplateData(e){try{for(let t of Object.keys(e))e[t]=this.rehydrateIfUser(e[t])}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",t)}}rehydrateUserInObject(e,t){try{let i=e[t];if(i&&typeof i=="object"&&"userId"in i){let a=i.userId,l=this.usersService.getUserById(a);l&&(e[t]=l)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",i)}}rehydrateUsersInArray(e,t){try{let i=e[t];Array.isArray(i)&&(e[t]=i.map(a=>this.rehydrateIfUser(a)))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",i)}}extractUserIdFromValue(e,t){try{if(e&&typeof e=="object"&&"userId"in e){let i=e.userId;typeof i=="string"&&t.add(i)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",i)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An),X(cv),X(AL),X(_p),X(rl),X(Hs),X(ol),X(bp))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dv=class{constructor({apiKey:o,documentId:r,organizationId:e,folderId:t,veltFolderId:i,clientDocumentId:a,clientOrganizationId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.folderId=t,this.veltFolderId=i,this.clientDocumentId=a,this.clientOrganizationId=l,a&&(this.documentId=mi(a)),l&&(this.organizationId=Pa(l)),t&&(this.folderId=t,this.veltFolderId=Pr(t)),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=`${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.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/`,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.crdt=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,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.userConfig=`${o}/${U.FIREBASE_PARTIAL_PATH_USERS}`),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.heartbeatByDocument=`${o}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${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.heartbeat=`${o}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT 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 heartbeat(){return this.paths.heartbeat?this.paths.heartbeat:this.throwError("Heartbeat path is not available.")}get heartbeatByDocument(){return this.paths.heartbeatByDocument?this.paths.heartbeatByDocument:this.throwError("Heartbeat by document 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 PL=class{constructor({apiKey:o,documentId:r,organizationId:e,clientDocumentId:t,clientOrganizationId:i,folderId:a,veltFolderId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.veltFolderId=l,t&&(this.documentId=mi(t)),i&&(this.organizationId=Pa(i)),a&&(this.folderId=a,this.veltFolderId=Pr(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.paths.activities=`${o}/${U.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,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.users=`${o}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_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.paths.lastActivityTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${o}/${U.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),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.crdt=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,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 permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get 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.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var I_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),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(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var E_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),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(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var T_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let i of e)i?.user?.userId&&t.add(i?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let i=t;e?.user&&typeof e.user=="object"&&(i=f(f({},i),e.user)),e=k(f({},e),{user:i})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var w_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["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(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var RL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),i=ot(),a=xc.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USERS_FROM_HUDDLE_MESSAGES,moduleName:a,source:"internal",payload:{userIds:t}});let l=yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a});for(let s of e)s?.from?.userId&&l[s.from.userId]&&(s.from=l[s.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),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(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var NL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let i of e)i?.updatedBy?.userId&&t.add(i?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(e){try{let t=new Set;return e?.editor?.userId&&t.add(e?.editor?.userId),e?.requestEditorAccess?.user?.userId&&t.add(e?.requestEditorAccess?.user?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return Q(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=ot(),a=xc.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:a,source:"internal",payload:{userIds:t}}),yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a}),this.mergeSingleEditorLiveStateDataWithUser(e)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),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(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var A_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mv=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Se(null),this.notificationById$=new Se({}),this.inFlightRequests=new Map,this.getNotificationById=a=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",l);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in NotificationResolverService constructor:",a)}}getProvider(){try{let e=this.notificationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in NotificationResolverService getProvider:",e);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(e){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",e)}}resolveNotifications(a){return Q(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let l,s=!1,d=!1,g=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,b)=>{l=setTimeout(()=>{if(!d){s=!0,g();let xe=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:e}}),b(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let E=this.getProvider();if(!E)return g(),u({});let A={},M=this.notificationById$.getValue()||{},V=[...new Set(e.notificationIds||[])],q=[],ae=[],fe=[];for(let xe of V)M[xe]||(this.inFlightRequests.has(xe)?(q.push(this.inFlightRequests.get(xe)),ae.push(xe)):fe.push(xe));let ie=k(f({},e),{notificationIds:fe});Q(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),fe.length>0){let xe=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:ie}});let ke,ye=new Promise(Ne=>{ke=Ne});for(let Ne of fe)this.inFlightRequests.set(Ne,ye.then(Ue=>Ue?.[Ne]));let Oe=Ai(()=>E?.config?.getConfig?.url?ji(E.config.getConfig.url,E.config.getConfig.headers,ie,!0):E?.get?.(ie)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Ne=>s?{}:(g(),Ne&&Ne.statusCode!==200?(this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Ne,request:ie}}),this.loggingService.catch(Ne?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Ne?.data)).catch(Ne=>{throw g(),Ne});try{A=(yield Oe)||{},ke(A);for(let Ue of fe)this.inFlightRequests.delete(Ue);this.analyticsService.trackEvent(K.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:fe});let Ne={};Object.entries(A).forEach(([Ue,ze])=>{let Ge=this.notificationById$.value?.[Ue];Ge?Ge&&JSON.stringify(Ge)!==JSON.stringify(ze)&&(Ne[Ue]=ze):Ne[Ue]=ze}),Object.keys(Ne).length>0&&this.notificationById$.next(f(f({},this.notificationById$.getValue()),Ne)),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Ne,request:ie}}),u(Ne)}catch(Ne){ke({});for(let ze of fe)this.inFlightRequests.delete(ze);let Ue=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ue,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ne,request:ie}}),s||b(Ne),u(A)}}else g(),u({})}catch(xe){g();let ke=t||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ke,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:xe,request:ie}}),b(xe)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let s=t||ot();return this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let a=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let l=i||ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let s=this.notificationById$.getValue(),d=f({},s);delete d?.[e],this.notificationById$._value=d;let g={notificationId:e,organizationId:t},u=yield Ai(()=>a?.config?.deleteConfig?.url?ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,g,!1):a?.delete?.(g)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=s),this.loggingService.catch(u?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:u,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:e}),this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",a);let l=i||ot();return this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:a,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):le(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),le(void 0)}}setNotificationDataProvider(e){try{if(e){this.loggingService.log("Setting notification data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,g=l in e&&typeof e[l]=="function";!d&&!g&&a.push(l)}),a.length>0){let l=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.notificationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",t)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(x),X(lt))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var LL=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=s,this.notificationResolverService=d}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let i of e){let{notification:a}=i;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let l=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let s of l)t.add(s)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),i=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[i]?.commentText,l=t?.comments?.[i]?.commentHtml;return a&&l&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=l),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let i=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.notification.notificationSourceData.location=l?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=l?.location)),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",i),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let i=this.usersService.getUserById(t?.actionUser?.userId);i&&(t.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);i&&(t.displayHeadlineMessageTemplateData.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);i&&(t.displayHeadlineMessageTemplateData.recipientUser=i)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){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,t);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",i),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(i=>{i?.notification?.targetAnnotationId&&i?.raw?.notificationSource==="comment"&&t.push(i.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return Q(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let i="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield hc(e,i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",i),e}})}getCustomNotificationIdsToResolve(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let t=new Set,i=Array.isArray(e)?e:Object.values(e||{});for(let a of i)if(a?.raw?.notificationSource==="custom"){let l=a?.notification?.id||a?.notificationId;l&&t.add(l)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",t),[]}}mergeResolvedNotificationData(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||e?.raw?.notificationSource!=="custom")return e;let t=e?.notification?.id||e?.notificationId;if(!t)return e;let i=this.notificationResolverService.getNotificationById(t);if(!i)return e;let a=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let l of a)i[l]!==void 0&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]));return Object.keys(i).forEach(l=>{!a.includes(l)&&l!=="notificationId"&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]))}),e.notification&&(e.notification.isNotificationResolverUsed=!0),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(cv),X(_p),X(x),X(An),X(We),X(rl),X(mv))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var P_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=f(f({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var R_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let i of e)i?.user?.userId&&t.add(i.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var N_e=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i.from.userId),i?.to?.length)for(let a of i.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let i=this.usersService.getUserById(t?.userId);i&&(t=i)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),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(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var rd=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V,q,ae,fe,ie,Ce,xe,ke,ye,Oe,Ne){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=s,this.cursorUtilsService=d,this.huddleUtilsService=g,this.liveStateUtilsService=u,this.loggingService=b,this.multiThreadUtilsService=E,this.notificationUtilsService=A,this.presenceUtilsService=M,this.reactionUtilsService=V,this.recorderUtilsService=q,this.selectionUtilsService=ae,this.tagUtilsService=fe,this.usersService=ie,this.docService=Ce,this.commentAnnotationsResolverService=xe,this.reactionAnnotationsResolverService=ke,this.recorderAnnotationsResolverService=ye,this.notificationResolverService=Oe,this.activityResolverService=Ne}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",i),null}}getFirestorePath({feature:e,properties:t,documentPaths:i,apiKey:a}){try{if(!a)return;let{documentId:l,organizationId:s,folderId:d}=t;s||(s=i?.organizationId);let g=new PL({apiKey:a,documentId:l?`${l}`:"",organizationId:s?`${s}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&g?.userConfig?`${g?.userConfig}/${t?.userId}${t?.documentId?`/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return g?.permissionsUsers?`${g?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&g?.comment?`${g?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&g?.comment?`${g?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return g?.lastNotificationTimestamp?`${g?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&g?.lastNotificationTimestamp?`${g?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&g?.activities?`${g?.activities}/${t?.id}`:void 0;case"allActivities":return g?.activities?`${g?.activities}`:void 0;case"allLastActivityTimestamp":return g?.lastActivityTimestamp?`${g?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&g?.lastActivityTimestamp?`${g?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&g?.area?`${g?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&g?.area?`${g?.area}`:void 0;case"allDocuments":return g?.document?`${g?.document}`:void 0;case"allLocations":return g?.location?`${g?.location}`:void 0;case"allFolders":return g?.folder?`${g?.folder}`:void 0;case"folder":return g?.folder&&t.folderId?`${g?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&g?.documentUsers?`${g?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&g?.reaction?`${g?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&g?.document?`${g?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return g?.organization?`${g?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&g?.document?`${g?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&g?.folder?`${g?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&g?.location&&t?.id?`${g?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&g?.documentUsers?`${g?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return g?.users?`${g?.users}`:void 0;case"allFolderUsers":return g?.users?`${g?.users}`:void 0;case"allOrganizationGroups":return g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return g?.users?`${g?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&g?.notificationViews?`${g?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&g?.documentViews?`${g?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&g?.documentViews?`${g?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&g?.locationViews?`${g?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&g?.locationViews?`${g?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&g?.docNotification?`${g?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&g?.docNotification?`${g?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&g?.notificationUsers?`${g?.notificationUsers}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&g?.notificationUsers?`${g?.notificationUsers}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(l){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",l);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"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(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:i,apiKey:a,useFirestore:l}){try{if(!a)return;let{documentId:s,organizationId:d}=t;d||(d=i?.organizationId);let g=new dv({apiKey:a,documentId:s?`${s}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&g?.userConfig?`${g?.userConfig}/${t?.userId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&g?.comment?`${g?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&g?.globalContacts?`${g?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&g?.globalContacts?`${g?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&g?.groupContacts?`${g?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&g?.groupContacts?`${g?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&g?.logins?`${g?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&g?.logins?`${g?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&g?.logins?`${g?.logins}${t?.userId}`:void 0;case"customerMetadata":return g?.customerMetadata?`${g?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&g?.arrow?`${g?.arrow}`:void 0;case"arrow":return t?.documentId&&g?.arrow&&t.id?`${g?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&g?.cursor?`${g?.cursor}`:void 0;case"cursor":return t?.documentId&&g?.cursor&&t.id?`${g?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&g?.flock&&t.id?`${g?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&g?.flock&&t.id?`${g?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&g?.huddle?`${g?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&g?.huddle?`${g?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&g?.huddle?`${g?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&g?.huddle?`${g?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&g?.huddle&&t.id?`${g?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&g?.liveState?`${g?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&g?.liveState?`${g?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&g?.liveState&&t?.id?`${g?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&g?.liveStateSingleEditorMode?`${g?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&g?.liveState?`${g?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&g?.liveState?`${g?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&g?.liveState&&t?.id?`${g?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&g?.presence&&t?.userId?`${g?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&g?.presence?`${g?.presence}`:void 0;case"workspaceIam":return g?.workspaceIam?`${g?.workspaceIam}`:void 0;case"selection":return t?.documentId&&g?.selection&&t?.userId?`${g?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&g?.selection?`${g?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&g?.syncVideoPlayer?`${g?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&g?.tag?`${g?.tag}`:void 0;case"tag":return t?.documentId&&g?.tag&&t?.id?`${g?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&g?.userContactUs?`${g?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&g?.userFeedback?`${g?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&g?.userReportBugs?`${g?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&g?.comment?`${g?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&g?.crdt?`${g?.crdt}`:void 0;case"crdtData":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&g?.crdt&&t?.id&&t?.versionId?`${g?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&g?.crdt&&t?.id&&t?.messageId?`${g?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&g?.crdt&&t?.id?`${g?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&g?.documentIam?`${g?.documentIam}`:void 0;case"allDocuments":return!l&&g?.docs&&t?.documentId?`${g?.docs}/${t?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&g?.area?`${g?.area}`:void 0;case"area":return!l&&t?.id&&g?.area?`${g?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&g?.folder?`${g?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&g?.documentIam?`${g?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&g?.organizationIam?`${g?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&g?.reaction?`${g?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"organizationMetadata":return!l&&g?.organizationMetadata?`${g?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&g?.heartbeat?`${g?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return g?.heartbeat?`${g?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&g?.heartbeatByDocument?`${g?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return g?.heartbeatByDocument?`${g?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&g?.views?`${g?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&g?.views?`${g?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&g?.views?`${g?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&g?.organizationNotificationsWithDocumentId?`${g?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&g?.organizationNotificationsWithDocumentId?`${g?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&g?.organizationNotificationsUsers?`${g?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&g?.organizationNotificationsUsers?`${g?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",s);return}}resolveAnnotations(i){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=ot(),l=Jb.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:l,source:"internal",payload:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let a=ot(),l=Xb.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:l,source:"internal",payload:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let a=ot(),l=Qb.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:l,source:"internal",payload:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(b){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:s=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:g=!1,shouldRecorderResolverAwait:u=!1}){try{if(this.usersService.userDataProviderAvailable()){let E=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(E=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(E=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}case"allActivities":{t&&typeof t=="object"&&(E=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(t)?t:Object.values(t)));break}default:E=[]}if(E?.length){let A=ot(),M=xc.GET_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.FORMAT_RESPONSE,source:"internal",moduleName:M,payload:{userIds:E,feature:e,forceResolve:a}}),i?yield this.usersService.resolveUsers({userIds:E,forceResolve:a,feature:e,uniqueId:A,moduleName:M}):this.usersService.resolveUsers({userIds:E,forceResolve:a,feature:e,uniqueId:A,moduleName:M})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let E=[];switch(e){case"allDocNotifications":case"allUserNotifications":{t&&typeof t=="object"&&(E=this.notificationUtilsService.getCustomNotificationIdsToResolve(t),E=E.filter(A=>!this.notificationResolverService.getNotificationById(A)));break}default:E=[]}if(E?.length){let A=ot(),M=dQ.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:Sl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:s}}),s?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.notificationResolverService.resolveNotifications({request:{notificationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let E=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);E=[...E,...A],E=E.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);E=[...E,...A],E=E.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allActivities":{if(t&&typeof t=="object"){let A=Array.isArray(t)?t:Object.values(t),M=this.activityUtilsService.getEntityIdsToResolveFromActivities(A,"comment");E=[...E,...M],E=E.filter(V=>!this.commentAnnotationsResolverService.getCommentAnnotationById(V))}break}default:E=[]}if(E?.length){let A=ot(),M=Jb.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldCommentAnnotationsResolverAwait:l}}),l?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:E,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(e==="allActivities"&&t&&typeof t=="object"){let E=Array.isArray(t)?t:Object.values(t),A=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let M=[];for(let V of E)V?.id&&!this.activityResolverService.getActivityById(V.id)&&M.push(V.id);if(M.length){let V=ot(),q=mQ.GET_ACTIVITIES;this.coreActionsService.triggerAction(Qe.ACTIVITY_RESOLVER,{event:K.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:gs.FORMAT_RESPONSE,moduleName:q,source:"internal",payload:{activityIds:M,organizationId:A,shouldActivityResolverAwait:d}}),d?yield this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:V,moduleName:q})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(E,"reaction");if(M=M.filter(V=>!this.reactionAnnotationsResolverService.getAnnotationById(V)),M.length){let V=ot(),q=Xb.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:g}}),g?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(E,"recorder");if(M=M.filter(V=>!this.recorderAnnotationsResolverService.getAnnotationById(V)),M.length){let V=ot(),q=Qb.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:q,source:"internal",payload:{recorderAnnotationIds:M,organizationId:A,shouldRecorderResolverAwait:u}}),u?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:V,moduleName:q})}}}return t}catch(E){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",E),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(l),i),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",i),e}}mergeActivityResolverWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable())switch(t){case"allActivities":return Array.isArray(e)?e.map(i=>this.activityUtilsService.mergeActivityWithResolverData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",i),e}}mergeNotificationsWithResolvedData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(t){case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeResolvedNotificationData(l),i),{}):Array.isArray(e)?e.map(i=>this.notificationUtilsService.mergeResolvedNotificationData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",i),e}}mergeNotificationsWithResolvedData$({data:e,feature:t}){try{return this.notificationResolverService.getNotificationsById$().pipe(ue(()=>{let i=this.mergeNotificationsWithResolvedData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),le(e)}}mergeReactionAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",i),e}}mergeRecorderAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(t){case"allRecorders":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",i),e}}mergeActivitiesWithFeatureData(e){return Array.isArray(e)?e.map(t=>this.activityUtilsService.mergeActivityWithFeatureData(t)):e}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),i&&typeof i=="object"&&!Array.isArray(i))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(s,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(s,i),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.areaUtilsService.mergeAreaWithUser(l),i),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.arrowUtilsService.mergeArrowWithUser(l),i),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.cursorUtilsService.mergeCursorUserWithUser(l),i),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeCommentWithUser(l),i),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(l),i),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(i=>this.notificationUtilsService.mergeNotificationWithUser(i)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeNotificationWithUser(l),i),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.presenceUtilsService.mergePresenceUserWithUser(l),i),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeRecorderWithUser(l),i),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeReactionWithUser(l),i),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.tagUtilsService.mergeTagWithUser(l),i),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(l),i),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(l),i),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"liveStateSingleEditorMode":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.selectionUtilsService.mergeSelectionWithUser(l),i),{}):t;case"allActivities":return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithUser(i)):t;default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",i),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ue(()=>{let i=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),le(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ue(()=>{let i=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),le(e)}}mergeRecorderAnnotationsWithData$({data:e,feature:t}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ue(()=>{let i=this.mergeRecorderAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),le(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ue(()=>{let i=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof i=="object"?{data:JSON.parse(JSON.stringify(i)),operation:t?.operation??null}:{data:i,operation:t?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),le(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ue(i=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:i});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),xt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),le(e)}}handleDataStripping(l){return Q(this,arguments,function*({feature:e,data:t,actionType:i,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return yield this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:i,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);case"recorder":return this.recorderUtilsService.stripRecorderAnnotationData({data:t,actionType:i});default:return{originalData:t,strippedData:null}}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",s),{originalData:t,strippedData:null}}})}formatData({feature:e,data:t,properties:i,offset:a,isRealtimeDb:l}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let s=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return l?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,s);case"notificationViewsTimestamp":return{views:{[i.user??""]:t}};case"documentUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"documentDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"documentMetadataViews":return l?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return l?t:{metadata:t};case"locationUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"locationDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"locationViews":return l?t:{location:t};case"docNotificationViews":return l?t:{views:t.views};case"userNotificationViews":return l?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",s),t}}modifyAndSetData(l){return Q(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let s=yield this.modifyData({feature:e,data:t});i.next({data:s,operation:a})}catch(s){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",s)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:i}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(i??{}).includes(t.doc.id);if(i?.[t.doc.id]){let a=t.doc.data(),l=i?.[t.doc.id];return a?.lastUpdated===l?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(i){return Q(this,arguments,function*({feature:e,data:t}){try{return yield this.formatResponse({feature:e,data:t})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),t}})}addMetadata(e,t){try{return e&&typeof e=="object"&&!Array.isArray(e)?k(f({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",i),e}}setDataInLocal(d){return Q(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:s=null}){try{let u={comment:"allComments",reaction:"allReactions"}[e];if(!u)return null;let b=t?.metadata?.documentId,E=t?.metadata?.veltFolderId;return Object.keys(i).filter(A=>A.includes(u)&&(!b||A.includes(b)||E&&A.includes(E))).forEach(A=>{let M=i[A]?.subject?.getValue()??{};a==="DELETE"?l&&M?.data?.[l]&&(delete M?.data?.[l],i[A]?.subject&&i[A].subject.next({data:M?.data,operation:s})):i[A]?.subject?.next({data:k(f({},M?.data),{[t?.annotationId]:t}),operation:s})}),null}catch(g){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",g),null}})}handleCommentEncryption(s){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l})}catch(d){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",d),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:i})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",l),e}})}rtdbDefaultTransactionCallback(e,t){try{let i=f({},e||{});return Object.entries(t).forEach(([a,l])=>{l==null?delete i[a]:i[a]=l}),i}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",i),e}}};o.\u0275fac=function(t){return new(t||o)(X(sS),X(I_e),X(E_e),X(cv),X(T_e),X(tr),X(w_e),X(RL),X(NL),X(x),X(A_e),X(LL),X(P_e),X(AL),X(_p),X(R_e),X(N_e),X(An),X(ct),X(rl),X(Hs),X(ol),X(mv),X(bp))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var F_e=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{pn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe($e(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,s])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||En?.firebaseLogLevel||"silent";SX(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=Cp.getFirestoreProdDbName(l,a.firebaseOptions),g=this.configService.getProxyConfig();if(g?.v2DbHost){let u={host:g.v2DbHost,ssl:!0};g.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,s&&(u.localCache=rQ({tabManager:oQ()}));try{this.firestore$.next(aL(Vl(),u,d))}catch(b){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",b),this.firestore$.next(qb(d))}}else if(s)try{let u=Vl(),b=aL(u,{localCache:rQ({tabManager:oQ()})},d);this.firestore$.next(b)}catch{this.firestore$.next(qb(d))}else this.firestore$.next(qb(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||qb("DocumentIdDb");if(e){let t=ZD(e,"generateDocumentId");return Kb(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(X(Ft),X(We),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=s,this.databaseService=d,this.configService=g,this.docService=u,this.usersService=b,this.commentAnnotationsResolverService=E,this.reactionAnnotationsResolverService=A,this.recorderAnnotationsResolverService=M,this.notificationResolverService=V,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(q=>{if(q){this.db=q;let ae=Ur(q,".info/serverTimeOffset");this.offsetListener=mg(ae,fe=>{let ie=fe.val();this.offset=ie})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(q=>{q&&(this.firestore=q)}))}setActivityService(e){this.activityService=e}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return Q(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return ds(i).update(t)}return Promise.resolve()}catch(i){return this.loggingService.catch("Error in setupOnDisconnect:",i),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){pn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe($e(([t,i])=>!!t),ut(1),on(([t,i])=>{e({db:t,firestore:i})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,i,a,l,s){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>Q(this,[u],function*({db:d,firestore:g}){let b;t?.skipFirestore||(b=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let E=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!d){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let A,M;try{E&&(A=Ur(d,`${E}`))}catch{this.loggingService.catch("Error in dbRef")}try{b?.includes("/organizations")&&g&&b&&(M=Kb(g,`${b}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:b}),s&&s({firestoreAvailable:!!g})}catch(A){this.loggingService.catch(`Error in ${e} operation: `,A),l&&l(A)}}))}catch(d){this.loggingService.catch("Error in performDatabaseOperation:",d)}})}setData(d){return Q(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,g=>Q(this,null,function*(){if(g.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield zf(g.dbRef,()=>JSON.parse(JSON.stringify(u))):yield Wf(g.dbRef,JSON.parse(JSON.stringify(u)))}try{if(g.firestoreRef&&g.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:b,originalData:E,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ni.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),b&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:b,eventType:A,commentId:s?.targetAnnotationData?.commentId},V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:E,firestorePath:g.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(b,V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:E,firestorePath:g.firestorePath??""}))}else if(e==="recorder"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.SET_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:b,eventType:A},V)),E&&(M?.isSuccess||M===null)&&this.firestore&&(yield sQ(this.firestore,q=>Q(this,null,function*(){q.set(g.firestoreRef,JSON.parse(JSON.stringify(E)))})))}else yield cQ(g.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(g){this.loggingService.catch(`Error in setData for ${e}`,g)}})}updateData(d){return Q(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,g=>Q(this,null,function*(){if(g.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield zf(g.dbRef,b=>{let E;return i?.rtdbTransactionCallback?E=i.rtdbTransactionCallback(b,u):E=this.commonDbUtilsService.rtdbDefaultTransactionCallback(b,u),JSON.parse(JSON.stringify(E))}):yield b8(g.dbRef,JSON.parse(JSON.stringify(u)))}try{if(g.firestoreRef&&g.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:b,originalData:E,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ni.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),b&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:b,eventType:A,commentId:s?.targetAnnotationData?.commentId},V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:E,firestorePath:g.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:ri.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(b,V)),E&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:E,firestorePath:g.firestorePath??""}))}else if(e==="recorder"){let M=null,V=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:V,methodName:oi.UPDATE_DATA,source:"internal",payload:{strippedData:b,originalData:E}}),b&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:b,eventType:A},V)),E&&(M?.isSuccess||M===null)&&this.firestore&&(yield sQ(this.firestore,q=>Q(this,null,function*(){q.set(g.firestoreRef,JSON.parse(JSON.stringify(E)))})))}else yield cQ(g.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(g){this.loggingService.catch(`Error in updateData for ${e}`,g)}})}createActivityFromExtraData(e,t){try{if(!t?.actionType||!this.activityService)return;let i=this.activityUtilsService.buildActivityDataFromExtraData({feature:e,extraData:t});i&&this.activityService.createActivity(i)}catch(i){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",i)}}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,callback:i,errorCallback:a,extraData:l}){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:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.createActivityFromExtraData(e,l),this.performDatabaseOperation(e,t,d=>Q(this,null,function*(){d.dbRef&&(yield _8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.COMMENT_RESOLVER,{event:K.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.REACTION_RESOLVER,{event:K.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.RECORDER_RESOLVER,{event:K.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),g=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(g?.isSuccess||g===null)&&(yield cL(d.firestoreRef))}else if(e==="userNotification"){let g=null,u=ot();this.coreActionsService.triggerAction(Qe.NOTIFICATION_RESOLVER,{event:K.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:Sl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),g=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(g?.isSuccess||g===null)&&(yield cL(d.firestoreRef))}else yield cL(d.firestoreRef)}catch(g){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,g)}}),void 0,a,i)}catch(d){this.loggingService.catch(`Error in deleteData for ${e}`,d)}})}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=ot()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),ot()||"noDocumentId"}}queryData(i){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();return!e||!t?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,t):yield this.handleRtdbQuery(e,t)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,t){return Q(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let i=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=ZD(this.firestore,i);t?.useCollectionGroup&&(a=iQ(this.firestore,i));let l=t?.firestoreQuery??[],s=lQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield n_e(s).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,g),null));return d?d.data().count:0}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,d),0}else try{let d=yield o_e(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let g=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:g})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),g}}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,d),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(i){return this.loggingService.catch(`Error in Firestore query for ${e}:`,i),[]}})}handleRtdbQuery(e,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let i=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Ur(this.db,i),l=t?.rtdbQuery??[],s=Xq(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield Kq(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let g=d.val();return g?t?.skipObjectValues?g:Object.values(g??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let l=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let s=yield r_e(Kb(this.firestore,l)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=s.data();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,s),{}}}if(this.db){let l=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let s=yield Kq(Ur(this.db,l)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=s.val();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,s),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return pn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe($e(l=>!!l))]).pipe($e(([l,s])=>l?i&&!s?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),_e(([l,s])=>{try{if(i&&s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,s).subscribe(b=>{this.observablesCache[a]?.subject?.next(b)},b=>this.observablesCache[a]?.subject?.error(b));this.firestoreSubscriptions[a]=u}return new Gt(g=>{let u=this.observablesCache[a]?.subject?.subscribe(b=>g.next(b),b=>g.error(b),()=>g.complete());return this.observablesCache[a].count+=1,()=>{u?.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(l){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleRealtimeDbListener(e,t,l).subscribe(b=>{this.observablesCache[a]?.subject?.next(b)},b=>this.observablesCache[a]?.subject?.error(b));this.rtdbSubscriptions[a]=u}return new Gt(g=>{let u=this.observablesCache[a]?.subject?.subscribe(b=>g.next(b),b=>g.error(b),()=>g.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return le({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),le({})}}),Uh(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,i){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),l=`${e}-${JSON.stringify(t)}`;return a?new Gt(s=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,s,t):this.setupDocumentListener(i,a,e,s,t);return()=>{s.complete(),s.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(_e(s=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:s})),_e(s=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:s,feature:e}):le(s)),_e(s=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:s,feature:e}):le(s)),_e(s=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:s,feature:e}):le(s)),xt(Jt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),le({}))}setupCollectionListener(e,t,i,a,l){let s=`${i}-${JSON.stringify(l)}`,d=ZD(e,t);if(l?.useCollectionGroup&&(d=iQ(e,t)),l?.useQuery&&l?.firestoreQuery){let b=l?.firestoreQuery??[];d=lQ(d,...b)}let g=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),aQ(d,b=>{try{let E=JSON.parse(JSON.stringify(this.observablesCache[s]?.subject?.getValue()?.data??{})),A=null,M=!1;b?.docChanges()?.length?b.docChanges().forEach(V=>{["allComments","allReactions","allRecorders"].includes(i)&&!g&&V.type!=="removed"&&u.push(V.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:V,cache:this.observablesCache[s]?.subject?.getValue()?.data??{}})||(M=!0,Object.assign(E,this.handleCollectionChange(V,E)),V.type==="removed"&&(A||(A={type:V.type,ids:[]}),A.ids.push(V.doc.id)))}):M=!0,M&&(["allComments","allReactions","allRecorders"].includes(i)&&u?.length&&(this.commonDbUtilsService.resolveAnnotations({data:u,feature:i}),u=[]),this.commonDbUtilsService.modifyAndSetData({feature:i,data:E,subscriber:a,operation:A})),g=!1}catch(E){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,E),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(E,i,a)}},b=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,b),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(b,i,a)})}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,i,a,l){let s=Kb(e,t);return aQ(s,d=>{try{let g=d.data()||{};l?.field&&(g=g?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:g,subscriber:a,operation:null})}catch(g){this.handleListenerError(g,i,a)}},d=>this.handleListenerError(d,i,a))}handleListenerError(e,t,i){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,i){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),le({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let s=t?.rtdbQuery??[];l=Xq(l,...s)}return this.objectValFromChildEvents(l,e).pipe(Jn(s=>(this.loggingService.catch(`RTDB listener error for ${e}:`,s),le({}))),ue(s=>(s===null&&(s={}),s&&typeof s=="object"?Object.entries(s??{}).reduce((g,[u,b])=>(g[u]=this.commonDbUtilsService.addMetadata(b,t),g),{}):this.commonDbUtilsService.addMetadata(s,t))),_e(s=>this.commonDbUtilsService.modifyData({feature:e,data:s})),_e(s=>this.usersService.getUserById$().pipe(ue(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:s}),operation:null})))))}pushData(a){return Q(this,arguments,function*({feature:e,properties:t,data:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${e}`,"color: green;"),this.performDatabaseOperation(e,t,l=>Q(this,null,function*(){if(l.dbRef){let s=C8(l.dbRef);yield Wf(s,JSON.parse(JSON.stringify(l.data)))}}),i)}catch(l){this.loggingService.catch(`Error in pushData for ${e}`,l)}})}streamChildAdded({feature:e,properties:t,afterTs:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${e}`,"color: green;"),new Gt(a=>{let l=null,s=!1,d=({db:g})=>{if(!g||s||!this.authService.getUser())return;let u=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!u)return;let E=Ur(g,u),A=!1,M=ae=>{try{let fe=ae.val();if(A){if(i!=null&&fe?.timestamp!=null&&fe.timestamp<=i)return;a.next(fe)}}catch(fe){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,fe)}},V=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(fe){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,fe)}};Jq(E,M,V);let q=mg(E,()=>{A=!0},V,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),cw(E,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{s=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),le(null)}}objectValFromChildEvents(e,t){return new Gt(i=>{let a={},l=!1,s=null,d=V=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,V),i.error(V)}catch{}},g=V=>{try{if(!Mr(V,s)){let q=JSON.parse(JSON.stringify(V));s=q,i.next(q)}}catch{}},u=V=>{try{V.key&&(a[V.key]=V.val(),l&&g(f({},a)))}catch{}},b=V=>{try{V.key&&(a[V.key]=V.val(),l&&g(f({},a)))}catch{}},E=V=>{try{V.key&&(delete a[V.key],l&&g(f({},a)))}catch{}},A=V=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};s=q,i.next(q),l=!0}}catch{}};Jq(e,u,d),wve(e,b,d),Dve(e,E,d);let M=mg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),cw(e,"child_added",u),cw(e,"child_changed",b),cw(e,"child_removed",E)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(X(sS),X(We),X(rd),X(tr),X(x),X(F_e),X($n),X(Ft),X(ct),X(An),X(rl),X(Hs),X(ol),X(mv))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vv=(()=>{let o=class o{static uniquifySvgIds(e){let t=`v${++o.idCounter}`,i=/\bid="([^"]+)"/g,a=[],l;for(;(l=i.exec(e))!==null;)a.push(l[1]);let s=e;for(let d of a){let g=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;s=s.replace(new RegExp(`\\bid="${g}"`,"g"),`id="${u}"`),s=s.replace(new RegExp(`url\\(#${g}\\)`,"g"),`url(#${u})`),s=s.replace(new RegExp(`href="#${g}"`,"g"),`href="#${u}"`)}return s}constructor(e,t,i){this.domService=e,this.loggingService=t,this.sanitizer=i,this.emojis={},this.emojisSignal=Ae({}),this.rawSvgs={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let l=o.Icons[a];this.rawSvgs[a]=l,this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(l)))}),Object.keys(o.GIF_PATHS).forEach(a=>{let l=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(l))}),this.emojisSignal.set(f({},this.emojis))}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{let t=this.rawSvgs[e];return t?this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(t))):this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let i=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(i=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(i))}catch{return""}}setEmojiList(e){try{this.emojis={},this.rawSvgs={},Object.keys(e).forEach(t=>{let i=e[t];if(i.svg)this.rawSvgs[t]=i.svg,this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(i.svg)));else if(i.url){let a=`<img src="${i.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else i.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(i.emoji)))}),this.emojisSignal.set(f({},this.emojis))}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.idCounter=0,o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
223
223
  <path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
224
224
  <path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
225
225
  <path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
@@ -405,7 +405,7 @@ This typically indicates that your device does not have a healthy Internet conne
405
405
  </radialGradient>
406
406
  </defs>
407
407
  </svg>
408
- `},o.GIF_PATHS={CAT_JAM:"https://firebasestorage.googleapis.com/v0/b/snippyly-sdk-external/o/emojis%2Fcatjam.gif?alt=media&token=9868b4ec-0031-4751-bb2e-47bf0f9d9583"},o.\u0275fac=function(t){return new(t||o)(X(Be),X(x),X(Rd))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u){this.analyticsService=e,this.authService=t,this.configService=i,this.coreActionsService=a,this.databaseService=l,this.docService=s,this.loggingService=d,this.commonDbService=g,this.usersService=u,this.db=null,this.internalUserContacts$=new Se([]),this.userGlobalContact$=new Se(!1),this.userGroupContact$=new Se(null),this.users$=new Se([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new Se({}),this.userOrganizationContacts$=new Se([]),this.userFolderContacts$=new Se([]),this.userDocumentContacts$=new Se([]),this.userOrganizationGroups$=new Se([]),this.onContactSelectedSubject$=new it,this.documentAccessType=null,this.atHereEnabled$=new Se(!1),this.atHereLabel$=new Se("here"),this.atHereDescription$=new Se(null),this.contactListScopeForOrganizationUsers$=new Se([fo.ALL]),this.customUserContacts$=new Se(null),this.customUserContactsConfig$=new Se({merge:!1}),this.currentOrganizationUserIAM$=new Se(null),this.userContacts$=new Se([]),this.userSnippylyIdContacts$=new Se(null),this.usersByOrganizationId$=new Se({}),this.temporaryUserIds$=new Se([]),this.usersByOrganizationIdAndDocumentId$=new Se({}),this.usersByOrganizationIdAndFolderId$=new Se({}),this.userById$=new Se({}),this.searchUsersSubject$=new it,this.searchUsersDebounceTime=300,this.pendingSearchPromises=new Map,this.authService.setContactService(this),this.usersService.setContactService(this),this.authService.getUser$().pipe(_e(b=>this.docService.getDocumentPaths$().pipe(on(E=>{this.documentPaths=E}),ue(()=>b)))).subscribe(b=>Q(this,null,function*(){if(this.user=b,b&&this.documentPaths)if(!b?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(b),this.setLoggedInUser(b),yield this.moveGlobalContactUserFromEmailToUserIdPath(b),this.updateUserInGlobalContactsIfAvailable(b),b?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(b?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let E=this.userPermissionService?.getCurrentUserPermissions(),A=this.documentPaths.folderId,M=!0;A&&E?.[b?.userId]?.folders?.[A]?.errorCode===_o.PERMISSION_DENIED&&(M=!1),this.getOrganizationContactsFromDb$(),M&&this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()}else this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0}),b=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",b)}),this.databaseService.getDb().pipe($e(b=>!!b),ut(1)).subscribe(b=>{b&&(this.db=b)},b=>{this.loggingService.catch("Error in ContactService constructor getDb: ",b)}),this.getOrganizationGroups$().subscribe(b=>{this.authService.setOrganizationUserGroups(b)}),pn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([b,E,A])=>{E?A?.merge?this.userContacts$.next([...b||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(b||[])}),this.getUserContacts$().subscribe(b=>{try{b?.forEach(E=>{let A=E?.userSnippylyId||Qc(this.configService.getApiKey(),E.userId);A&&this.userSnippylyIdContacts$.next(k(f({},this.userSnippylyIdContacts$.value),{[A]:E}))})}catch{}})}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in ContactService setCommentService: ",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in ContactService setUserPermissionService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.temporaryUserIds$.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=[],this.currentOrganizationUserIAM$.next(null)}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(k(f({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;if(i){if(i?.contacts){let a={};Object.keys(i?.contacts??{})?.forEach(l=>{let s=i.contacts[l];if(s?.userId){let d=It(s?.userId);a[d]=s}}),i.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}getUserAccessFields(){return JSON.parse(JSON.stringify(this.userAccessFields$.value))}getUserAccessFieldsByUserId(e){return this.getUserAccessFields()?.[e]}setUserAccessFields(e){try{let t=this.getUserAccessFields();e.forEach(a=>{t[a.user.userId]=a.accessFields||[]});let i=this.authService.getUser()?.userId;if(i&&t?.[i]?.length){let a=this.userPermissionService?.getCurrentUserPermissions();a&&(a[i]||(a[i]={}),a[i].context={accessFields:t[i]},this.userPermissionService?.setCurrentUserPermissions(a))}this.userAccessFields$.next(JSON.parse(JSON.stringify(t)))}catch(t){this.loggingService.catch("Error in ContactService setUserAccessFields: ",t)}}updateUserInGlobalContactsIfAvailable(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let i=new ra;i.userId=e?.userId,i.userSnippylyId=e?.userSnippylyId,i.email=e?.email,i.name=e?.name,i.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;i&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let i,a=t?.filter(s=>s?.visibility!=="group"),l=!1;this.authService.getUserOptions()&&(l=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(i={},a?.forEach(s=>{if(s?.userId){let d=It(s?.userId);i[d]=s}}),l?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})):l&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}})}}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",i)}}migrateGroupContactsFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(i=>Q(this,null,function*(){let a=t[i];a?.email&&a?.userId&&It(a?.email)===i&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:i,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return Q(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(ut(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let i=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===zr.PUBLIC)i=!0;else if(a===zr.RESTRICTED){let l=It(this.user?.userId);if(t?.users?.[l]&&(i=!0),this.user?.email){let s=It(this.user?.email);t?.users?.[s]&&(i=!0)}}if(i){let l=new im;l.email=this.user.email,l.visibility="group",l.name=this.user.name,l.photoUrl=this.user.photoUrl,l.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[l]),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,t){try{let i=t?.filter(a=>a?.visibility==="group");i?.length&&i.forEach(a=>Q(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:It(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:It(a?.email),skipFirestore:!0}}))}}))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",i)}}removeGroupContacts(e){return Q(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(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(i=>{i?.userId?(!i?.email||!t[i.email])&&(t[i.userId]=i):i?.email&&(!i?.userId||!t[i.userId])&&(t[i.email]=i)}),e=Object.values(t??{}),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:t,documentId:i,veltFolderId:a}=e||{};return t&&i?pn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ue(([l,s,d,g,u,b,E,A])=>{let M={},V=!1;b&&!b?.merge&&(V=!0);let q=xe=>E.some(ke=>xe.includes(ke)),ae=q([fo.ALL,fo.ORGANIZATION])?Object.keys(l?.[t]||{}):[],fe=a?q([fo.ALL,fo.FOLDER])?Object.keys(s?.[t]?.[a]||{}):[]:[],ie=q([fo.ALL,fo.DOCUMENT])?Object.keys(d?.[t]?.[i]||{}):[];if([...ae,...fe||[],...ie,...A].forEach(xe=>{let ke=g?.[xe];ke&&(M[xe]=ke)}),u){let{merge:xe,options:ke}=b||{},{organizationId:ye,documentId:Oe,folderId:Ne}=ke||{},Ue=Ne?Pr(Ne):void 0;(!ye||ye===t)&&(!Oe||Oe===i)&&(!Ue||Ue===a)&&(xe||(M={}),u.forEach(ze=>{ze?.userId&&(M[ze.userId]=ze)}))}return Object.values(M??{})})):this.userContacts$.asObservable().pipe(ue(l=>l))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),le([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getUserBySnippylyId(e){return this.userSnippylyIdContacts$.value?.[e]}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe($e(e=>!!e),_e(e=>this.docService.getDocumentPaths$().pipe($e(t=>!!t),on(t=>{this.documentPaths=t}),ue(()=>e))),_e(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return le();if(!this.documentPaths)return le();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>i?.data),on(i=>{i?(this.userGlobalContacts=Object.values(i??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ue(i=>i?.data),on(i=>{i?(this.userGroupContacts=Object.values(i??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:It(e?.userId)}}).pipe(ue(i=>i?.data),on(i=>{i?this.userPersonalContacts=Object.values(i??{}):this.userPersonalContacts=[]}))),Ro(...t).pipe(zo(this.authService.getUser$().pipe($e(i=>!i))))})).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(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(xt(Jt))}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(_e(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(ue(t=>t?.data),on(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],le()):le():le())).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(_e(e=>e?.organizationId?this.userById$.pipe(ue(t=>{let i={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(i[a?.userSnippylyId]=a)}),i})):this.users$.pipe(ue(t=>{let i={};return t.forEach(a=>{i[a.userSnippylyId]=a}),i}))))}getUserByEmail$(e){return this.users$.pipe(ue(t=>t.find(i=>i.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ue(t=>t.find(i=>i.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe($e(t=>!!t),ue(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let i=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(i?.length){let a=i.map(g=>g?.userId),l=ot(),s=xc.GET_TEMPORARY_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:l,moduleName:s,methodName:gi.GET_TEMPORARY_USERS,source:"internal",payload:{userIds:a}});let d=yield this.usersService.resolveUsers({userIds:a,uniqueId:l,moduleName:s});if(d){let g={};Object.entries(d).forEach(([b,E])=>{g[b]=E}),this.userById$.next(f(f({},this.userById$.value),g));let u=new Set([...this.temporaryUserIds$.value,...Object.keys(g)]);this.temporaryUserIds$.next(Array.from(u))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}searchUsers(e){return Q(this,null,function*(){try{if(!e||typeof e!="string"||!e.trim())return[];let t=e.trim();return this.searchUsersDebounced$||(this.searchUsersDebounced$=this.searchUsersSubject$.pipe(Qr(this.searchUsersDebounceTime),xt(),_e(i=>po(this.performSearch(i)).pipe(ue(a=>({searchText:i,results:a})),Jn(a=>(this.loggingService.catch("Error in ContactService performSearch: ",a),le({searchText:i,results:[]})))))),this.searchUsersDebounced$.subscribe({next:({searchText:i,results:a})=>{Array.from(this.pendingSearchPromises.keys()).forEach(d=>{if(d!==i){let g=this.pendingSearchPromises.get(d);g&&(g.forEach(({resolve:u})=>u([])),this.pendingSearchPromises.delete(d))}});let s=this.pendingSearchPromises.get(i);s&&(s.forEach(({resolve:d})=>d(a)),this.pendingSearchPromises.delete(i))},error:i=>{this.pendingSearchPromises.forEach(a=>{a.forEach(({reject:l})=>l(i))}),this.pendingSearchPromises.clear()}})),new Promise((i,a)=>{this.pendingSearchPromises.has(t)||this.pendingSearchPromises.set(t,[]),this.pendingSearchPromises.get(t).push({resolve:i,reject:a}),this.searchUsersSubject$.next(t)})}catch(t){return this.loggingService.catch("Error in ContactService searchUsers: ",t),[]}})}performSearch(e){return Q(this,null,function*(){try{let t=this.docService.getOrganizationConfig()?.organizationId;if(!t)return[];let i=this.documentPaths?.veltFolderId,a=this.docService.getDocumentIds().map(q=>q?.documentId),l=e.toLowerCase().trim(),s=l+"\uF8FF",d=[],g=a?.filter(q=>!!q)||[],u=g.length>0,b=!!i;if(u){let q=[];for(let fe=0;fe<g.length;fe+=20)q.push(g.slice(fe,fe+20));q.forEach(fe=>{let ie=[ft("documentIds","array-contains-any",fe),ft("viewerDocumentIds","array-contains-any",fe)],Ce=[ft("organizationIds","array-contains-any",[t]),ft("viewerOrganizationIds","array-contains-any",[t]),...ie];b&&Ce.push(ft("folderIds","array-contains-any",[i]),ft("viewerFolderIds","array-contains-any",[i])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[_r(N0(...Ce),ft("user.name_lowercase",">=",l),ft("user.name_lowercase","<",s)),lv(10)]}}).catch(()=>[])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[_r(N0(...Ce),ft("user.email_lowercase",">=",l),ft("user.email_lowercase","<",s)),lv(10)]}}).catch(()=>[]))})}let E=yield Promise.all(d),A=[];E.forEach(q=>{q&&Array.isArray(q)?q.forEach(ae=>{ae&&ae.user&&ae.user.userId&&A.push(ae)}):q&&typeof q=="object"&&Object.values(q).forEach(fe=>{fe&&fe.user&&fe.user.userId&&A.push(fe)})});let M=new Map;A.forEach(q=>{let ae=q.user?.userId;ae&&!M.has(ae)&&M.set(ae,q)});let V=Array.from(M.values());return this.setResolvedUsers(V,!0),V}catch(t){return this.loggingService.catch("Error in ContactService performSearch: ",t),[]}})}setResolvedUsers(e,t=!1){try{if(e?.length){let i=[],a=[],l=[],s=this.docService.getOrganizationConfig()?.organizationId,d=this.documentPaths?.veltFolderId,g=this.docService.getDocumentIds().map(E=>E?.documentId);e.forEach(E=>{this.userById$.value[E?.user?.userId]||(s&&E?.organizationIds?.includes(s)&&!i.find(A=>A?.user?.userId===E?.user?.userId)&&i.push(E),d&&E?.folderIds?.includes(d)&&!a.find(A=>A?.user?.userId===E?.user?.userId)&&a.push(E),g?.some(A=>E?.documentIds?.includes(A))&&!l.find(A=>A?.user?.userId===E?.user?.userId)&&l.push(E))}),i?.length&&this.setUserOrganizationContacts(i,s,t),a?.length&&this.setUserFolderContacts(a,t),l?.length&&this.setUserDocumentContacts(l,t);let b=[...i,...a,...l].filter((E,A,M)=>A===M.findIndex(V=>V.user.userId===E.user.userId));b?.length&&(this.setUserAccessFields(b),this.mergeOrganizationAndDocumentContacts())}}catch(i){this.loggingService.catch("Error in ContactService setResolvedUsers: ",i)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?.organizationId?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>this.usersService.getResolveOrganizationUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],i),t?i?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i]))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]}}).pipe(ue(a=>a?.data),_e(a=>this.commentService?.getPaginatedContactList()&&!Object.values(a??{}).find(l=>l?.user?.userId===this.authService.getUser()?.userId)?po(this.commonDbService.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i])),ft("user.userId","==",this.authService.getUser()?.userId))]}})).pipe(ue(l=>{if(l&&l.length>0){let s=l[0],d=s?.user?.userId||s?.id;if(d&&a){let g=It(d);return k(f({},a),{[g]:s})}}return a})):le(a)),ue(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let l=Object.values(a??{});this.setUserAccessFields(l),this.setUserOrganizationContacts(l,i)}else this.setUserOrganizationContacts([],i)})):le():le()}),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>this.usersService.getResolveFolderUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return le();if(!this.commonDbService.shouldUseFirestore())return le();if(!this.documentPaths?.veltFolderId)return le();let a=le([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:i,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ft("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]}}).pipe(ue(l=>l?.data)),a.pipe(ue(l=>{if(l){typeof l=="object"&&(l?.undefined&&delete l.undefined,l?.null&&delete l.null);let s=Object.values(l??{});this.setUserAccessFields(s),this.setUserFolderContacts(s)}else this.setUserFolderContacts([])}))}),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?le(e).pipe(_e(t=>this.docService.getDocumentPaths$().pipe($e(i=>!!i),on(i=>{this.documentPaths=i}),ue(()=>t))),_e(t=>this.usersService.getResolveDocumentUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(_e(i=>{let a=i?.length>0?i.map(g=>g.documentId):[this.documentPaths?.documentId??""];if(a.some(g=>!g)||!this.documentPaths)return le();let l=le([]),s={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(s.documentId=a?.length?a[0]:void 0,s.organizationId=this.documentPaths?.organizationId);let d=[];for(let g=0;g<a.length;g+=U.LISTENER_BATCH_SIZE)d.push(a.slice(g,g+U.LISTENER_BATCH_SIZE));return l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:k(f({},s),{firestoreQuery:[_r(N0(ft("documentIds","array-contains-any",g),ft("viewerDocumentIds","array-contains-any",g))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]})}).pipe(la()))).pipe(ue(g=>Ra(g)?.data)),l.pipe(ue(g=>{if(g){typeof g=="object"&&(g?.undefined&&delete g.undefined,g?.null&&delete g.null);let u=Object.values(g??{});this.setUserAccessFields(u),this.setUserDocumentContacts(u)}else this.setUserDocumentContacts([])}))})):le():le())),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t,i=!0){try{let a=e.find(s=>s.user.userId===this.user?.userId);a&&this.setCurrentOrganizationUserIAM(a);let l=e.map(s=>s.user)?.filter(s=>!this.userOrganizationContacts$.value.find(d=>d.userId===s.userId));if(this.userOrganizationContacts$.next([...this.userOrganizationContacts$.value,...l]),i&&this.usersService.setUserByIds(l),t){let s={};s[t]={};let d={};e.forEach(u=>{s[t][u.user.userId]=u,d[u.user.userId]=u.user}),this.userById$.next(f(f({},this.userById$.value),d));let g=this.usersByOrganizationId$.value?.[t];g&&(s[t]=f(f({},g),s[t])),this.usersByOrganizationId$.next(k(f({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(a){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",a)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION])?this.userOrganizationContacts$.asObservable():le([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userFolderContacts$.value.find(g=>g.userId===d.userId));this.userFolderContacts$.next([...this.userFolderContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndFolderId$.value||{},l=f({},a),s={};e?.forEach(d=>{let{organizationId:g}=d?.metadata||{};g&&(l[g]||(l[g]={}),d.folderIds?.forEach(u=>{l[g][u]||(l[g][u]={}),l[g][u]=k(f({},l[g][u]),{[d.user.userId]:d}),s[d.user.userId]=d.user}))}),this.userById$.next(f(f({},this.userById$.value),s)),this.usersByOrganizationIdAndFolderId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.FOLDER])?this.userFolderContacts$.asObservable():le([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userDocumentContacts$.value.find(g=>g.userId===d.userId));this.userDocumentContacts$.next([...this.userDocumentContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndDocumentId$.value||{},l=f({},a),s={};e?.forEach(d=>{let{organizationId:g}=d?.metadata||{};g&&(l[g]||(l[g]={}),d.documentIds?.forEach(u=>{l[g][u]||(l[g][u]={}),l[g][u]=k(f({},l[g][u]),{[d.user.userId]:d}),s[d.user.userId]=d.user}))}),this.userById$.next(f(f({},this.userById$.value),s)),this.usersByOrganizationIdAndDocumentId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.userDocumentContacts$.asObservable():le([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.userDocumentContacts$.value:[]}setCurrentOrganizationUserIAM(e){try{this.currentOrganizationUserIAM$.next(JSON.parse(JSON.stringify(e)))}catch(t){this.loggingService.catch("Error in ContactService setCurrentOrganizationUserIAM: ",t)}}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable().pipe(xt(Jt))}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{this.mergeContactsDebounceTimer&&clearTimeout(this.mergeContactsDebounceTimer),this.mergeContactsDebounceTimer=setTimeout(()=>{this.executeMergeContacts()},200)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}executeMergeContacts(){try{let e=this.getContactListScopeForOrganizationUsers(),t=[];e.includes(fo.ALL)?t=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:e.includes(fo.ORGANIZATION)?t=[...this.getUserOrganizationContacts()]:e.includes(fo.FOLDER)?t=[...this.getUserFolderContacts()]:e.includes(fo.DOCUMENT)&&(t=[...this.getUserDocumentContacts()]);let i=[...new Map(t.filter(a=>a?.userId).map(a=>[a.userId,a])).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(_e(e=>e?.organizationId?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>{if(this.setUserOrganizationGroups([]),!t)return le();let i=this.docService.getOrganizationConfig()?.organizationId;return i?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:i,isCollection:!0}}).pipe(ue(a=>a?.data),ue(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):le()})):(this.setUserOrganizationGroups([]),le()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),i=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case zr.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:i,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():le([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.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:je.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.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(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.atHereEnabled$.asObservable():le(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return Q(this,null,function*(){try{this.analyticsService.trackEvent(K.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService.setUserByIds(e),this.customUserContacts$.next(e),this.customUserContactsConfig$.next(t)}catch(i){this.loggingService.catch("Error in CommentService updateContactList: ",i)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=k(f({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(_e(e=>e?pn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ue(([t,i,a,l,s])=>{let d={};d.organizationUsers=t?.map(u=>this.convertToClientUser(u)),d.folderUsers=i?.map(u=>this.convertToClientUser(u)),d.documentUsers=a?.map(u=>this.convertToClientUser(u)),d.updatedContactList=s?.map(u=>this.convertToClientUser(u));let g=[];return l?.forEach(u=>{let b=this.convertToClientUserGroup(u,d.organizationUsers||[]);b&&g.push(b)}),d.userGroups=g,d}),xt(Jt)):le(null)),Jn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),le(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),le(null)}}convertToClientUserGroup(e,t){try{let i={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(l=>{if(l?.userId){let s=It(l.userId);a[s]=l}}),Object.keys(e?.users??{}).forEach(l=>{a[l]&&i.users?.push(a[l])}),i}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",i),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(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(Ft),X(tr),X($n),X(ct),X(x),X(Tn),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ln=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.analyticsService=e,this.authService=t,this.contactService=i,this.databaseService=a,this.docService=l,this.configService=s,this.loggingService=d,this.commonDbService=g,this.documentIAM$=new Se(null),this.workspaceIAM$=new Se(null),this.roles$=new Se([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe($e(u=>!!u),ut(1)).subscribe(u=>{u&&(this.getUser(),this.getDocumentPaths())},u=>{this.loggingService.catch("Error in CommentService getDb subscription: ",u)}),this.getRole$().pipe(ut(1)).subscribe(u=>{this.authService?.getUser()&&!u&&this.analyticsService.trackEvent(K.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(u=>{u?.accessType&&this.contactService.setDocumentAccessType(u.accessType)})}catch(u){this.loggingService.catch("Error in IamService constructor: ",u)}}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($e(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($e(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 t=e||new uL;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Jn(e=>le(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(ue(e=>!!e),xt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ue(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ue(e=>e?.features),_e(e=>this.getRole$().pipe(ue(t=>(t===Lo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(_e(()=>this.documentIAM$.pipe($e(t=>!!t),_e(()=>this.workspaceIAM$.pipe(ue(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),le(!1)}}getRole$(){try{return this.authService.getUser$().pipe(_e(()=>this.configService.getSF$()),_e(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():le(null)),_e(()=>this.configService.getSF()?this.documentIAM$.pipe($e(e=>!!e),xt(Jt)):le(null)),_e(()=>this.workspaceIAM$.pipe(xt(Jt))),ue(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),le(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return Lo.ADMIN;if(!e)return this.user?.isAdmin?Lo.ADMIN:Lo.COMMENTER;let t=null,i;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?zr.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||zr.PUBLIC:null){case zr.PUBLIC:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||Lo.COMMENTER;break;case zr.RESTRICTED:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ue(e=>e===Lo.ADMIN),xt())}isUserAdmin(){try{return this.getRole()===Lo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let i;return e&&(i=this.documentIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.documentIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",i)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let i;return e&&(i=this.workspaceIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.workspaceIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",i)}}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(dn),X($n),X(ct),X(Ft),X(x),X(Tn))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var UL="public",il=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b){this.authService=e,this.docService=t,this.loggingService=i,this.commonDbService=a,this.usersService=l,this.commentUtilsService=s,this.coreActionsService=d,this.functions=g,this.configService=u,this.contactService=b,this.currentUserPermissions$=new Se(null),this.permissionsCache$=new Se(null),this.permissionProvider$=new Se(null),this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(E){this.loggingService.catch("Error in UserPermissionService constructor:",E)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,t,i,a,l,s){try{return e.find(g=>g.resourceId===i&&g.type===a&&g.organizationId===l&&g.userId===s)?(t.push({userId:s,resourceId:i,organizationId:l,type:a,hasAccess:!1}),e.filter(g=>!(g.resourceId===i&&g.type===a&&g.organizationId===l&&g.userId===s))):e}catch(d){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",d),e}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled()||t.includes(U.DEFAULT_VELT_CONTEXT))return!0;let i=this.contactService.getUserAccessFieldsByUserId(e);return i?t.every(a=>i.includes(a)):!0}catch(i){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",i),!1}}organizationDetails(e){return Q(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e}});return t&&t?.errorCode?{errorCode:_o.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:_o.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return Q(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t}});if(a&&a?.errorCode)return{errorCode:_o.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:_o.DOES_NOT_EXIST,error:!0};let l=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},l),a?.metadata??{}));let s,d=a?.metadata?.veltFolderId;if(d)try{s=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:d,organizationId:t}}))?.folderIamConfig?.accessType}catch(g){this.loggingService.catch("Error fetching folder accessType for document:",g)}return s||(s=a?.docIamConfig?.accessType),{error:!1,accessType:s}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(i){return Q(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:_o.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:_o.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:a?.folderIamConfig?.accessType}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let i=yield this.validateResources(t),[a,l]=yield this.fetchUserPermissionsFromDB(t),s=this.buildPermissionsResponse(t,i,a,l);return!e&&Object.keys(s).length>0&&this.setCurrentUserPermissions(s),s}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),i=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:i.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId,organizationId:e?.organizationId??t?.clientOrganizationId?Pa(e?.organizationId??t?.clientOrganizationId??""):void 0}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a,clientOrganizationId:l}=e,s=[],d=[];a&&(s.push(this.organizationDetails(a)),d.push({id:l??"",type:"organization"})),t.forEach(b=>{s.push(this.folderDetails({folderId:Pr(b),organizationId:a??""})),d.push({id:b,type:"folder"})}),i.forEach(b=>{s.push(this.documentDetails({documentId:mi(b),organizationId:a??""})),d.push({id:b,type:"document"})});let[g,u]=yield Promise.all([Promise.allSettled(s),this.getDefaultDocumentAccessType()]);return k(f({},this.processValidationResults(g,d)),{defaultDocumentAccessType:u})})}getDefaultDocumentAccessType(){return Q(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,t){let i=[],a=[],l,s={},d={};for(let g=0;g<e.length;g++){let u=e[g],b=t[g];if(u.status==="rejected"||u.status==="fulfilled"&&u.value.error){let A=u.status==="fulfilled"?u.value.errorCode??_o.SOMETHING_WENT_WRONG:_o.SOMETHING_WENT_WRONG,M={id:b.id,errorCode:A};switch(b.type){case"organization":if(l=M,A===_o.DOES_NOT_EXIST)throw new Error(`Organization with id '${b.id}' does not exist`);break;case"folder":i.push(M);break;case"document":a.push(M);break}}else if(u.status==="fulfilled")switch(b.type){case"folder":u.value.accessType&&(s[b.id]=u.value.accessType);break;case"document":u.value.accessType&&(d[b.id]=u.value.accessType);break}}return{failedFolderIds:i,failedDocumentIds:a,failedOrganizationId:l,folderAccessTypes:s,documentAccessTypes:d}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a}=e,l=[this.authService.getUser()?.userId??""],s=[...t.map(u=>Pr(u)),...i.map(u=>mi(u)),a??""],[d,g]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:l,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:l,organizationId:a,resourceIds:s})]);return[d.status==="fulfilled"?d.value:[],g.status==="fulfilled"?g.value:[]]})}buildPermissionsResponse(e,t,i,a){let{folderIds:l,documentIds:s,clientOrganizationId:d,organizationId:g}=e,{failedFolderIds:u,failedDocumentIds:b,failedOrganizationId:E}=t,A={};return this.processRegularUserPermissions(A,i,l,s,d??"",g??"",u,b,E,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.processTemporaryUserPermissions(A,a),this.processContextPermissions(A),A}processContextPermissions(e){try{let t=this.authService.getUser()?.userId;if(t){let i=this.contactService.getUserAccessFieldsByUserId(t);i?.length&&(e[t]||(e[t]={}),e[t].context={accessFields:i})}}catch(t){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",t);return}}processRegularUserPermissions(e,t,i,a,l,s,d,g,u,b,E,A){for(let M of t)for(let V of M)V?.user?.userId&&(e[V.user.userId]=k(f({},i.length&&{folders:this.buildFolderPermissions(i,V,d,b,A)}),{documents:this.buildDocumentPermissions(a,V,g,E,A),organization:{[l]:this.buildOrganizationPermission(s,V,u)}}))}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case _o.DOES_NOT_EXIST:return`${t} does not exist`;case _o.PERMISSION_DENIED:return`User does not have access to ${t}`;case _o.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(i){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",i),"Something went wrong"}}buildFolderPermissions(e,t,i,a,l){return e.reduce((s,d)=>{let g=i.find(u=>u.id===d);return g?s[d]=f({error:this.getErrorMessage(g.errorCode,"folder"),errorCode:g.errorCode},g.errorCode===_o.PERMISSION_DENIED&&{accessType:a[d]??l??UL}):s[d]={accessRole:t.viewerFolderIds?.includes(Pr(d))?$s.VIEWER:$s.EDITOR,accessType:a[d]??l??UL},s},{})}buildDocumentPermissions(e,t,i,a,l){return e.reduce((s,d)=>{let g=i.find(u=>u.id===d);return g?s[d]=f({error:this.getErrorMessage(g.errorCode,"document"),errorCode:g.errorCode},g.errorCode===_o.PERMISSION_DENIED&&{accessType:a[d]??l??UL}):s[d]={accessRole:t.viewerDocumentIds?.includes(mi(d))?$s.VIEWER:$s.EDITOR,accessType:a[d]??l??UL},s},{})}buildOrganizationPermission(e,t,i){return i?{error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?$s.VIEWER:$s.EDITOR}}processTemporaryUserPermissions(e,t){for(let i of t)if(i?.userId)switch(this.ensureUserPermissionStructure(e,i.userId),i.type){case"folder":this.addTemporaryFolderPermission(e,i);break;case"document":this.addTemporaryDocumentPermission(e,i);break;case"organization":this.addTemporaryOrganizationPermission(e,i);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].folders||(e[i].folders={}),e[i].folders[a]||(e[i].folders[a]={accessRole:l??$s.EDITOR,expiresAt:s})}addTemporaryDocumentPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].documents||(e[i].documents={}),e[i].documents[a]={accessRole:l??$s.EDITOR,expiresAt:s}}addTemporaryOrganizationPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].organization||(e[i].organization={}),e[i].organization[a]={accessRole:l??$s.EDITOR,expiresAt:s}}hasEditAccess({organizationId:e,folderId:t,documentId:i}){try{let a=!0,l=this.getCurrentUserPermissionsWithServerIds(),s=this.authService.getUser()?.userId??"";return l&&(e&&typeof e=="string"&&l?.[s]?.organization?.[e]&&(l?.[s]?.organization?.[e]?.accessRole===$s.VIEWER||l?.[s]?.organization?.[e]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&l?.[s]?.folders?.[t]&&(l?.[s]?.folders?.[t]?.accessRole===$s.VIEWER||l?.[s]?.folders?.[t]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1),i&&typeof i=="string"&&l?.[s]?.documents?.[i]&&(l?.[s]?.documents?.[i]?.accessRole===$s.VIEWER||l?.[s]?.documents?.[i]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(xt(Jt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),i=this.authService.getUser()?.userId??"";if(t?.[i]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[i]?.organization?.[a]){let l=Pa(a);t[i].organization&&(t[i].organization[l]=t[i].organization[a],delete t[i].organization[a])}t?.[i]?.folders&&(t[i].folders=Object.fromEntries(Object.entries(t?.[i]?.folders??{}).map(([l,s])=>[Pr(l),s]))),t?.[i]?.documents&&(t[i].documents=Object.fromEntries(Object.entries(t?.[i]?.documents??{}).map(([l,s])=>[mi(l),s])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ue(e=>this.refactorPermissionsWithServerIds(e)),xt(Jt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let t=null;e&&(t=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(t)}catch(t){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",t)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.permissionProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",t)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return Q(this,null,function*(){let e=ot();try{if(this.isRevokeAccessOnUserLogoutEnabled){let t=[],i=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(l=>{l.userId===i&&l.hasAccess&&(l.type===oa.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&t.push(k(f({},l),{hasAccess:!1})):t.push(k(f({},l),{hasAccess:!1})))}),t.length>0){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}}),this.setPermissionsCache([]),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}});let l=yield this.revokeAccess({requests:t,userId:this.authService.getUser()?.userId??""});l.success?this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!1,statusCode:500}}})}}}catch(t){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:t}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",t)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(t){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",t),""}}cancelPendingRevokes(e){try{e.forEach(t=>{let i=this.getRevokeKey({userId:t.userId,resourceId:t.resource.id,type:t.resource.type,organizationId:t.resource.organizationId});this.pendingRevokeRequests.has(i)&&this.pendingRevokeRequests.delete(i)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(t){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",t)}}flushPendingRevokes(){return Q(this,null,function*(){let e=this.pendingRevokeUniqueId,t=this.pendingRevokeUserId;try{let i=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",i.length===0)return;let a=this.getPermissionsCache()??[];i.forEach(s=>{a=a.filter(d=>!(d.resourceId===s.resourceId&&d.type===s.type&&d.organizationId===s.organizationId&&d.userId===s.userId))}),this.setPermissionsCache(a);let l=yield this.revokeAccess({requests:i,userId:t});l.success?this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:l,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:l,success:!1,statusCode:500}}})}catch(i){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",i)}})}revokeAccessOnDocumentUnset(a){return Q(this,arguments,function*({documentIds:e,folderId:t,context:i}){let l=ot();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let s=[],d=this.docService.getOrganizationConfig()?.clientOrganizationId??"",g=this.authService.getUser()?.userId??"",u=this.getPermissionsCache()??[];e.forEach(b=>{u=this.collectRevokeRequest(u,s,b.clientDocumentId,oa.DOCUMENT,d,g)}),t&&(u=this.collectRevokeRequest(u,s,t,oa.FOLDER,d,g)),d&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(u=this.collectRevokeRequest(u,s,d,oa.ORGANIZATION,d,g)),i&&this.getIsContextEnabled()&&FN({input:i}).forEach(E=>{let A=JSON.stringify(E.access);u=this.collectRevokeRequest(u,s,A,oa.CONTEXT,d,g)}),this.setPermissionsCache(u),s.length>0&&(this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:s}}),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:s}}),s.forEach(b=>{this.pendingRevokeRequests.set(this.getRevokeKey(b),b)}),this.pendingRevokeUniqueId=l,this.pendingRevokeUserId=g,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(s){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",s)}})}getAccess(i){return Q(this,arguments,function*({requests:e,userId:t}){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield _l({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(i){return Q(this,arguments,function*({requests:e,userId:t}){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield _l({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}onResourceAccessRequired(s){return Q(this,arguments,function*({requests:e,uniqueId:t,methodName:i,userId:a,fromCache:l=!0}){try{if(!e?.length)return;let d=[],g=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&l&&(e.forEach(u=>{let b=g?.find(E=>E.resourceId===u.resource.id&&E.type===u.resource.type&&E.userId===u.userId&&E.organizationId===u.resource.organizationId);b&&d.push(b)}),d.length>0&&(e=e.filter(u=>!d.find(b=>b.resourceId===u.resource.id&&b.type===u.resource.type&&b.userId===u.userId&&b.organizationId===u.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{requests:e,fromCache:l}});let u=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{result:u}}),u?.success&&u?.data?.length&&(this.setPermissionsCache([...g,...u.data]),u.data=[...d,...u.data]),u}else if(d.length>0)return this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{results:{data:d,success:!0,statusCode:200}}}),{data:d,success:!0,statusCode:200};return}catch(d){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",d),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{error:d,requests:e,fromCache:l}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let t=new Map;e.forEach(a=>{let l=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(l,a)});let i=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(i)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",t)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(We),X(ct),X(x),X(Tn),X(An),X(cv),X(tr),X(Do),X(Ft),X(dn))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hi=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.databaseService=l,this.commonDbService=s,this.docService=d,this.domService=g,this.emojiService=u,this.iamService=b,this.loggingService=E,this.userPermissionService=A,this.documentPaths=null,this.reactionAnnotationById$=new Se({}),this.customReactions$=new Se({}),this.commentService=null,this.darkMode$=new Se(null),this.loggingService.log("%c[WB] Creating CLASS: ReactionService","color: blue;"),this.analyticsService.setReactionService(this),this.authService.setReactionService(this),this.databaseService.getDb().pipe($e(M=>!!M),ut(1)).subscribe(M=>{M&&this.getAllReactionAnnotations(void 0,void 0,!0).subscribe()},M=>{this.loggingService.catch("Error in ReactionService getDb subscription: ",M)})}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in ReactionService setCommentService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ReactionService","color: green;");try{this.reactionAnnotationById$.next({}),this.customReactions$.next({}),this.documentPaths=null}catch(e){this.loggingService.catch("Error in ReactionService clearCache: ",e)}}getAllReactionAnnotations(e,t,i,a,l){this.loggingService.log("%c[WB] Calling FUNCTION: getAllReactionAnnotations","color: green;");let s,d;try{if(e&&(d=`${Qn(e)}`),t&&typeof t=="object"){let g=Oi(t);s=Qn(JSON.stringify(g))}}catch(g){this.loggingService.catch("Error in ReactionService getAllReactionAnnotations: ",g)}return fr(this.afAuth).pipe($e(g=>!!g),_e(g=>this.isFeatureAllowed({firebaseUser:g,annotations:[],filteredAnnotations:[]})),_e(g=>g.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(u=>(g.featureAllowed=u,g))):le(g)),_e(g=>g.featureAllowed?le(g).pipe(_e(u=>this.docService.getDocumentPaths$().pipe(ue(b=>(this.documentPaths=b,u.documentPaths=b,u)))),_e(u=>d?this.getDataFromDocumentIds([d]).pipe(ue(b=>(u.annotations=b||[],f({},u)))):this.docService.getDocumentIds$().pipe(_e(b=>{let E=b?.length>0?b.map(A=>A.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(E).pipe(ue(A=>(u.annotations=A||[],f({},u))))}))),_e(u=>this.docService.getLocation$().pipe(ue(b=>(u.location=b,u)))),_e(u=>this.docService.getLocations$().pipe(ue(b=>(u.customLocations=b,u)))),ue(u=>{if(u.filteredAnnotations=[],d&&!s)return u.filteredAnnotations=u.annotations?.slice(),u;{let b=[];return s?b.push(s):(b.push(u?.location?.locationId),b.push(...Object.values(u?.customLocations||[]).map(E=>E.locationId))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,b),u}}),_e(u=>i?le(u):u?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>u)):le(u)),_e(u=>i?le(u):le(u)),ue(u=>u),_e(u=>u?.filteredAnnotations?le(u?.filteredAnnotations||[]):le([]))):le([])),xt(Jt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.REACTION)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Reaction feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))),xt((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return le([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=le([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=t?.length?t[0]:void 0,s.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[U.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],g=[];for(let u=0;u<(d?.length??0);u+=U.LISTENER_CONTEXT_BATCH_SIZE)g.push(d?.slice(u,u+U.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=pn(g.map(u=>this.commonDbService.dbListener({feature:"allReactions",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Ra(u)))}else{let d=[];for(let g=0;g<(t?.length??0);g+=U.LISTENER_BATCH_SIZE)d.push(t?.slice(g,g+U.LISTENER_BATCH_SIZE)??[]);l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allReactions",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",g),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(g=>Ra(g)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:g})=>{let u=[];return d&&(u=Object.values(d??{}).filter(b=>typeof b=="object")),u?.forEach(b=>{this.sanitizeReactionAnnotation(b)}),{data:u,operation:g}}),ue(({data:d,operation:g})=>{if(!t)return{data:d,documentMap:{},operation:g};let u=d.reduce((b,E)=>{let A=E.metadata?.documentId;return A&&(b[A]||(b[A]=[]),b[A].push(E)),b},{});return{data:d,documentMap:u,operation:g}}),ue(({data:d,documentMap:g,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let b=this.reactionAnnotationById$.value;u?.ids?.forEach(E=>{delete b?.[E]}),this.reactionAnnotationById$.next(b)}}else Object.entries(g??{}).forEach(([b,E])=>{this.setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:b,annotations:E})});return d}),Jn(d=>(this.loggingService.catch("Error in ReactionService getDataFromDocumentId: ",d),le([]))))}else return le([])}setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let s=f(f({},this.reactionAnnotationById$.value),l);this.reactionAnnotationById$.next(s)}}catch(l){this.loggingService.catch("Error in ReactionService setReactionAnnotationsByOrganizationIdAndDocumentId:",l)}}getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.reactionAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getLocations$(){return this.docService.getLocation$().pipe(_e(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ReactionService filterAnnotationsByLocations:",i),[]}}getAnnotationById(e,t){try{let i=this.reactionAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in ReactionService getAnnotationById: ",i);return}}getBaseMetadataFromReactionAnnotationId(e){try{let t=this.reactionAnnotationById$.value?.[e];return t?t.metadata:void 0}catch(t){this.loggingService.catch("Error in ReactionService getBaseMetadataFromReactionAnnotationId: ",t);return}}getReactionAnnotationByAnnotationId(e,t){try{return this.reactionAnnotationById$.pipe(ue(()=>this.getAnnotationById(e,t)),_e(i=>i?le(i):le(i)))}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationByAnnotationId: ",i),le(void 0)}}getReactionAnnotationsBySectionId(e){try{return this.reactionAnnotationById$.pipe(_e(t=>this.docService.getDocumentPaths$().pipe(ue(i=>({documentPaths:i,sectionId:e,reactionAnnotationsMap:t})))),_e(t=>{let i=tl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(s=>{let g=Object.values(s||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return k(f({},t),{additionalLocation:g,locationOnElement:!!a})}))}}return le(k(f({},t),{additionalLocation:null,element:i}))}),_e(t=>t?.locationOnElement?le(t):this.docService.getLocation$().pipe(ue(i=>k(f({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:s})=>{let d=null,g=this.docService.getAdditionalDocumentIdFromElement(s),u=g?this.docService.generateDocumentId(g):t?.documentId,b=t?.organizationId;if(u){let E=this.getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:b,documentId:u});if(E){d=[];for(let A of E)A?.targetElementId===e&&(l?a&&s0({location:a?.location,locationId:a?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):i?s0({location:i?.location,locationId:i?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):A?.locationId||d.push(A))}}return d}))}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsBySectionId: ",t),le(null)}}addOrUpdateReaction(e,t,i,a,l,s,d,g){return Q(this,null,function*(){try{let u=t?.map(b=>this.getAnnotationById(b)).find(b=>b?.icon===e);if(u){if(!d||d==="delete")return yield this.updateUserInReaction(u)}else if(!d||d==="add")return yield this.addReaction(void 0,e,i,a,l,s,g)}catch(u){this.loggingService.catch("Error in ReactionService addOrUpdateReaction: ",u)}})}addReaction(e,t,i,a,l,s,d){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{let g=this.authService.getUser();if(g)if(g.isReadOnly||g.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add reactions.");else{let u=new dL;if(u.from=g,u.lastUpdated=this.timestamp,u.reactions=[],u.reactions.push({from:g,lastUpdated:this.timestamp}),a&&(u.targetElementId=a),l){u.commentAnnotationId=l;let b=this.commentService?.getAnnotationById(l);if(b?.context?.access&&b?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:g.userId,accessFields:b.context.accessFields})){this.loggingService.catch("User does not have context access to add reaction annotation.",void 0,void 0,!0);return}u.context={access:b.context.access,accessFields:b.context.accessFields}}}if(this.setLocationToReactionAnnotation(u),u.pageInfo=to(),u.pageInfo&&(u.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),t)if(u.icon=t,s)u.iconUrl=s?.url,u.iconEmoji=s?.emoji;else{let b=this.customReactions$.value;if(b){let E=b[t];E?.url&&(u.iconUrl=E?.url),E?.emoji&&(u.iconEmoji=E?.emoji)}}return i&&(u.location={},u.location=f({},i),u.locationId=this.docService.genarateLocationId(u.location)),yield this.saveReactionToDb(u)}}catch(g){this.loggingService.catch("Error in ReactionService addReaction: ",g)}})}setLocationToReactionAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?.xpath?i=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId&&(i=tl(e.targetElementId,["id","data-id"]));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in ReactionService setLocationToReactionAnnotation:",t)}}getElementForReactionAnnotation(e){try{let t;return e.targetElementId&&(t=tl(e.targetElementId,["id","data-id"])),t}catch(t){return this.loggingService.catch("Error in ReactionService getElementForReactionAnnotation: ",t),null}}saveReactionToDb(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: saveReactionToDb","color: green;");try{if(this.authService.getUser()){let t=yield this.docService.getDocumentPaths$().pipe($e(a=>!!a),ut(1)).toPromise();if(!t)throw new Error("Document paths not found.");if(this.documentPaths=t,this.loggingService.log(this.documentPaths),!(yield this.databaseService.getDb().pipe($e(a=>!!a),ut(1)).toPromise()))throw new Error("Database not found.");if(this.documentPaths?.reaction){if(e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo,!e?.metadata?.documentId){e?.metadata||(e.metadata={});let g=this.getElementForReactionAnnotation(e),u=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId,element:g});e.metadata=f(f({},e?.metadata),u)}let a=JSON.parse(JSON.stringify(e));a.position=null;let{documentId:l,organizationId:s}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(e),d=e.commentAnnotationId?void 0:{annotationData:a,actionType:"add",notificationSource:"reaction"};return yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:a,extraData:d}),a}else return}}catch(t){this.loggingService.catch("Error in ReactionService saveReactionToDb: ",t)}})}getDocumentIdAndOrganizationIdFromReactionAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in ReactionService getDocumentIdAndOrganizationIdFromReactionAnnotation: ",t),{}}}updateUserInReaction(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(t)return e?.reactions||(e.reactions=[]),e?.reactions?.find(a=>a?.from?.userId===t?.userId)?e.reactions=e?.reactions?.filter(a=>a?.from?.userId!==t?.userId):e.reactions.push({from:t,lastUpdated:this.timestamp}),e.reactions.length?yield this.updateReaction(e):yield this.deleteReactionPinAnnotation(e?.annotationId),e}catch(t){this.loggingService.catch("Error in ReactionService updateUserInReaction: ",t)}})}removeUserFromReaction(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeUserFromReaction","color: green;");try{let t=this.authService.getUser();t&&(e?.reactions||(e.reactions=[]),e.reactions=e?.reactions?.filter(i=>i?.from?.userId!==t?.userId),this.updateReaction(e))}catch(t){this.loggingService.catch("Error in ReactionService removeUserFromReaction: ",t)}}updateReaction(e,t,i){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateReaction","color: green;");try{if(this.authService.getUser()){if(e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let g=d.iterateNext();g&&(Zr(g)||(e.targetElement=null))}}let a=JSON.parse(JSON.stringify(e));if(a.position=null,a.lastUpdated=this.timestamp,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId});a.metadata=f(f({},a?.metadata),d)}let{documentId:l,organizationId:s}=a?.metadata||{};return i?yield this.commonDbService.updateData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))}):yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))}),a}}catch(a){this.loggingService.catch("Error in ReactionService updateReaction: ",a)}})}deleteReactionPinAnnotation(e,t){return Q(this,null,function*(){try{let i=this.getAnnotationById(e),{documentId:a,organizationId:l}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(i),s=i&&!i.commentAnnotationId?{annotationData:i,actionType:"delete",notificationSource:"reaction"}:void 0;yield this.commonDbService.deleteData({feature:"reaction",properties:{id:e,documentId:a,organizationId:l},extraData:s})}catch(i){this.loggingService.catch("Error in ReactionService deleteReactionPinAnnotation: ",i)}})}setCustomReactions(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;"),this.customReactions$.next(e),this.emojiService.setEmojiList(e)}catch(t){this.loggingService.catch("Error in ReactionService setCustomReactions: ",t)}}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in ReactionService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in ReactionService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}sanitizeReactionAnnotation(e){try{e&&(e.iconUrl&&(e.iconUrl=this.domService.sanitizeHtml(e.iconUrl)),e.iconEmoji&&(e.iconEmoji=this.domService.sanitizeHtml(e.iconEmoji)),e.icon&&(e.icon=this.domService.sanitizeHtml(e.icon)))}catch(t){this.loggingService.catch("Error in ReactionService sanitizeReactionAnnotation: ",t)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getReactionAnnotationForClient(e){try{let t=["isReactionResolverUsed","pageInfo","from","involvedUserIds","position"],i=JSON.parse(JSON.stringify(e)),a={};return Object.keys(i).forEach(l=>{t.includes(l)||(l==="reactions"?a.fromUsers=i[l]:a[l]=i[l])}),a}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationForClient: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(lt),X(We),X(Ft),X($n),X(Tn),X(ct),X(Be),X(vv),X(Ln),X(x),X(il))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tg={user:"componentConfigSignal.appState.user",isUserAdmin:"componentConfigSignal.appState.isUserAdmin",isKnownUser:"componentConfigSignal.appState.isKnownUser",repliesUniqueUsers:"componentConfigSignal.appState.repliesUniqueUsers",annotation:"componentConfigSignal.data.annotation",annotations:"componentConfigSignal.data.annotations",allAnnotations:"componentConfigSignal.data.allAnnotations",ghostComment:"componentConfigSignal.data.ghostComment",selectedFiles:"parentLocalUIState.selectedFiles",invalidSelectedFiles:"parentLocalUIState.invalidSelectedFiles",selectedAttachments:"parentLocalUIState.selectedAttachments",editComment:"parentLocalUIState.editComment",editCommentIndex:"parentLocalUIState.editCommentIndex",assignTo:"componentConfigSignal.data.assignTo",selectedUserContacts:"componentConfigSignal.data.selectedUserContacts",localRecordedData:"parentLocalUIState.localRecordedData",customList:"componentConfigSignal.data.customList",toOrganizationUserGroup:"componentConfigSignal.data.toOrganizationUserGroup",taggedUserContacts:"componentConfigSignal.data.taggedUserContacts",taggedGroups:"componentConfigSignal.data.taggedGroups",attachmentsToDelete:"parentLocalUIState.attachmentsToDelete",customChipData:"componentConfigSignal.data.customChipData",selectedCustomChipSet:"componentConfigSignal.data.selectedCustomChipSet",currentDialogView:"componentConfigSignal.data.currentDialogView",sidebarMode:"parentLocalUIState.sidebarMode",inboxMode:"parentLocalUIState.inboxMode",dialogMode:"parentLocalUIState.dialogMode",inlineCommentMode:"parentLocalUIState.inlineCommentMode",inlineCommentSectionMode:"parentLocalUIState.inlineCommentSectionMode",focusedThreadMode:"parentLocalUIState.focusedThreadMode",isFocusedThreadEnabled:"parentLocalUIState.isFocusedThreadEnabled",pageModeComposer:"parentLocalUIState.pageModeComposer",darkMode:"parentLocalUIState.darkMode",variant:"parentLocalUIState.variant",disabled:"parentLocalUIState.disabled",commentPinSelected:"parentLocalUIState.commentPinSelected",fullExpanded:"parentLocalUIState.fullExpanded",commentDialogSelected:"parentLocalUIState.commentDialogSelected",readOnly:"parentLocalUIState.readOnly",dialogShadowDOM:"parentLocalUIState.dialogShadowDOM",locationVersion:"parentLocalUIState.locationVersion",composerPosition:"parentLocalUIState.composerPosition",dialogOpenedInSidebar:"parentLocalUIState.dialogOpenedInSidebar",expandOnSelection:"parentLocalUIState.expandOnSelection",selectedVisibility:"parentLocalUIState.selectedVisibility",selectedVisibilityUsers:"parentLocalUIState.selectedVisibilityUsers",containerComponentId:"componentConfigSignal.uiState.containerComponentId",isPrivateComment:"componentConfigSignal.uiState.isPrivateComment",assignToMenuOpened:"parentLocalUIState.assignToMenuOpened",showGhostCommentMessage:"componentConfigSignal.uiState.showGhostCommentMessage",showReplies:"componentConfigSignal.uiState.showReplies",collapsedComments:"componentConfigSignal.uiState.collapsedComments",showAllComments:"componentConfigSignal.uiState.showAllComments",composerContent:"parentLocalUIState.composerContent",composerContentHTML:"parentLocalUIState.composerContentHTML",composerInOpenState:"parentLocalUIState.composerInOpenState",composerMode:"componentConfigSignal.uiState.composerMode",multiThreadAnnotationId:"componentConfigSignal.uiState.multiThreadAnnotationId",maxReplyAvatars:"componentConfigSignal.uiState.maxReplyAvatars",showSuggestionModeActions:"componentConfigSignal.uiState.showSuggestionModeActions",uploadingAttachments:"componentConfigSignal.uiState.uploadingAttachments",playVideoInFullScreen:"componentConfigSignal.uiState.playVideoInFullScreen",commentDialogUniqueId:"componentConfigSignal.uiState.commentDialogUniqueId",recorderInitConfig:"componentConfigSignal.uiState.recorderInitConfig",isInputFocused:"componentConfigSignal.uiState.isInputFocused",showCommentButtons:"componentConfigSignal.uiState.showCommentButtons",isAutocompleteDropdownOpen:"componentConfigSignal.uiState.isAutocompleteDropdownOpen",bottomSheetMode:"componentConfigSignal.uiState.bottomSheetMode",commentComposerMode:"componentConfigSignal.uiState.commentComposerMode",shouldScrollToBottom:"componentConfigSignal.uiState.shouldScrollToBottom",deviceType:"componentConfigSignal.uiState.deviceType",showReplyComposer:"componentConfigSignal.uiState.showReplyComposer",reactionToolOpenIndex:"componentConfigSignal.uiState.reactionToolOpenIndex",openDropdownIndexValue:"componentConfigSignal.uiState.openDropdownIndexValue",hasReactionsByCommentId:"componentConfigSignal.uiState.hasReactionsByCommentId",newComment:"parentLocalUIState.composerContent",newCommentHTML:"parentLocalUIState.composerContentHTML",canResolveAnnotation:"componentConfigSignal.featureState.canResolveAnnotation",canUnresolveAnnotation:"componentConfigSignal.featureState.canUnresolveAnnotation",dialogSelectedByKnownUser:"componentConfigSignal.featureState.dialogSelectedByKnownUser",resolveStatusAccessAdminOnly:"componentConfigSignal.featureState.resolveStatusAccessAdminOnly",enableResolve:"componentConfigSignal.featureState.enableResolve",isPlanExpired:"componentConfigSignal.featureState.isPlanExpired",moderatorMode:"componentConfigSignal.featureState.moderatorMode",enableAutoCategorize:"componentConfigSignal.featureState.enableAutoCategorize",suggestionMode:"componentConfigSignal.featureState.suggestionMode",commentAcceptedStatus:"componentConfigSignal.featureState.commentAcceptedStatus",commentRejectedStatus:"componentConfigSignal.featureState.commentRejectedStatus",enableSignInButton:"componentConfigSignal.featureState.enableSignInButton",enableUpgradeButton:"componentConfigSignal.featureState.enableUpgradeButton",enableGhostCommentsMessage:"componentConfigSignal.featureState.enableGhostCommentsMessage",replyAvatars:"componentConfigSignal.featureState.replyAvatars",userMentions:"componentConfigSignal.featureState.userMentions",recordingSummaryEnabled:"componentConfigSignal.featureState.recordingSummaryEnabled",enableAttachment:"componentConfigSignal.featureState.enableAttachment",allowedFileTypes:"componentConfigSignal.featureState.allowedFileTypes",allowedRecordings:"componentConfigSignal.featureState.allowedRecordings",screenSharingSupported:"componentConfigSignal.featureState.screenSharingSupported",enterKeyToSubmit:"componentConfigSignal.featureState.enterKeyToSubmit",deleteOnBackspace:"componentConfigSignal.featureState.deleteOnBackspace",showScreenSizeInfo:"componentConfigSignal.uiState.showScreenSizeInfo",enableReactions:"componentConfigSignal.featureState.enableReactions",isInsidePdfViewer:"componentConfigSignal.featureState.isInsidePdfViewer",sidebarButtonOnCommentDialogVisible:"componentConfigSignal.uiState.sidebarButtonOnCommentDialogVisible",enableStatus:"componentConfigSignal.featureState.enableStatus",customStatusesShown:"componentConfigSignal.featureState.customStatusesShown",statusOptions:"componentConfigSignal.featureState.statusOptions",enablePriority:"componentConfigSignal.featureState.enablePriority",visibilityOptions:"componentConfigSignal.featureState.visibilityOptions",priorityOptions:"componentConfigSignal.featureState.priorityOptions",enableAssignment:"componentConfigSignal.featureState.enableAssignment",enableNotifications:"componentConfigSignal.featureState.enableNotifications",enableEdit:"componentConfigSignal.featureState.enableEdit",enableDelete:"componentConfigSignal.featureState.enableDelete",enablePrivateMode:"componentConfigSignal.featureState.enablePrivateMode",deleteThreadWithFirstComment:"componentConfigSignal.featureState.deleteThreadWithFirstComment",seenByUsers:"componentConfigSignal.featureState.seenByUsers",allowAssignment:"componentConfigSignal.featureState.enableAssignment",allowToggleNotification:"componentConfigSignal.featureState.enableNotifications",allowEdit:"componentConfigSignal.featureState.enableEdit",allowChangeCommentAccessMode:"componentConfigSignal.featureState.enablePrivateMode",notificationEnabled:"notificationEnabled",mainCommentId:"componentConfigSignal.data.annotation.comments.0.commentId",commentObj:"commentObj",commentIndex:"commentIndex",userContact:"selectorItem.contact",comment:"commentObj",commentAnnotation:"componentConfigSignal.data.annotation",commentAnnotations:"componentConfigSignal.data.annotations",context:"parentLocalUIState.context",focusedAnnotation:"focusedAnnotation",notification:"notification",notificationsPanel:"notificationsPanel",selectedMinimalFilterDropdownOption:"selectedMinimalFilterDropdownOption",appliedFiltersCount:"appliedFiltersCount",filteredCommentAnnotationsCount:"filteredCommentAnnotationsCount",unreadCommentAnnotationCount:"unreadCommentAnnotationCount"},FWe=["user","annotation","annotations","allAnnotations","userContact","comment","commentAnnotation","commentAnnotations","recorderInitConfig","ghostComment","editComment","assignTo","customChipData","currentDialogView","context","focusedAnnotation","notification","notificationsPanel","selectedMinimalFilterDropdownOption"],I=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(n,o,r,e,t,i){this.authService=n,this.commentService=o,this.loggingService=r,this.injector=e,this.docService=t,this.configService=i,this.subscriptions=[],this.commonData$=new Se({}),this.evaluateConditionTriggered=new Le,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=Ae({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(f(f({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(l=>(l=f(f({},l),a),l)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(n=>n.unsubscribe())}catch(n){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",n)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(n,o){try{return Object.keys(o).forEach(r=>{o[r].path=this.modifyPathBasedOnCondition(r,n)}),o}catch(r){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",r)}}getComputedValues(n,o,r,e,t,i){try{Object.keys(r).forEach(a=>{let l;if(lo(n)?l=ce(()=>Cl(n(),r[a].path)):l=ce(()=>Cl(n,r[a].path)),lo(l()))On(()=>{try{let s=l()();r[a].value=s,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}catch{}},{injector:this.injector,allowSignalWrites:!0});else{let s=l();r[a].value=s,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(n,o){try{let r=n.match(/^([^\.\[]+)/),e=r?r[1]:n,t=n.slice(e.length);if(Tg[n])return Tg[n];if(["commentDialogOptionsDropdownConfigSignal","commentDialogStatusDropdownConfigSignal"].includes(e)&&t.startsWith(".")){let a=t.slice(1),l=a.match(/^([^\.\[]+)/),s=l?l[1]:a,d=a.slice(s.length);return Tg[s]?Tg[s]+d:"componentConfigSignal."+a}if(e&&o&&typeof o=="function"){let a=o();if(a&&e in a){let s=n.match(/\[(.*?)\]/);if(s&&s[1]){let d=s[1];if(d.includes(".")){let g=d.split(".")[0];if(Tg[g]){let u=d.replace(g,Tg[g]);return n.replace(`[${d}]`,`[${u}]`)}return g&&a&&g in a?n:n.replace(`[${d}]`,`[componentConfigSignal.${d}]`)}}return n}let l=a?.componentConfigSignal;if(l&&typeof l=="function"){let s=l();if(s&&e in s)return"componentConfigSignal."+n}}return Tg[e]?FWe.includes(e)?Tg[e]+t:Tg[e]:"componentConfigSignal."+n}catch(r){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",r),n}}applyConditionalClasses(n,o){try{this.elementRef=n,this.data=o}catch(r){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",r)}}executeConditionalClasses(){try{let n=this.getHostElementAttributes(this.elementRef),r=[...Object.keys(n).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:n[e]}))];if(n["velt-class"]){let e=n["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,i=[],a=0,l=100,s;for(;(s=t.exec(e))!==null;){if(a++>l){this.loggingService.catch("Too many class definitions detected.");break}if(s.length<3)continue;let[,d,g]=s;!d||!g||d.split(" ").forEach(u=>{u.trim()&&i.push({name:`velt-class-${u.trim()}`,value:g.trim()})})}r=[...r,...i]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),r.forEach(e=>{let t=e.name.replace("velt-class-","");this.condition=e.value,this.condition&&(this.extractProps(),this.extractedProps=this.getModifiedPathBasedOnCondition(this.dataComponentConfigSignal,this.extractedProps),this.getComputedValues(this.dataComponentConfigSignal,this.evaluateCondition,this.extractedProps,t,this.elementRef,e.value))})}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}updateDataComponentConfigSignal(n,o){try{n==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(r=>k(f({},r),{[n]:o}))}catch(r){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",r)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let n;for(;(n=this.conditionRegex.exec(this.condition))!==null;){let o=n[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(n){this.loggingService.catch("Error in DynamicDataService extractProps: ",n)}}hasDynamicParts(n){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(n),r=/\[[^[\]]*[\.\[][^[\]]*\]/.test(n);return o||r}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(n,o,r){try{if(r){let e=this.extractedProps,t=r.replace(this.conditionRegex,(l,s)=>{let d=e[s];if(d&&d.value!==void 0){let g=d.value;return typeof g=="string"?`'${g}'`:typeof g=="boolean"||typeof g=="number"?String(g):g===null?"null":typeof g=="object"?g?"true":"false":String(g)}return"false"}),i=this.sanitizeCondition(t),a=this.safeEval(i);return n&&o&&(a?this.setHostElementClasses(o,n):this.removeHostElementClasses(o,n)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(n){try{return n.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let n=this.tokenize(expression.trim());return this.evaluateTokens(n)}else return eval(expression)}catch(n){return this.loggingService.catch("safeEval error",n),!1}}tokenize(n){try{if(!n||n.trim()==="")return[];let o=[],r=0;for(;r<n.length;){let e=n[r];if(/\s/.test(e)){r++;continue}if(e==='"'||e==="'"){let t=e,i="";for(r++;r<n.length;)if(n[r]==="\\"&&r+1<n.length)i+=n[r+1],r+=2;else if(n[r]===t){r++;break}else i+=n[r],r++;o.push({type:"string",value:i});continue}if(e==="("){o.push({type:"lparen",value:"("}),r++;continue}if(e===")"){o.push({type:"rparen",value:")"}),r++;continue}if(r<n.length-2&&n.substring(r,r+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),r+=3;continue}if(r<n.length-2&&n.substring(r,r+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),r+=3;continue}if(r<n.length-1&&n.substring(r,r+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)===">="){o.push({type:"operator",value:">=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),r+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),r++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),r++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),r++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;r<n.length&&/[a-zA-Z0-9._]/.test(n[r]);)t+=n[r],r++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}r++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(n){try{if(!n||n.length===0)return!1;let o=this.infixToPostfix(n);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(n){try{let o=[],r=[];for(let e of n)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")r.push(e);else if(e.type==="operator"){for(;r.length>0;){let t=r[r.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(r.pop())}r.push(e)}else if(e.type==="lparen")r.push(e);else if(e.type==="rparen"){for(;r.length>0&&r[r.length-1].type!=="lparen";)o.push(r.pop());r.length>0&&r.pop()}for(;r.length>0;){let e=r.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(n){try{let o=[];for(let r of n)if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="null"||r.type==="undefined"||r.type==="identifier")o.push(r.value);else if(r.type==="unary"){if(o.length>=1){let e=o.pop();r.value==="!"&&o.push(!this.isTruthy(e))}}else if(r.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();r.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):r.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,r.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(n){try{let o=n.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),n}}compare(n,o,r){try{switch(r){case"===":return n===o;case"!==":return n!==o;case"==":return n==o;case"!=":return n!=o;case"<":return n<o;case">":return n>o;case"<=":return n<=o;case">=":return n>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(n){try{return n==null||n===""||n==="false"?!1:n==="true"?!0:typeof n=="number"?n!==0:!!n}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(n){try{let o=n,r={};for(let e of o.attributes)r[e.name]=e.value;return r}catch{return{}}}setHostElementClasses(n,o){try{n.classList.add(o)}catch{}}removeHostElementClasses(n,o){try{n.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(X(We),X(Pe),X(x),X(Ot),X(ct),X(Ft))},_DynamicDataService.\u0275prov=Me({token:_DynamicDataService,factory:_DynamicDataService.\u0275fac,providedIn:"root"});let DynamicDataService=_DynamicDataService;return DynamicDataService})();var oe=(()=>{let o=class o{set veltIf(e){try{e&&this.setIfCondition(e)}catch(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,i){this._elementRef=e,this._dynamicDataService=t,this._loggingService=i,this.componentConfigSignal=Ae({}),this.veltElement=!0,this.conditionSignal=Ae(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}ngOnInit(){try{this._dynamicDataService.applyConditionalClasses(this._elementRef?.nativeElement,{componentConfigSignal:this.componentConfigSignal})}catch(e){this._loggingService.catch("Error in BaseComponent ngOnInit:",e)}}ngOnDestroy(){}setIfCondition(e){try{this.conditionSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(y(Z),y(I),y(x))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,i){},encapsulation:2});let n=o;return n})();var _t=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.configService=t,this.darkMode$=new Se(!1)}setDarkMode(e){try{let t=document.documentElement;if(!t)return;e?t.setAttribute(U.ATTRIBUTES.VELT_THEME,"dark"):t.removeAttribute(U.ATTRIBUTES.VELT_THEME),this.darkMode$.next(e)}catch(t){this.loggingService.catch("Error in theme service setDarkMode: ",t)}}getDarkMode$(){return this.darkMode$.asObservable()}updateListenerOnConfigChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.usePrefersColorScheme){this.enablePrefersColorScheme();return}this.disablePrefersColorScheme()})}catch(e){this.loggingService.catch("Error in theme service updateListenerOnConfigChange: ",e)}}enablePrefersColorScheme(){try{if(this.disablePrefersColorScheme(),!window.matchMedia)return;this.darkModeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.setDarkMode(this.darkModeQuery.matches),this.darkModeQueryListener=e=>{this.setDarkMode(e.matches)},this.darkModeQuery.addEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service enablePrefersColorScheme: ",e)}}disablePrefersColorScheme(){try{this.darkModeQuery&&this.darkModeQueryListener&&this.darkModeQuery.removeEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service disablePrefersColorScheme: ",e)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(Ft))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wt=(()=>{let o=class o extends oe{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,i,a,l,s,d){super(e,s,d),this._elementRef=e,this._themeService=t,this._changeDetector=i,this._featureService=a,this._componentDarkModeObservable=l,this._componentDarkMode=null,this._globalDarkMode=!1,this._featureDarkMode=!1,this._themeSubscriptions=[],this._darkMode=!1,this.darkMode=!1,this.darkModeSubject$=new Se(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(g=>{this._globalDarkMode=g,this.setDarkMode()})),this._featureService&&(this._featureService instanceof Pe?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(g=>{this._featureDarkMode=g,this.setDarkMode()})):this._featureService instanceof Hi&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(g=>{g!==null&&(this._featureDarkMode=g),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Gt&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(g=>{this._componentDarkMode=g,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,this.setDarkMode()}}catch{}}setComponentDarkMode(e){try{this._componentDarkMode=e,this.setDarkMode()}catch{}}setDarkMode(){try{this._componentDarkMode===null?this._featureDarkMode?this.darkMode=!0:this.darkMode=!!this._globalDarkMode:this.darkMode=!!this._componentDarkMode,this.darkMode?this._elementRef.nativeElement.hasAttribute("dark")||this._elementRef.nativeElement.setAttribute("dark",""):this._elementRef.nativeElement.hasAttribute("dark")&&this._elementRef.nativeElement.removeAttribute("dark"),this.darkModeSubject$.next(this.darkMode),this._changeDetector&&this._changeDetector.markForCheck()}catch{}}ngOnDestroy(){try{super.ngOnDestroy(),this._themeSubscriptions.forEach(e=>{e.unsubscribe()})}catch{}}};o.\u0275fac=function(t){return new(t||o)(y(Z),y(_t),y(Qt),y("FeatureService",8),y(Gt),y(I),y(x))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[P,st],decls:0,vars:0,template:function(t,i){},encapsulation:2,changeDetection:0});let n=o;return n})();var Ze=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new Se(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let i=this.wireframeMap.value,a=i.get(e),l=t.children.length>0||t.innerHTML?.trim()?.length>0,s=a&&(a.children.length>0||a.innerHTML?.trim()?.length>0);(!a||l&&!s)&&(i.set(e,t),this.wireframeMap.next(i))}catch(i){this.loggingService.catch("Error in WireframeService setWireframe: ",i)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((i,a)=>{let l=t.get(a),s=i.children.length>0||i.innerHTML?.trim()?.length>0,d=l&&(l.children.length>0||l.innerHTML?.trim()?.length>0);(!l||s&&!d)&&t.set(a,i)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a&&(a?.children?.length>0||a?.innerHTML?.trim()?.length>0)?a:void 0}catch(i){this.loggingService.catch("Error in WireframeService getWireframe: ",i);return}}getConditionElement(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a}catch(i){this.loggingService.catch("Error in WireframeService getConditionElement: ",i);return}}getWireframe$(e,t=!0){return this.wireframeMap.asObservable().pipe(ue(i=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var L_e=n=>({componentConfigSignal:n}),LWe=(n,o)=>({condition:n,data:o}),UWe=(n,o,r,e,t)=>({template:n,context:o,componentName:"velt-confirm-dialog-wireframe",variant:r,setIfCondition:e,componentElementRef:t});function VWe(n,o){if(n&1&&(C(0),D(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),h(3,"div",6),D(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),S(),_()),n&2){let r=c(3);m(),v("componentConfigSignal",r.componentConfigSignal),m(),v("componentConfigSignal",r.componentConfigSignal),m(2),v("componentConfigSignal",r.componentConfigSignal),m(),v("componentConfigSignal",r.componentConfigSignal)}}function BWe(n,o){if(n&1&&(C(0),p(1,VWe,6,4,"ng-container",4),_()),n&2){let r=c().ngIf,e=c();m(),v("veltDynamicTemplate",j(3,UWe,e.template,G(1,L_e,e.componentConfigSignal),r==null?null:r.variant,e.setIfCondition.bind(e),e.elementRef))}}function jWe(n,o){if(n&1&&(C(0),p(1,BWe,2,9,"ng-container",3),_()),n&2){let r=c();m(),v("veltIf",w(3,LWe,r.conditionSignal(),G(1,L_e,r.componentConfigSignal)))}}var xl=(()=>{let o=class o extends wt{constructor(e,t,i,a,l,s,d){super(l,a,void 0,void 0,void 0,d,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=i,this.themeService=a,this.elementRef=l,this.dynamicDataService=d,this.subscriptions=[],this.componentConfigSignal=Ae({title:"",message:"",yesButton:"",noButton:"",variant:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{s&&(this.componentConfigSignal.update(g=>(g=f(f({},g),s),g)),s?.darkMode&&[!0,!1].includes(s?.darkMode)&&super.setComponentDarkMode(s?.darkMode)),this.setZIndex()}catch(g){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",g)}}ngOnInit(){try{this.loggingService.log("%c[WB] Calling FUNCTION: ngOnInit","color: green;");let e="velt-confirm-dialog-wireframe";super.ngOnInit(),this.componentConfigSignal()?.variant&&(e+=`---${this.componentConfigSignal()?.variant}`),this.subscriptions.push(this.wireframeService.getWireframe$(e).subscribe(t=>{if(t){let i=document.createElement(t.tagName);i.innerHTML=t.innerHTML,this.template=i}}))}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnInit: ",e)}}ngOnDestroy(){super.ngOnDestroy();try{this.subscriptions.forEach(e=>e.unsubscribe())}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnDestroy: ",e)}}setZIndex(){try{if(this.dialogRef){let e=this.dialogRef._overlayRef;e&&(e.backdropElement&&(e.backdropElement.style.zIndex="2147483647"),e.hostElement&&(e.hostElement.style.zIndex="2147483647"))}}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent setZIndex: ",e)}}closeDialog(e){try{this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}};o.\u0275fac=function(t){return new(t||o)(y(x),y(Vi),y(Ze),y(_t),y(Z),y(Yc,8),y(I))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},standalone:!1,features:[B([I]),P],decls:3,vars:5,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,i){if(t&1&&(h(0,"div",1,0),p(2,jWe,2,6,"ng-container",2),S()),t&2){let a=Ie(1);v("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),T("data-testid",i.componentId),m(2),v("ngIf",i.componentConfigSignal())}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%] *[_ngcontent-%COMP%]{outline:0}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)}.velt-confirm-dialog[_ngcontent-%COMP%]{width:455px;padding:40px;display:block;box-sizing:border-box;background-color:var(--velt-background-0)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface:has(snippyly-confirm-dialog){border-radius:var(--velt-border-radius-xl);padding:0}@media (max-width: 768px){.velt-confirm-dialog[_ngcontent-%COMP%]{width:auto;max-width:455px;padding:24px}}"],changeDetection:0});let n=o;return n})();var xn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V,q,ae,fe,ie,Ce){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.commonDbService=l,this.commonDbUtilsService=s,this.commentUtilsService=d,this.commentAnnotationsResolverService=g,this.notificationResolverService=u,this.databaseService=b,this.docService=E,this.domService=A,this.iamService=M,this.loggingService=V,this.notificationUtilsService=q,this.usersService=ae,this.functions=fe,this.userPermissionService=ie,this.coreActionsService=Ce,this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new Se([]),this.rawNotificationsByIdMap$=new Se(new Map),this.processedNotifications$=new Se([]),this.userNotificationsFromServer$=new Se(null),this.readNotificationsOnForYouTab$=new Se(!1),this.currentDocumentOnly$=new Se(!1),this.notificationViews$=new Se({}),this.notificationsByIdMap$=new Se(new Map),this.historyPanelVisible$=new Se(!1),this.notificationsForYou$=new Se(null),this.notificationsByDocumentIdMap$=new Se(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new Se(null),this.maxNotificationDays$=new Se(15),this.tabConfig$=new Se({people:{enable:!1}}),this.settingsConfig$=new Se(null),this.setSettingsConfigByOrganization$=new Se(!1),this.muteAllNotifications$=new Se(!1),this.enableSettings$=new Se(!1),this.selfNotifications$=new Se(!1),this.settingsInitialConfig$=new Se([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new Se(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe($e(xe=>!!xe),ut(1)).subscribe(xe=>{if(xe){this.db=xe;try{let ke=this.configService.getProxyConfig(),ye=En.firebaseNotificationsDatabaseURL;ke?.v1DbHost&&ye&&(ye=kN(ye,ke.v1DbHost)),this.notificationsDb=x1(void 0,ye),ke?.v1DbHost&&ye&&this.databaseService.lockDatabaseHost(this.notificationsDb)}catch(ke){this.loggingService.catch("Error initializing notifications DB, using default: ",ke),this.notificationsDb=xe}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},xe=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",xe)}),this.authService.getUser$().subscribe(xe=>{xe?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(ke=>{this.notificationsByDocumentIdSubscription[ke]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(xe=>{if(xe){let ke=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(xe||{}).forEach(ye=>{let Oe=ke?.[ye]?.notifications;Oe?.length&&Oe.forEach(Ne=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Ne},xe)?.notification})}),this.notificationsByDocumentIdMap$.next(ke)}})}catch(xe){this.loggingService.catch("Error in NotificationService constructor: ",xe)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([i,a])=>{t[i]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=++this.settingsConfigGeneration,i=It(this.authService.getUser()?.userId??""),a=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:e?.documentId,organizationId:e?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:i}});if(t!==this.settingsConfigGeneration)return;if(a?.notificationsConfig)this.setDBConfigDataToInitialConfig(a?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let l={};this.settingsInitialConfig$.getValue().forEach(d=>{if(d.enable){let g=d?.values?.find(u=>u.id===d.default);l[d.id]=g||d?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(l).forEach(d=>{s[d]=l[d].id}),yield this.updateSettingsConfigToDb(s)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=It(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe($e(t=>t===!0),_e(()=>pn([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe($e(([t,i,a])=>(i||!!t)&&!!a?.organizationId),_e(([t,i,a])=>po(this.getInitialConfigFromDB(t)).pipe(_e(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?void 0:t?.documentId,organizationId:t?.organizationId??a?.organizationId,userId:e}}).pipe(ue(l=>{l?.data?.notificationsConfig&&!Mr(l?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(l?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.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(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(_e(()=>this.getCurrentDocumentOnly$().pipe(_e(e=>e?this.docService.getDocumentPaths$().pipe(ue(t=>{})):le(void 0)))),on(()=>{this.notificationsByDocumentIdMap$.next(null)}),_e(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Nr(),ue(([e,t])=>{let i=e?.map(g=>g.documentId),a=t?.map(g=>g.documentId),l=i?.filter(g=>!a?.includes(g)),s=a?.map(g=>({documentId:g,timestamp:t?.find(u=>u.documentId===g)?.timestamp})).filter(g=>!i?.includes(g.documentId)),d=a?.map(g=>{let u=t?.find(b=>b.documentId===g)?.timestamp;return{documentId:g,timestamp:u}}).filter(g=>{let u=e?.find(b=>b.documentId===g.documentId)?.timestamp;return u&&g.timestamp&&u!==g.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),d?.length&&this.fetchNotificationsForDocumentIds(d,1),l?.forEach(g=>{this.removeNotificationsForDocumentId(g)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).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(_e(t=>this.docService.getOrganizationConfig$().pipe(ue(i=>{let a=null,l=this.configService.getApiKey(),s=i?.organizationId||t?.organizationId;return l&&s&&(a=new dv({apiKey:l,organizationId:s})),{user:t,documentPaths:a}}))),_e(t=>{let{user:i,documentPaths:a}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return le(null);if(i&&a?.organizationNotificationsLastNotificationTimestamp){let l=new Date,s=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;l.setDate(l.getDate()-s);let d=l.getTime(),g=[_r(ft("timestamp",">=",d),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ft("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];return this.getCurrentDocumentOnly()||(g.push(vo("timestamp","desc")),g.push(lv(e))),this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:g}}).pipe(ue(u=>u?.data),ue(u=>{let b=[];return Object.keys(u||{}).forEach(E=>{let A=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],M=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(M&&M.id&&M?.timestamp===A){let V=M.id,q=u[E]?.metadata?.documentId,ae=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),fe=ae?.[q]??{documentMetadata:null,notifications:[]},ie=fe.notifications??[],Ce=ie?.findIndex(xe=>xe.id===V);Ce!==-1&&(ie.splice(Ce,1),this.notificationsByDocumentIdMap$.next(k(f({},ae),{[q]:k(f({},fe),{notifications:ie})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(V)&&this.notificationResolverService.deleteNotification(V,this.docService.getDocumentPaths()?.clientOrganizationId??"")}b.push({documentId:E,timestamp:A})}),b}),Jn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),le([]))))}return le(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),le([])}}resolveAndUpdateDocumentNotifications(e,t){try{Object.keys(e).forEach(i=>{let a=e[i]?.documentMetadata||{},l;if(t==="user")l=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:e[i]?.notifications||[]});else if(t==="notification"){let s=e[i]?.notifications?.reduce((g,u)=>(g[u.notificationId]=u,g),{}),d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:s});l=Object.values(d??{})}else{let s=e[i]?.notifications?.reduce((g,u)=>(g[u.notificationId]=u,g),{}),d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:s});l=Object.values(d??{})}l.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),this.setNotificationForDocumentIdInCache(i,a,l)})}catch(i){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",i)}}resolveAndMergeUserNotifications(e,t,i=!1){try{let a=e;if(i&&t==="comment"){let u=this.getUserNotificationsFromServer()??[],b=new Set(e.map(E=>E.notificationId));a=u.filter(E=>b.has(E.notificationId)).concat(e.filter(E=>!u.some(A=>A.notificationId===E.notificationId)))}let l=a.reduce((u,b)=>(u[b.notificationId]=b,u),{}),s;if(t==="user"){let u=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}else if(t==="notification"){let u=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}else{let u=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}s.forEach(u=>{u.notification=this.getClientNotificationObject(u)});let d=this.getUserNotificationsFromServer()??[],g=new Map(d.map(u=>[u.notificationId,u]));s.forEach(u=>{g.set(u.notificationId,u)}),this.setUserNotificationsFromServer(Array.from(g.values()))}catch(a){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",a)}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let i=Gr(this.functions,Wr({url:En.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let l=this.getStartAtTimestamp(),s={};if(e.forEach(ie=>{if(ie?.documentId){let Ce=this.getAllowedDocumentMetadataByDocumentId(ie.documentId);Ce&&(s[ie.documentId]=Ce)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let ie=[];if(e.forEach(Oe=>{this.docService.getDocumentMetadata(Oe.documentId)||ie.push(Oe.documentId)}),ie.length){let Oe=this.authService.getUser(),Ne=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let Ue=yield _l({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Oe?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:ie},getSdkProxy:Ne,userId:Oe?.userId??""});if(Ue?.data?.length){let ze={};Ue.data.forEach(Ge=>{Ge?.documentId&&(ze[Ge.documentId]=Ge)}),this.docService.setAllDocumentMetadata(f(f({},this.docService.getAllDocumentMetadataMap()),ze))}}catch(Ue){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",Ue)}}let Ce=[],xe=[];e.forEach(Oe=>{let Ne=this.docService.getDocumentMetadata(Oe.documentId);Ne?.clientDocumentId?Ce.push({userId:this.authService.getUser()?.userId??"",resource:{id:Ne.clientDocumentId,type:oa.DOCUMENT,source:ro.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):xe.push(Oe.documentId)}),xe.length&&(e=e.filter(Oe=>!xe.includes(Oe.documentId)));let ke=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ke,methodName:ro.GET_NOTIFICATIONS,source:"internal",payload:{requests:Ce}});let ye=yield this.userPermissionService?.onResourceAccessRequired({requests:Ce,uniqueId:ke,methodName:ro.GET_NOTIFICATIONS});ye?.success&&ye?.data?.length?ye.data.forEach(Oe=>{!Oe.hasAccess&&Oe.resourceId&&(e=e.filter(Ne=>Ne.documentId!==mi(Oe.resourceId)))}):e=[]}catch(ie){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",ie),e=[]}if(!e.length)return[];let d=this.userPermissionService?.getPermissionsCache()?.filter(ie=>ie.type===oa.CONTEXT),g={organizationId:a,documentIds:e.filter(ie=>!!ie.documentId&&!!ie.timestamp).map(ie=>({documentId:ie.documentId,timestamp:ie.timestamp??0})),timestamp:l,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:d,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},u=yield this.notificationUtilsService.handleNotificationEncryption({data:g}),b=yield i({veltData:u}),E=b?.data?.data?.veltData||{},A=b?.data?.data?.veltAdditionalData||{},M="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),V=yield Q1(E,M),{userNotifications:q=[],userNotificationIdsInDocNotifications:ae=[],permissionResults:fe=[]}=yield Q1(A,M);if(this.userPermissionService?.getIsContextEnabled()){let ie=[...this.userPermissionService?.getPermissionsCache()??[],...fe??[]];this.userPermissionService?.setPermissionsCache(ie)}if(V&&typeof V=="object"){let ie=this.usersService.userDataProviderAvailable(),Ce=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),xe=this.notificationResolverService.notificationDataProviderAvailable(),ke=[],ye=[],Oe=[];Object.keys(V).forEach((ze,Ge)=>{let $r=V[ze].documentMetadata;if($r){let Tt=this.allowedDocumentMetadataMap$.value||{};(!Tt?.[ze]||!Mr(Tt?.[ze],$r))&&this.allowedDocumentMetadataMap$.next(k(f({},Tt),{[ze]:$r}))}let et=V[ze].notifications||[];et.forEach(Tt=>{ae.includes(Tt.notificationId)&&!q.find(Xe=>Xe.notificationId===Tt.notificationId)&&q.push(JSON.parse(JSON.stringify(Tt))),Tt.notification=this.getClientNotificationObject(Tt)}),this.setNotificationForDocumentIdInCache(ze,$r,et),ie&&(ke.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldAwait:!0,forceResolve:!0})),ke.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldAwait:!0,forceResolve:!0}))),Ce&&(ye.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldCommentAnnotationsResolverAwait:!0})),ye.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldCommentAnnotationsResolverAwait:!0}))),xe&&(Oe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldNotificationResolverAwait:!0})),Oe.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldNotificationResolverAwait:!0})))});let Ne=JSON.parse(JSON.stringify(q));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...q]),(xe||ie||Ce)&&(()=>{let ze=Promise.resolve();if(xe&&(ze=ze.then(()=>Promise.allSettled(Oe)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"notification"),this.resolveAndMergeUserNotifications(Ne,"notification")})),ie&&(ze=ze.then(()=>Promise.allSettled(ke)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"user"),this.resolveAndMergeUserNotifications(Ne,"user")})),Ce){let Ge=xe||ie;ze=ze.then(()=>Promise.allSettled(ye)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"comment"),this.resolveAndMergeUserNotifications(Ne,"comment",Ge)})}return ze})().catch(ze=>{this.loggingService.catch("Error in NotificationService resolveChain: ",ze)})}}}catch(i){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t?.filter((i,a,l)=>a===l.findIndex(s=>s.notificationId===i.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,i,a){try{let l=this.docService.getOrganizationConfig()?.organizationId??"",s=this.docService.getOrganizationMetadata(l);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(l)||{})));let d=this.notificationsByDocumentIdMap$.getValue(),g=d?.[e]?.notifications||[],u=this.docService.getLocationMetadatas(),b=i?.map(M=>{let V=M?.notification;return V?(V.metadata&&(V.metadata.documentName=t?.documentName||V.metadata.documentName,V.metadata.organizationMetadata=s||V.metadata.organizationMetadata,V.metadata.documentMetadata=t||V.metadata.documentMetadata),u&&(V=this.notificationUtilsService.mergeLocationWithNotification({notification:V},u)?.notification),V):null})?.filter(M=>!!M)||[],E=new Map(g.map(M=>[M.id,M]));b.forEach(M=>{E.set(M.id,M)});let A=Array.from(E.values()).sort((M,V)=>(V.timestamp||0)-(M.timestamp||0));this.notificationsByDocumentIdMap$.next(k(f({},d),{[e]:{notifications:A,documentMetadata:t}}))}catch(l){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",l)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(_e(e=>le(e).pipe($e(t=>!!t),ue(t=>{let i=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),l=this.notificationResolverService?.notificationDataProviderAvailable();if(l||i||a){let d=t?.reduce((g,u)=>(g[u.notificationId]=u,g),{});l&&(d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:d||[]})),i&&(d=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:d||[]})),a&&(d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:d||[]})),t=Object.values(d??{})}return t.forEach(d=>{d.notification=this.getClientNotificationObject(d)}),t.sort((d,g)=>g.timestamp-d.timestamp),t.map(d=>d.notification).filter(d=>!!d)}),_e(t=>{let i={data:t?.reduce((a,l)=>(a[l.id]={notification:l},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:i,feature:"allUserNotifications"}).pipe(ue(a=>Object.values(a?.data||{}).map(l=>l?.notification)))}))),_e(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ue(()=>e))}),_e(e=>this.allowedDocumentMetadataMap$.pipe(ue(()=>e))),ue(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let i=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),l=this.docService.getOrganizationMetadata(i);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),l||(l=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(i)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=l||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),le(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),le({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let i,a;try{if(e&&(a=Qn(e)),t&&typeof t=="object"){let l=Oi(t);i=Qn(JSON.stringify(l))}}catch(l){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",l)}return fr(this.afAuth).pipe($e(l=>!!l),_e(l=>this.isFeatureAllowed({firebaseUser:l})),_e(l=>l.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(s=>(l.featureAllowed=s,l))):le(l)),_e(l=>!l.featureAllowed||l?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),le([])):le(l).pipe(_e(s=>this.docService.getDocumentPaths$().pipe(ue(d=>(this.documentPaths=d,s.documentPaths=d,s)))),_e(s=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.NOTIFICATION)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe($e(t=>!!t),_e(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let i=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(i+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=Ur(this.db,`${e?i+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return f8(a).pipe(Jn(l=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",l),le(null))),ue(l=>{let s=[],d=new Map;l?.raw&&(Object.keys(l?.raw||{}).forEach(u=>{let b=l?.raw[u];b?.id&&s.push(b)}),s.forEach(u=>{u.id&&d.set(u.id,u)})),this.notifications$.next(s),this.rawNotificationsByIdMap$.next(d);let g=[];l?.processed&&Object.keys(l?.processed||{}).forEach(u=>{let b=l?.processed[u];b?.id&&g.push(b)}),this.processedNotifications$.next(g),this.setNotificationsByIdMap()}))}else return le(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),i;e?.email&&(i=It(e?.email));let a;e?.userId&&(a=It(e?.userId));let l=new Map;this.processedNotifications$.getValue().forEach(d=>{if(d.id&&d?.displayHeadlineMessageTemplate){let g=!1;(i&&d.notifyUsers?.[i]||a&&d.notifyUsers?.[a])&&(g=!0);let u={id:d.id,notificationSource:d.notificationSource,actionType:d.actionType,actionUser:d.actionUser,timestamp:d.timestamp,targetAnnotationId:d.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(d),displayBodyMessage:this.getNotificationBodyMessage(d),forYou:g,notificationSourceData:d.notificationSourceData},b=this.getRawNotificationById(u.id);if(b?.metadata&&(u.metadata={apiKey:b.metadata.apiKey,organizationId:b.metadata.organizationId,clientOrganizationId:b.metadata.clientOrganizationId,documentId:b.metadata.documentId,clientDocumentId:b.metadata.clientDocumentId,location:b?.location,locationId:b?.locationId}),u?.notificationSource==="comment"&&u?.targetAnnotationId){let E=this.commentService?.getAnnotationById(u.targetAnnotationId);E||b?.annotationData&&(E=b.annotationData),E&&(u.notificationSourceData=this.commentService?.getCommentAnnotationForClient(E))}l.set(d.id,u)}}),l.forEach((d,g)=>{d.isUnread=d?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[g]?.views?.[e?.userSnippylyId],l.set(g,d)}),this.notificationsByIdMap$.next(l)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:i,views:a,notification:l}){try{let s=this.authService.getUser(),d=l||e;if(d.id&&d?.displayHeadlineMessageTemplate&&s){let g=null;s?.email&&(g=It(s?.email));let u=null;s?.userId&&(u=It(s?.userId));let b=!1,E=!0;(g&&d.notifyUsers?.[g]||u&&d.notifyUsersByUserId?.[u])&&(b=!0),u&&a?.[u]&&(E=!1);let A={id:d.id};if(l?A=k(f(f({},A),l),{displayHeadlineMessage:this.getNotificationHeadlineMessage(l),displayBodyMessage:this.getNotificationBodyMessage(l),forYou:b,isUnread:E}):A={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:b,isUnread:E,metadata:i},A?.notificationSource==="comment"&&A?.targetAnnotationId){let M=this.commentService?.getAnnotationById(A.targetAnnotationId);M||l?.notificationSourceData&&(M=l?.notificationSourceData),M||t?.annotationData&&(M=t.annotationData),M&&(A.notificationSourceData=this.commentService?.getCommentAnnotationForClient(M))}return t?.targetAnnotationData?.isCommentResolverUsed&&(A.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),l?.isNotificationResolverUsed&&(A.isNotificationResolverUsed=l.isNotificationResolverUsed),A}return}catch(s){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",s);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ue(e=>e?Object.keys(e??{}).map(t=>{let i=e[t].notifications||[],a=i.filter(s=>s.isUnread).length,l=i.length>0&&i[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:l,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,i)=>i.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ue(e=>{let t=null;return e?(t=[],e.forEach(i=>{i.notifications.forEach(a=>{t?.push(a)})}),t?.sort((i,a)=>a.timestamp-i.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,i=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.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(t?.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(i?this.docService.getOrganizationMetadata(i)||{}:{})),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 l=t?.documentId?new dv({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=l?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=l?.clientOrganizationId||e.actionUser.clientOrganizationId);let s=this.docService.getLocation();s&&(e.location=s?.location,e.locationId=s?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let d=this.commonDbService.getServerTimestamp(),g=this.notificationUtilsService.formatNotification(e,d);return JSON.parse(JSON.stringify(g))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{if(!this.notificationsDb)return;let t=Ur(this.notificationsDb),i=this.processNotificationData(e);s8(t,JSON.parse(JSON.stringify(i)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(_e(t=>t?t.organizationId?this.getAllNotifications$().pipe(_e(i=>this.notificationsForYou$.pipe(ue(a=>{if(i||a){let l=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(i||[]).forEach(s=>{s.id&&l.set(s.id,s)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(s=>{s.id&&!l.has(s.id)&&l.set(s.id,s)}),Array.from(l.values()).sort((s,d)=>(d.timestamp||0)-(s.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ue(i=>Array.from(i.values())),ue(i=>i.sort((a,l)=>l.timestamp-a.timestamp)),Vh()):le(null)),xt(Jt))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let i=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,l=/\{(\w+)\}/g,s=i.replace(l,(d,g)=>(g==="actionUser"||g==="recipientUser")&&a[g]?t?.email&&a[g].email===t?.email||t?.userId&&a[g]?.userId===t?.userId?"You":a[g].name||a[g].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[g]?a[g]:d);return this.domService.sanitizeHtml(s)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(i=>{if(i?.userId){let a=this.usersService.getUserById(i?.userId);t=t?.replaceAll(`{{${i.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${i.userId}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,i=!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(K.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(K.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,t=!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(K.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(K.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 Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(e?.length){for(let s=0;s<e.length;s+=50){let g=e.slice(s,s+50).filter(E=>E?.id),u=g.map(E=>this.setNotificationAsRead({notification:E,userNotifications:JSON.parse(JSON.stringify(t))})),b=yield Promise.all(u);g.forEach((E,A)=>{let M=b[A];if(!M.some(q=>q.notificationId===E.id))t=t.filter(q=>q.notificationId!==E.id);else{let q=t.find(fe=>fe.notificationId===E.id),ae=M.find(fe=>fe.notificationId===E.id);q&&ae?.views&&(q.views=ae.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(s=>{let d=s.metadata?.documentId;if(d&&a?.[d]){let g=a?.[d]?.notifications||[],u=g.find(b=>b.id===s.id);u&&(u.isUnread=!1),a[d].notifications=g}}),this.notificationsByDocumentIdMap$.next(a),!Mr(t,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(t)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return Q(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(ut(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ue(e=>e?.filter(i=>i?.isUnread)?.length??null),_e(e=>this.getNotifications$().pipe(ue(t=>{let i=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:i}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),le({forYou:null,all:null})}}setNotificationAsRead(i){return Q(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let l=It(a?.userId),{metadata:s}=e;if(s){let{apiKey:d,organizationId:g,documentId:u}=s;if(d&&g&&u&&l){let b=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:g,documentId:u,apiKey:d}});b?.notificationId&&(b?.views?.[l]||(b.views||(b.views={}),b.views[l]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:g,documentId:u,apiKey:d},data:b})));let E=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:g}});if(E?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:g}}),t=t.filter(A=>A.notificationId!==e.id);else if(!E?.views?.[l]){E.views||(E.views={}),E.views[l]={timestamp:Date.now()};let A=t.find(M=>M.notificationId===e.id);A&&(A.views=E.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:l,documentId:u,organizationId:g},data:E})}}}}}return t}catch(a){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",a),t}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}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}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",e)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",e)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(e){return Q(this,null,function*(){try{this.getNotifications$().pipe(ut(1)).subscribe(t=>{if(t){let i=t.filter(a=>a.id===e);this.setNotificationsAsRead(i)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",e)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",e)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(i=>{["email","inbox"].includes(i.id)&&(t=!i.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return Q(this,null,function*(){try{let t=this.authService.getUser(),i=It(t?.userId??""),a=this.docService.getDocumentPaths(),l=this.docService.getOrganizationConfig(),s=a?.organizationId??l?.organizationId,d=a?.clientOrganizationId??l?.clientOrganizationId,g={apiKey:this.configService.getApiKey(),organizationId:s,documentId:a?.documentId,clientOrganizationId:d,clientDocumentId:a?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:d??t?.clientOrganizationId??"",user:{userId:t?.userId??""},notificationsConfig:e||this.settingsConfig$.getValue()}):a?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:a?.documentId,userId:i},data:{id:a?.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:g}})))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(lt),X(We),X(Ft),X(Tn),X(rd),X(cv),X(rl),X(mv),X($n),X(ct),X(Be),X(Ln),X(x),X(LL),X(An),X(Do),X(il),X(tr))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lm=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=s,this.domService=d,this.afAuth=g,this.iamService=u,this.dialog=b,this.loggingService=E,this.notificationService=A,this.userPermissionService=M,this.areaAnnotationById$=new Se({}),this.documentPaths=null,this.areaEnabled$=new Se(!0),this.allowedElementIds$=new Se([]),this.addAreaMode$=new Se(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe($e(V=>!!V),ut(1)).subscribe(V=>{V&&this.getDocumentPaths()},V=>{this.loggingService.catch("Error in AreaService getDb subscription: ",V)}),this.domService.onWindowPointerMove$().subscribe(V=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&(this.isElementInsideAllowedElements(q)?wN(V.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,U.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},V=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",V)}),this.domService.onWindowKeyupEsc$().subscribe(V=>{this.addAreaMode$.value&&this.disableAddAreaMode()},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",V)}),this.domService.onDocumentClick$().subscribe(V=>{if(V&&this.addAreaMode$.value){if(V.preventDefault(),V.stopPropagation(),!wN(V.target)){let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&this.isElementInsideAllowedElements(q)&&this.addArea(V)}this.disableAddAreaMode()}},V=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",V)}),this.addAreaMode$.subscribe(V=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),V?this.domService.addClassToElement(document.body,"snippyly-add-area-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-area-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},V=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",V)}),this.domService.onWindowKeyupBackspace$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupBackspace")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",V)}),this.domService.onWindowKeyupDelete$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupDelete")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",V)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in AreaService","color: green;");try{this.areaAnnotationById$.next({}),this.areaEnabled$.next(!0),this.allowedElementIds$.next([]),this.addAreaMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in AreaService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllAreaAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,l;try{if(e&&(l=Qn(e)),t&&typeof t=="object"){let s=Oi(t);a=Qn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",s)}return fr(this.afAuth).pipe($e(s=>!!s),_e(s=>this.isFeatureAllowed({firebaseUser:s,annotations:[],filteredAnnotations:[]})),_e(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(s.featureAllowed=d,s))):le(s)),_e(s=>s.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(s.featureAllowed=!d,s))):le(s)),_e(s=>s.featureAllowed?le(s).pipe(_e(d=>this.docService.getDocumentPaths$().pipe(ue(g=>(this.documentPaths=g,d.documentPaths=g,d)))),_e(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(g=>(d.annotations=g||[],f({},d)))):this.docService.getDocumentIds$().pipe(_e(g=>{let u=g?.length>0?g.map(b=>b.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(b=>(d.annotations=b||[],f({},d))))}))),_e(d=>this.docService.getLocation$().pipe(ue(g=>(d.location=g,d)))),_e(d=>this.docService.getLocations$().pipe(ue(g=>(d.customLocations=g,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let g=[],u=[];return a?g.push(a):(g.push(d?.location?.locationId),g.push(...Object.values(d?.customLocations||[]).map(b=>b.locationId)),d?.location?.location?.id&&u.push(d?.location?.location?.id)),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,g,u),d}}),_e(d=>i?le(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):le(d)),_e(d=>i?le(d):d?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ue(()=>d)):le(d)),ue(d=>(d.filteredAnnotations=d.filteredAnnotations?.map(g=>{let u=Object.assign({},g);return u.areaProperties=this.calculateAreaAnnotationPosition(u),u}),d)),_e(d=>d?.filteredAnnotations?le(d?.filteredAnnotations||[]):le([])),_e(d=>{if(this.authService.isFeatureAllowed(je.COMMENT))return le(d);{let g=d?.filter(u=>!u?.targetAnnotations?.filter(b=>b?.type===je.COMMENT)?.length);return le(g)}})):le([])),xt(Jt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.AREA)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))),xt((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return le([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=le([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=t?.length?t[0]:void 0,s.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[U.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],g=[];for(let u=0;u<(d?.length??0);u+=U.LISTENER_CONTEXT_BATCH_SIZE)g.push(d?.slice(u,u+U.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=pn(g.map(u=>this.commonDbService.dbListener({feature:"allAreas",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Ra(u)))}else{let d=[];for(let g=0;g<(t?.length??0);g+=U.LISTENER_BATCH_SIZE)d.push(t?.slice(g,g+U.LISTENER_BATCH_SIZE)??[]);l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allAreas",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",g),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(g=>Ra(g)))}return l.pipe(ue(({data:d,operation:g})=>{let u=[];return d&&(u=Object.values(d??{}).filter(b=>typeof b=="object")),{data:u,operation:g}}),ue(({data:d,operation:g})=>{if(!t)return{data:d,documentMap:{},operation:g};let u=d.reduce((b,E)=>{let A=E.metadata?.documentId;return A&&(b[A]||(b[A]=[]),b[A].push(E)),b},{});return{data:d,documentMap:u,operation:g}}),ue(({data:d,documentMap:g,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let b=this.areaAnnotationById$.value;u?.ids?.forEach(E=>{delete b?.[E]}),this.areaAnnotationById$.next(b)}}else Object.entries(g??{}).forEach(([b,E])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:b,annotations:E})});return d}))}else return le([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let s=f(f({},this.areaAnnotationById$.value),l);this.areaAnnotationById$.next(s)}}catch(l){this.loggingService.catch("Error in AreaService setAreaAnnotationsByOrganizationIdAndDocumentId:",l)}}getAnnotationById(e){try{return this.areaAnnotationById$.value?.[e]?this.areaAnnotationById$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in AreaService filterAnnotationsByLocations:",a),[]}}calculateAreaAnnotationPosition(e,t=!1){try{if(e.targetElements?.length){let i=e.targetElements[0],a=e.targetElements[1];if(i?.xpath&&a?.xpath||i?.anchor&&a?.anchor){let l=null,s=null;if(i?.anchor){let d=this.domService.resolveAnchorRecord(i.anchor);d?.element&&d?.element instanceof HTMLElement&&!Co(d.element)&&this.domService.isElementVisible(d.element)&&Zr(d.element)&&(l=d.element)}else i?.xpath&&(l=this.domService.getElementFromXPath(i.xpath),l&&Co(l)&&(l=null),this.domService.isXpathWithId(i.xpath)||(!l&&i.cfXpath&&(l=this.domService.getElementFromXPath(i.cfXpath),l&&Co(l)&&(l=null)),!l&&i.fXpath&&(l=this.domService.getElementFromXPath(i.fXpath),l&&Co(l)&&(l=null))));if(a?.anchor){let d=this.domService.resolveAnchorRecord(a.anchor);d?.element&&d?.element instanceof HTMLElement&&!Co(d.element)&&this.domService.isElementVisible(d.element)&&Zr(d.element)&&(s=d.element)}else a?.xpath&&(s=this.domService.getElementFromXPath(a.xpath),s&&Co(s)&&(s=null),this.domService.isXpathWithId(a.xpath)||(!s&&a.cfXpath&&(s=this.domService.getElementFromXPath(a.cfXpath),s&&Co(s)&&(s=null)),!s&&a.fXpath&&(s=this.domService.getElementFromXPath(a.fXpath),s&&Co(s)&&(s=null))));if(l&&s){let d=ZK(l,s);if(d){let g=l,u=s,b=g.getBoundingClientRect(),E=u.getBoundingClientRect(),A=t?b.width:g.offsetWidth||b.width,M=t?b.height:g.offsetHeight||b.height,V=t?E.width:u.offsetWidth||E.width,q=t?E.height:u.offsetHeight||E.height,ae={};A&&M&&(ae={top:M*i.topPercentage/100,left:A*i.leftPercentage/100});let fe={};V&&q&&(fe={top:q*a.topPercentage/100,left:V*a.leftPercentage/100});let ie=!t,Ce=JK(ae.left,ae.top,l,d,ie),xe=JK(fe.left,fe.top,s,d,ie),ke,ye,Oe,Ne,Ue={};Ce.x>xe.x?Ce.y>xe.y?(Ne={x:Ce.x,y:Ce.y},ke={x:xe.x,y:xe.y},Ue.handle1=Ne,Ue.handle2=ke):(ye={x:Ce.x,y:Ce.y},Oe={x:xe.x,y:xe.y},Ue.handle1=ye,Ue.handle2=Oe):Ce.y>xe.y?(Oe={x:Ce.x,y:Ce.y},ye={x:xe.x,y:xe.y},Ue.handle1=Oe,Ue.handle2=ye):(ke={x:Ce.x,y:Ce.y},Ne={x:xe.x,y:xe.y},Ue.handle1=ke,Ue.handle2=Ne);let ze={topLeft:ke||{x:Oe?.x,y:ye?.y},bottomRight:Ne||{x:ye?.x,y:Oe?.y},topRight:ye||{x:Ne?.x,y:ke?.y},bottomLeft:Oe||{x:ke?.x,y:Ne?.y}};return Ue.coordinates=ze,Ue.targetElement=this.domService.getXPath(d),Ue}}}}return}catch(i){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",i);return}}addArea(e,t=[],i,a,l,s){this.loggingService.log("%c[WB] Calling FUNCTION: addArea","color: green;");try{let d=this.authService.getUser();if(d)if(d.isReadOnly||d.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add areas.");else{let g=new mL;a&&(g.annotationId=a),g.from=d,g.color=U.DEFAULT_ANNOTATION_COLOR,g.lastUpdated=this.timestamp,i&&(g.targetAnnotations=[i]),g.props=new td;let u=this.domService.getCurrentWindowSizeValue();if(g.props.screenWidth=u.screenWidth,g.props.screenHeight=u.screenHeight,g.props.screenScrollHeight=u.screenScrollHeight,g.props.viewportWidth=window.innerWidth,g.props.viewportHeight=window.innerHeight,e||t?.length>0){let A=e?this.getPointsForAreaPinAnnotation(e):t;g.targetElements=[],A.forEach(M=>{g.targetElements.push(this.domService.getTargetElementForCursorPosition(e,void 0,void 0,void 0,void 0,!0,{clientX:M.x,clientY:M.y}))})}this.setLocationToAreaAnnotation(g),l&&(g.locationId=l.locationId,g.location=l.location),g.pageInfo=to(),g.pageInfo&&(g.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let b=this.getElementForAreaAnnotation(g),E=this.docService.getBaseMetadata("area",{element:b});if(g?.metadata||(g.metadata={}),g.metadata=f(f({},g.metadata),E),s?.access&&s?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:d.userId,accessFields:s.accessFields})){this.loggingService.catch("User does not have context access to add area annotation.",void 0,void 0,!0);return}g.context={access:s.access,accessFields:s.accessFields}}return this.saveAreaToDb(g),g}return}catch(d){this.loggingService.catch("Error in AreaService addArea: ",d);return}}setLocationToAreaAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,i,a;if(e.targetElements?.length){if(e.targetElements[0]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[0].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Zr(l.element)&&(i=l.element)}else e.targetElements[0]?.xpath&&(i=this.domService.getElementFromXPath(e.targetElements[0].xpath));if(e.targetElements[1]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[1].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Zr(l.element)&&(a=l.element)}else e.targetElements[1]?.xpath&&(a=this.domService.getElementFromXPath(e.targetElements[1].xpath))}return i&&a&&(t=ZK(i,a)),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)&&pn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe($e(([t,i])=>!!t&&!!i),ut(1),_e(([t,i])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("area");a.metadata=f(f({},a?.metadata),d)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(K.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:l,organizationId:s}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))})}else return le(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,i){try{i&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,_N.UPDATED),this.updateAreaToDb(e)}catch(a){this.loggingService.catch("Error in AreaService updateArea: ",a)}}updateAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateAreaToDb","color: green;");try{if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("area");t.metadata=f(f({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(l=>Q(this,null,function*(){let s=t[l];s.type==="area"&&i&&s.from&&(i?.isAdmin||s.from.userId===i.userId)&&a.push(s)})),a?.length&&(this.analyticsService.trackEvent(K.Events.Area.AREA_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(xl,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(s=>Q(this,null,function*(){yield this.deleteAreaPinAnnotation(s)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i??{})}catch(i){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",i),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),l;t?l=a.find(s=>s?.annotationId===t):l=a.find(s=>s?.targetAnnotations?.find(d=>d?.annotationId===e)),l&&(l.targetAnnotations=l.targetAnnotations?.filter(s=>s?.annotationId!==e),l.targetAnnotations?.length?this.updateAreaToDb(l):this.deleteAreaPinAnnotation(l))}}catch(i){this.loggingService.catch("Error in AreaService onDeleteTargetAnnotation: ",i)}}deleteAreaPinAnnotation(e){if(this.authService.isFeatureAllowed(je.AREA)&&this.documentPaths?.area&&e?.annotationId){this.updateNotificationsDatabase(e,_N.DELETED),this.analyticsService.trackEvent(K.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:i}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,organizationId:i}})}else return Promise.resolve()}enableArea(){try{this.areaEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in AreaService enableArea: ",e)}}disableArea(){try{this.areaEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in AreaService disableArea: ",e)}}getAreaEnabled$(){try{return this.areaEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled$: ",e),le(!1)}}getAreaEnabled(){try{return this.areaEnabled$.value}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled: ",e),!1}}enableAddAreaMode(){this.authService.isFeatureAllowed(je.AREA)?(this.analyticsService.trackEvent(K.Events.Area.AREA_ADD_MODE_ENABLED),this.addAreaMode$.next(!0)):this.loggingService.catch("Error in AreaService enableAddAreaMode: ","Area feature is not enabled.")}disableAddAreaMode(){this.analyticsService.trackEvent(K.Events.Area.AREA_ADD_MODE_DISABLED),this.addAreaMode$.next(!1)}addAreaModeChange(){return this.addAreaMode$.asObservable()}getPointsForAreaPinAnnotation(e){let t=[],i=e,a=i?.touches?.length?i.touches[0]?.clientX:i.clientX,l=i?.touches?.length?i.touches[0]?.clientY:i.clientY;return t.push({x:a,y:l}),t.push({x:a+100,y:l+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"area"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in AreaService updateNotificationsDatabase: ",i)}}getAreaUrl(e){try{return e?.pageInfo?.areaUrl?e.pageInfo.areaUrl:(e?.pageInfo||(e.pageInfo=to(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(U.URL_PARAMS.TAG_ID),t.searchParams.append(U.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return Q(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield Hu(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(Ft),X(ct),X($n),X(Tn),X(We),X(Be),X(eo),X(Ln),X(Fo),X(x),X(xn),X(il))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var U_e=n=>{try{let o={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return g3.sanitize(n,o)}catch(o){return at.catch("Error in File utils sanitizeSvg: ",o),""}},V_e=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){at.catch("Error in File utils getFileName: ",o);return}},xQ=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){at.catch("Error in File utils getFileExtension: ",o);return}},B_e=(n,o)=>{try{let r=n.slice(0,-1,n.type);return new File([r],o+"."+xQ(n),{type:n.type})}catch(r){at.catch("Error in File utils updateFile: ",r);return}};var kQ={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 yp=(()=>{let o=class o{constructor(e,t,i,a,l){this.authService=e,this.configService=t,this.coreActionsService=i,this.loggingService=a,this.attachmentResolverService=l,this.storage=hw();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{if(s&&s.firebaseOptions?.storageBucket){this.storage=hw(void 0,s?.firebaseOptions?.storageBucket);let d=this.configService.getProxyConfig();d?.storageHost&&(this.storage.host=d.storageHost)}},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:t}){try{let i=new Zb;i.name=t.name;let a=B_e(t,`${i.attachmentId}_${V_e(t)}`),l=`${this.apiKey}/${e}/${a?.name}`;return i.bucketPath=l,i.size=t.size,i.type=xQ(t),i?.type&&(i.mimeType=kQ[i?.type]),i}catch(i){return this.loggingService.catch("Error in StorageService createAttachment: ",i),null}}sanitizeSvgFile(e){return Q(this,null,function*(){if(e.type===kQ.svg)try{let t=yield e.text(),i=U_e(t);return new File([i],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return Q(this,arguments,function*({attachment:e,file:t,resolve:i,reject:a}){try{let s=fw(this.storage,e.bucketPath),d=kY(s,t,{cacheControl:"public,max-age=3600"});d.on("state_changed",g=>{let u=g.bytesTransferred/g.totalBytes*100},g=>{a(g)},()=>{xY(d.snapshot.ref).then(g=>{e.url=g,i(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}})}uploadToResolver(d){return Q(this,arguments,function*({file:e,attachment:t,metadata:i,resolve:a,reject:l,scope:s}){try{i.attachmentId=t.attachmentId;let g={attachmentId:t.attachmentId,name:t.name,file:e,metadata:i,mimeType:t.mimeType},u=ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:kc.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:g,eventType:Io.ATTACHMENT_ADD}});let b=yield this.attachmentResolverService.saveAttachment({attachment:g,eventType:Io.ATTACHMENT_ADD},u,s);b&&b.data?.url?(t.url=b.data?.url,a(t)):l(new Error("Failed to upload attachment to resolver"))}catch(g){this.loggingService.catch("Error in StorageService uploadToResolver: ",g),l(g)}})}uploadFile({path:e,file:t,useAttachmentResolver:i,metadata:a,attachmentScope:l}){return new Promise((s,d)=>Q(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let g=yield this.sanitizeSvgFile(t),u=this.createAttachment({path:e,file:g});if(!u)throw new Error("Attachment not created");i?this.uploadToResolver({file:g,attachment:u,metadata:a,resolve:s,reject:d,scope:l}):this.uploadAttachmentToStorage({attachment:u,file:g,resolve:s,reject:d})}catch(g){this.loggingService.catch("Error in StorageService uploadFile:",g),d(g)}}))}uploadChunk(e,t,i,a){return new Promise((l,s)=>{try{if(a?.useAttachmentResolver){let d=this.createAttachment({path:e,file:t});if(!d){s(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:d,metadata:a.metadata,resolve:g=>l(g.url),reject:s,scope:a.attachmentScope});return}if(this.apiKey){let d=`${this.apiKey}/${e}/${t.name}`,g=fw(this.storage,d),u=kY(g,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",b=>{let E=b.bytesTransferred/b.totalBytes*100},b=>{s(b)},()=>{xY(u.snapshot.ref).then(b=>{l(b)}).catch(b=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${i}:`,b),s(b)})})}else{let d=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",d),s(d)}}catch(d){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${i}: `,d),s(d)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let i=t.response,a=document.createElement("a"),l=window.URL.createObjectURL(i);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=l,e?.name&&(a.download=e?.name),document.body.appendChild(a);let s=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(s),window.URL.revokeObjectURL(l),a.remove()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:i,attachmentScope:a}){return new Promise((l,s)=>{if(i){let d=ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},d,a).then(()=>{l(null)}).catch(g=>{s(g)})}else{let d=fw(this.storage,e.bucketPath);yY(d).then(()=>{l(null)}).catch(g=>{l(null)})}})}deleteFileFromPath(e){return new Promise((t,i)=>{let a=fw(this.storage,e);yY(a).then(()=>{t(null)}).catch(l=>{i(l)})})}};o.\u0275fac=function(t){return new(t||o)(X(We),X(Ft),X(tr),X(x),X(Gs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var go=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new Se(U.CommentAnnotationStatusMap),this._customPriorityMap=new Se(U.CommentAnnotationPriorityMap),this._customCategoryMap=new Se(U.CommentCategoryMap);try{let t=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);i&&this._customStatusMap.next(JSON.parse(i));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}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 t={};e.forEach(i=>{t[i.id]=i,i.type||(i.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}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 t={};e.forEach(i=>{t[i.id]=i}),this._customPriorityMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(i=>{t[i.id]=i}),this._customCategoryMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([i,a])=>a.type==="ongoing");if(t)return t.map(i=>i[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 t=Object.entries(this._customStatusMap.value),i=t.find(([a,l])=>l.type==="default");switch(e.status){case"open":i&&(e.status=i[1]);break;case"inProgress":let a=t.find(([s,d])=>d.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let l=t.find(([s,d])=>d.type==="terminal");l&&(e.status=l[1]);break;default:i&&(e.status=i[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}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(t=>U.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var j_e=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new it;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(Vh()),this.domService.onWindowKeydown$().subscribe(i=>{this.keyEventSubject$.next(i)})}catch(i){this.loggingService.catch("Error in HotkeyService constructor: ",i)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe($e(i=>i?.key===e),$e(i=>!(!!t?.includeCtrl!==i.ctrlKey||!!t?.includeAlt!==i.altKey||!!t?.includeShift!==i.shiftKey||!!t?.includeMeta!==i.metaKey)),$e(()=>this.isNoInputFocused()))}catch(i){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",i),new Gt}}isNoInputFocused(){try{let e=document.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e?.parentElement}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(Be),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function HWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",17)(2,"path",18)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function GWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",22)(2,"path",23)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function zWe(n,o){if(n&1&&(C(0),h(1,"div",6)(2,"div",7),p(3,HWe,6,0,"svg",8)(4,GWe,6,0,"ng-template",null,1,Ve),S(),h(6,"div",9),ne(7),R(8,"translate"),D(9,"br"),ne(10),R(11,"translate"),S(),h(12,"div",10)(13,"p"),ne(14),R(15,"translate"),de(),h(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),ne(21),R(22,"translate"),S(),St(),h(23,"p"),ne(24),R(25,"translate"),S()()(),_()),n&2){let r=Ie(5),e=c();m(3),v("ngIf",e.darkMode)("ngIfElse",r),m(4),Ee(" ",N(8,7,"Allow mic permission to")),m(3),Ee("",N(11,9,"enable your audio")," "),m(4),Ee(" ",N(15,11,"1. Click the")," "),m(7),Ee(" ",N(22,13,"page info icon in your browser\u2019s address bar")," "),m(3),Ee(" ",N(25,15,"2. Turn on Microphone")," ")}}function WWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",17)(2,"path",24)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function qWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",22)(2,"path",25)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function YWe(n,o){if(n&1&&(C(0),h(1,"div",6)(2,"div",7),p(3,WWe,6,0,"svg",8)(4,qWe,6,0,"ng-template",null,2,Ve),S(),h(6,"div",9),ne(7),R(8,"translate"),D(9,"br"),ne(10),R(11,"translate"),S(),h(12,"div",10)(13,"p"),ne(14),R(15,"translate"),de(),h(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),ne(21),R(22,"translate"),S(),St(),h(23,"p"),ne(24),R(25,"translate"),S()()(),_()),n&2){let r=Ie(5),e=c();m(3),v("ngIf",e.darkMode)("ngIfElse",r),m(4),Ee(" ",N(8,7,"Allow camera permission")),m(3),Ee("",N(11,9,"to enable your video")," "),m(4),Ee(" ",N(15,11,"1. Click the")," "),m(7),Ee(" ",N(22,13,"page info icon in your browser\u2019s address bar")," "),m(3),Ee(" ",N(25,15,"2. Turn on Camera")," ")}}var jL=(()=>{let o=class o{constructor(e,t,i,a,l){this.loggingService=e,this.themeService=t,this.elementRef=i,this.matDialogRef=a,this.data=l,this.veltElement=!0,this.darkMode=!0;try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionDeniedDialogComponent","color: blue;"),this.type=this.data?.type,[!0,!1].includes(this.data?.darkMode)&&(this.darkMode=this.data?.darkMode)}catch(s){this.loggingService.catch("Error in DevicePermissionDeniedDialogComponent constructor: ",s)}}ngOnDestroy(){}};o.\u0275fac=function(t){return new(t||o)(y(x),y(_t),y(Z),y(Vi,8),y(Yc,8))},o.\u0275cmp=O({type:o,selectors:[["velt-device-permission-denied-dialog-internal"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{type:"type"},standalone:!1,decls:5,vars:5,consts:[["devicePermissionDialogRef",""],["defaultAudioIcon",""],["defaultVideoIcon",""],[1,"velt-device-permission-denied-dialog--container",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"ngSwitch"],[4,"ngSwitchCase"],[1,"velt-device-permission-denied-dialog"],[1,"velt-device-permission-denied-dialog--icon"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg",4,"ngIf","ngIfElse"],[1,"velt-device-permission-denied-dialog--header"],[1,"velt-device-permission-denied-dialog--content"],["width","13","height","12","viewBox","0 0 13 12","fill","none","xmlns","http://www.w3.org/2000/svg",1,"velt-device-permission-denied-dialog--page-info-icon"],["d","M4.375 2.5C4.375 3.53553 3.53553 4.375 2.5 4.375C1.46447 4.375 0.625 3.53553 0.625 2.5C0.625 1.46447 1.46447 0.625 2.5 0.625C3.53553 0.625 4.375 1.46447 4.375 2.5Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M5 2.5H12.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M0 8.75H7.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M11.875 8.75C11.875 9.78553 11.0355 10.625 10 10.625C8.96447 10.625 8.125 9.78553 8.125 8.75C8.125 7.71447 8.96447 6.875 10 6.875C11.0355 6.875 11.875 7.71447 11.875 8.75Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg"],["x","0.5","y","4","width","56","height","56","rx","28","fill","white","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M13.5 17L43.5 47","stroke","currentColor","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","36.5","width","24","height","24","rx","12","fill","currentColor"],["d","M48.5 18.99V19M48.5 14V5","stroke","white","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","0.5","y","4","width","56","height","56","rx","28","fill","black","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","black","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","currentColor","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"]],template:function(t,i){if(t&1&&(h(0,"div",3,0),C(2,4),p(3,zWe,26,17,"ng-container",5)(4,YWe,26,17,"ng-container",5),_(),S()),t&2){let a=Ie(1);v("snippylyOverlay",a)("snippylyOverlayZIndex",3e3),m(2),v("ngSwitch",i.type),m(),v("ngSwitchCase","audio"),m(),v("ngSwitchCase","video")}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.velt-device-permission-denied-dialog--panel mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{padding:0;background-color:transparent;box-shadow:none;overflow:unset}.velt-device-permission-denied-dialog[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:var(--velt-spacing-lg);align-items:center;justify-content:center;padding:4rem;box-sizing:border-box;word-break:break-word;max-width:600px;max-height:400px;text-align:center;background-color:var(--velt-background-0);border-radius:var(--velt-border-radius-2xl);box-shadow:0 calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((-3rem + 0px) * var(--velt-base-rem-unit)) #1f2f461f}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--icon[_ngcontent-%COMP%]{color:var(--velt-error)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--header[_ngcontent-%COMP%]{font-size:var(--velt-font-size-lg);font-weight:600;line-height:36px;letter-spacing:-.02em;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%]{font-size:var(--velt-font-size-sm);font-weight:400;line-height:21px;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--page-info-icon[_ngcontent-%COMP%]{margin-left:var(--velt-spacing-sm);margin-right:var(--velt-spacing-sm);color:var(--velt-error)}"],changeDetection:0});let n=o;return n})();var gv=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.matDialog=t,this.audioPermissionState$=new Se(null),this.videoPermissionState$=new Se(null);try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionService","color: blue;"),this.checkPermissions()}catch(i){this.loggingService.catch("Error in DevicePermissionService constructor: ",i)}}checkPermissions(){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: checkPermissions","color: green;"),new ur().browserName!=="Firefox"&&(navigator.permissions.query({name:"microphone"}).then(t=>{this.audioPermissionState$.next(t.state),t.onchange=()=>{this.audioPermissionState$.next(t.state)}}).catch(t=>{}),navigator.permissions.query({name:"camera"}).then(t=>{this.videoPermissionState$.next(t.state),t.onchange=()=>{this.videoPermissionState$.next(t.state)}}).catch(t=>{}))}catch(e){this.loggingService.catch("Error in DevicePermissionService checkPermissions: ",e)}}getPermissionState$(e){try{switch(this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: getPermissionState$","color: green;"),e){case"audio":return this.getAudioPermissionState$();case"video":return this.getVideoPermissionState$();default:return le(null)}}catch(t){return this.loggingService.catch("Error in DevicePermissionService getPermissionState$: ",t),le(null)}}getAudioPermissionState$(){return this.audioPermissionState$.asObservable()}getVideoPermissionState$(){return this.videoPermissionState$.asObservable()}openDevicePermissionDeniedDialog(e,t){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: openDevicePermissionDeniedDialog","color: green;"),this.matDialog.open(jL,{panelClass:["velt-device-permission-denied-dialog--panel","velt-mat-dialog-container"],backdropClass:["velt-device-permission-denied-dialog--backdrop","s-background-blur-1"],data:f({type:e},t||{})})}catch(i){this.loggingService.catch("Error in DevicePermissionService openDevicePermissionDeniedDialog: ",i)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(Fo))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var KWe=()=>["video","screen"];function ZWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-video",4),n&2){let r=c(2);v("componentConfigSignal",r.componentConfigSignal)}}function JWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-audio",4),n&2){let r=c(2);v("componentConfigSignal",r.componentConfigSignal)}}function XWe(n,o){if(n&1&&(C(0),h(1,"div",2,0),p(3,ZWe,1,1,"app-recording-preview-steps-dialog-video",3)(4,JWe,1,1,"app-recording-preview-steps-dialog-audio",3),S(),_()),n&2){let r=o.ngIf,e=Ie(2),t=c();m(),v("snippylyOverlay",e)("snippylyOverlayZIndex",2e3),T("aria-label","Recording preview - "+r.type+" mode")("data-testid",t.componentId),m(2),v("ngIf",Et(6,KWe).includes(r.type)),m(),v("ngIf",r.type==="audio")}}var $L=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.loggingService=e,this.recorderService=t,this.dialog=i,this.devicePermissionService=a,this.dialogRef=l,this.elementRef=s,this.data=d,this.darkMode=!1,this.shadowDom=!0,this.startCountdownFrom=3,this.defaultMediaSourceOptions=Qd(),this.recordingCountdownEnabled=!1,this.subscriptions=[],this.veltElement=!0,this.componentId="velt-recording-preview-steps-dialog",this.componentConfigSignal=Ae({closeDialog:this.closeDialog.bind(this),startCountdown:this.startCountdown.bind(this),toggleAudio:this.toggleAudio.bind(this),toggleVideo:this.toggleVideo.bind(this),toggleSettings:this.toggleSettings.bind(this),cancelCountdown:this.cancelCountdown.bind(this),updateMediaConfig:this.updateMediaConfig.bind(this),handleOverlayClick:this.handleOverlayClick.bind(this),countdownStarted:!1,mediaConfig:{audio:{enabled:!1},video:{enabled:!1}},mediaState:{audio:{enabled:!1},video:{enabled:!1}},type:"video",countdown:this.startCountdownFrom,mediaStream:void 0,isSettingsOpen:!1,darkMode:this.darkMode,shadowDom:this.shadowDom,isExplicitShadowDom:!1});try{this.devicePermissionService.getPermissionState$("video").subscribe(g=>{this.componentConfigSignal.update(u=>(u=k(f({},u),{mediaState:k(f({},u.mediaState),{video:{enabled:g!=="denied"}})}),u))}),this.devicePermissionService.getPermissionState$("audio").subscribe(g=>{this.componentConfigSignal.update(u=>(u=k(f({},u),{mediaState:k(f({},u.mediaState),{audio:{enabled:g!=="denied"}})}),u))}),this.subscriptions.push(this.recorderService.getRecordingCountdownEnabled$().subscribe(g=>{this.recordingCountdownEnabled=g})),this.subscriptions.push(this.recorderService.getRecordingMicEnabled$().subscribe(g=>{g!==null&&(g?this.toggleAudioOn():this.toggleAudioOff())})),d&&(d.type&&this.componentConfigSignal.update(g=>(g=k(f({},g),{type:d.type}),g)),d.recordingCountdown!==void 0&&(this.recordingCountdownEnabled=!!d.recordingCountdown),d.mediaConfig&&(d.mediaConfig?.audio?.enabled&&!d.mediaConfig?.audio?.deviceId&&(d.mediaConfig.audio.deviceId=this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId),d.mediaConfig?.video?.enabled&&!d.mediaConfig?.video?.deviceId&&(d.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId),d?.darkMode?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark"),this.componentConfigSignal.update(g=>(g=k(f({},g),{shadowDom:d?.shadowDom!==!1,isExplicitShadowDom:!!d?.isExplicitShadowDom,darkMode:d.darkMode||!1}),g)),this.updateMediaConfig(d.mediaConfig)))}catch(g){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent constructor: ",g)}}ngOnInit(){try{this.setupA11yAttributes(),this.componentConfigSignal().type==="screen"&&this.subscriptions.push(this.recorderService.getScreenStream$().subscribe(e=>{e&&e.active&&e.getVideoTracks().some(t=>t.readyState==="live")&&this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig.screen={enabled:!0,stream:e},t))}))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnInit:",e)}}setupA11yAttributes(){try{let e=this.elementRef.nativeElement;e.setAttribute("data-testid",this.componentId+"-container"),e.setAttribute("role","dialog"),e.setAttribute("aria-label","Recording preview steps dialog")}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent setupA11yAttributes:",e)}}ngOnChanges(e){try{e&&Object.keys(e).forEach(t=>{this.componentConfigSignal.update(i=>(i=k(f({},i),{[t]:e[t].currentValue}),i))})}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.dialogRef.addPanelClass("snippyly-recording-preview-steps-dialog"),this.dialogRef.disableClose=!0}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngAfterViewInit: ",e)}}toggleSettings(e){try{e.stopPropagation(),this.componentConfigSignal.update(t=>(t=k(f({},t),{isSettingsOpen:!t.isSettingsOpen}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleSettings: ",t)}}toggleAudio(){try{this.componentConfigSignal().mediaConfig.audio||this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:{enabled:!0}})}),i));let e=!this.componentConfigSignal().mediaConfig.audio?.enabled;this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:{enabled:e}})}),i));let t=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];t?t.enabled=e:e&&(this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:k(f({},i.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),i)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudio: ",e)}}toggleAudioOn(){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:{enabled:!0}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e?e.enabled=!0:(this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:k(f({},t.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),t)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleAudioOff(){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:{enabled:!1}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e&&(e.enabled=!1)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleVideo(){try{this.componentConfigSignal.update(e=>(e=f({},e),e.mediaConfig.video||(e.mediaConfig.video={enabled:!0}),e.mediaConfig.video.enabled=!e.mediaConfig.video.enabled,e.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId,e)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleVideo: ",e)}}updateMediaConfig(e){try{this.stopMediaStream(),this.getMediaStream(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent updateMediaConfig: ",t)}}getMediaStream(e){try{if(!navigator.mediaDevices){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No media devices");return}if(!navigator.mediaDevices.getUserMedia){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No getUserMedia");return}if(e.audio?.enabled||e.video?.enabled){let t=$_e(e);navigator.mediaDevices.getUserMedia(t).then(i=>{this.componentConfigSignal.update(a=>(a=k(f({},a),{mediaConfig:e,mediaStream:i}),a))}).catch(i=>{this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream catch: ",i)})}else this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaStream:void 0,mediaConfig:e}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ",t)}}stopMediaStream(){try{this.componentConfigSignal.update(e=>(e=f({},e),e.mediaStream?.getTracks().forEach(t=>{t.stop()}),e.mediaStream=void 0,e))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent stopMediaStream: ",e)}}startCountdown(){return Q(this,null,function*(){try{let t=new ur().getBrowserName()==="Firefox",i=null;if(t&&this.componentConfigSignal().type==="screen")try{let a=this.componentConfigSignal().mediaConfig,l=$_e(a);Object.keys(l).length>0&&(i=yield navigator.mediaDevices.getUserMedia(l))}catch(a){this.loggingService.catch("Error getting Firefox user media stream:",a),i=null}if(this.componentConfigSignal().type==="screen"){if(!this.componentConfigSignal().mediaConfig.screen?.stream)try{let l=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});this.componentConfigSignal.update(s=>(s=f({},s),s.mediaConfig.screen={enabled:!0,stream:l},s))}catch(l){this.loggingService.catch("Error getting screen media stream:",l),this.cancelCountdown();return}this.componentConfigSignal.update(l=>(l=f({},l),i&&(l.mediaConfig.audio?.enabled&&(l.mediaConfig.audio.stream=i),l.mediaConfig.video?.enabled&&(l.mediaConfig.video.stream=i)),l)),this.componentConfigSignal().mediaConfig.screen?.stream?.getTracks().forEach(l=>{l&&(l.onended=()=>{this.cancelCountdown()})})}this.recordingCountdownEnabled?(this.componentConfigSignal.update(a=>(a=k(f({},a),{countdownStarted:!0}),a)),this.countdownInterval=setInterval(()=>{this.componentConfigSignal().countdown>1?this.componentConfigSignal.update(a=>(a=k(f({},a),{countdown:a.countdown-1}),a)):this.closeDialog(this.componentConfigSignal().mediaConfig)},1e3)):this.closeDialog(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent startCountdown: ",e)}})}cancelCountdown(){try{if(this.componentConfigSignal.update(e=>(e=k(f({},e),{countdownStarted:!1,countdown:this.startCountdownFrom}),e)),this.clearInterval(),this.componentConfigSignal().type==="screen"){let e=this.componentConfigSignal().mediaConfig.screen?.stream;e&&e.getTracks().forEach(t=>{t.stop()}),this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig.screen=void 0,t))}}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent cancelCountdown: ",e)}}closeDialog(e){return Q(this,null,function*(){try{this.clearInterval(),e||(this.stopMediaStream(),this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig&&(t.mediaConfig.screen?.stream&&(t.mediaConfig.screen.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.screen.stream=void 0),t.mediaConfig.audio?.stream&&(t.mediaConfig.audio.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.audio.stream=void 0),t.mediaConfig.video?.stream&&(t.mediaConfig.video.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.video.stream=void 0)),t))),this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent closeDialog: ",t)}})}handleOverlayClick(e){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{isSettingsOpen:!1}),t)),e.stopPropagation()}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent handleOverlayClick: ",t)}}clearInterval(){try{this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=void 0)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent clearInterval: ",e)}}ngOnDestroy(){try{this.clearInterval(),this.stopMediaStream(),this.subscriptions.forEach(e=>{e?.unsubscribe()})}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(y(x),y(Fn),y(Fo),y(gv),y(Vi),y(Z),y(Yc,8))},o.\u0275cmp=O({type:o,selectors:[["snippyly-recording-preview-steps-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{darkMode:"darkMode",shadowDom:"shadowDom"},standalone:!1,features:[st],decls:1,vars:1,consts:[["recordingPreviewDialogRef",""],[4,"ngIf"],["role","dialog","aria-modal","true",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"componentConfigSignal",4,"ngIf"],[3,"componentConfigSignal"]],template:function(t,i){t&1&&p(0,XWe,5,7,"ng-container",1),t&2&&v("ngIf",i.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog{max-width:none} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{background:transparent;padding:0;margin:0;border-radius:var(--velt-border-radius-lg)}"],changeDetection:0});let n=o;return n})();function $_e(n){try{let o={};return n.audio?.enabled&&(o.audio={deviceId:n.audio.deviceId?{exact:n.audio.deviceId}:void 0}),n.video?.enabled&&(o.video={deviceId:n.video.deviceId?{exact:n.video.deviceId}:void 0}),o}catch{return{}}}var Kl=(()=>{let o=class o{constructor(e){this.loggingService=e,this.isPipActive$=new Se(!1),this.pipStopRecordingTriggered$=new Se(!1),this.pipPauseRecordingTriggered$=new Se(!1),this.pictureInPicture$=new Se(!1),this.pipClearRecordingTriggered$=new Se(!1)}getPipClearRecordingTriggered$(){return this.pipClearRecordingTriggered$.asObservable()}resetPipClearRecordingTriggered(){this.pipClearRecordingTriggered$.next(!1)}openPictureInPicture(e,t){return Q(this,null,function*(){try{if(!this.isPictureInPictureEnabled()||!e||document.pictureInPictureElement||window.documentPictureInPicture?.window)return;if("documentPictureInPicture"in window){yield this.createDocumentPip(e,t);return}if(document.pictureInPictureEnabled){let i=yield this.findVideoElement();if(!i){this.loggingService.warn("No video element found for Picture-in-Picture");return}yield i.requestPictureInPicture(),this.isPipActive$.next(!0);return}}catch(i){this.loggingService.catch("Error in PipService openPictureInPicture:",i)}})}createDocumentPip(e,t){return Q(this,null,function*(){try{let i=window.documentPictureInPicture;this.pipWindow=yield i.requestWindow({width:320,height:288}),yield this.addStylesToPip(),yield this.createControlPanelInPip(e,t),this.pipWindow?.addEventListener("unload",()=>{try{this.isPipActive$.next(!1),this.pipWindow=void 0}catch(a){this.loggingService.catch("Error in PipService createDocumentPip unload:",a)}}),this.isPipActive$.next(!0)}catch{this.isPipActive$.next(!1),this.pipWindow=void 0}})}addStylesToPip(){return Q(this,null,function*(){try{if(!this.pipWindow)return;this.pipWindow.document.body.style.margin="0",this.pipWindow.document.body.style.padding="0",this.pipWindow.document.body.style.backgroundColor="#000",this.pipWindow.document.body.style.display="flex",this.pipWindow.document.body.style.alignItems="center",this.pipWindow.document.body.style.justifyContent="center"}catch(e){this.loggingService.catch("Error in PipService copyStylesToPip:",e)}})}createControlPanelInPip(e,t){return Q(this,null,function*(){if(this.pipWindow)try{let i=this.pipWindow.document.createElement("div");i.style.cssText=`
408
+ `},o.GIF_PATHS={CAT_JAM:"https://firebasestorage.googleapis.com/v0/b/snippyly-sdk-external/o/emojis%2Fcatjam.gif?alt=media&token=9868b4ec-0031-4751-bb2e-47bf0f9d9583"},o.\u0275fac=function(t){return new(t||o)(X(Be),X(x),X(Rd))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u){this.analyticsService=e,this.authService=t,this.configService=i,this.coreActionsService=a,this.databaseService=l,this.docService=s,this.loggingService=d,this.commonDbService=g,this.usersService=u,this.db=null,this.internalUserContacts$=new Se([]),this.userGlobalContact$=new Se(!1),this.userGroupContact$=new Se(null),this.users$=new Se([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new Se({}),this.userOrganizationContacts$=new Se([]),this.userFolderContacts$=new Se([]),this.userDocumentContacts$=new Se([]),this.userOrganizationGroups$=new Se([]),this.onContactSelectedSubject$=new it,this.documentAccessType=null,this.atHereEnabled$=new Se(!1),this.atHereLabel$=new Se("here"),this.atHereDescription$=new Se(null),this.contactListScopeForOrganizationUsers$=new Se([fo.ALL]),this.customUserContacts$=new Se(null),this.customUserContactsConfig$=new Se({merge:!1}),this.currentOrganizationUserIAM$=new Se(null),this.userContacts$=new Se([]),this.userSnippylyIdContacts$=new Se(null),this.usersByOrganizationId$=new Se({}),this.temporaryUserIds$=new Se([]),this.usersByOrganizationIdAndDocumentId$=new Se({}),this.usersByOrganizationIdAndFolderId$=new Se({}),this.userById$=new Se({}),this.searchUsersSubject$=new it,this.searchUsersDebounceTime=300,this.pendingSearchPromises=new Map,this.authService.setContactService(this),this.usersService.setContactService(this),this.authService.getUser$().pipe(_e(b=>this.docService.getDocumentPaths$().pipe(on(E=>{this.documentPaths=E}),ue(()=>b)))).subscribe(b=>Q(this,null,function*(){if(this.user=b,b&&this.documentPaths)if(!b?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(b),this.setLoggedInUser(b),yield this.moveGlobalContactUserFromEmailToUserIdPath(b),this.updateUserInGlobalContactsIfAvailable(b),b?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(b?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let E=this.userPermissionService?.getCurrentUserPermissions(),A=this.documentPaths.folderId,M=!0;A&&E?.[b?.userId]?.folders?.[A]?.errorCode===_o.PERMISSION_DENIED&&(M=!1),this.getOrganizationContactsFromDb$(),M&&this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()}else this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0}),b=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",b)}),this.databaseService.getDb().pipe($e(b=>!!b),ut(1)).subscribe(b=>{b&&(this.db=b)},b=>{this.loggingService.catch("Error in ContactService constructor getDb: ",b)}),this.getOrganizationGroups$().subscribe(b=>{this.authService.setOrganizationUserGroups(b)}),pn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([b,E,A])=>{E?A?.merge?this.userContacts$.next([...b||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(b||[])}),this.getUserContacts$().subscribe(b=>{try{b?.forEach(E=>{let A=E?.userSnippylyId||Qc(this.configService.getApiKey(),E.userId);A&&this.userSnippylyIdContacts$.next(k(f({},this.userSnippylyIdContacts$.value),{[A]:E}))})}catch{}})}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in ContactService setCommentService: ",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in ContactService setUserPermissionService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.temporaryUserIds$.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=[],this.currentOrganizationUserIAM$.next(null)}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(k(f({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;if(i){if(i?.contacts){let a={};Object.keys(i?.contacts??{})?.forEach(l=>{let s=i.contacts[l];if(s?.userId){let d=It(s?.userId);a[d]=s}}),i.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}getUserAccessFields(){return JSON.parse(JSON.stringify(this.userAccessFields$.value))}getUserAccessFieldsByUserId(e){return this.getUserAccessFields()?.[e]}setUserAccessFields(e){try{let t=this.getUserAccessFields();e.forEach(a=>{t[a.user.userId]=a.accessFields||[]});let i=this.authService.getUser()?.userId;if(i&&t?.[i]?.length){let a=this.userPermissionService?.getCurrentUserPermissions();a&&(a[i]||(a[i]={}),a[i].context={accessFields:t[i]},this.userPermissionService?.setCurrentUserPermissions(a))}this.userAccessFields$.next(JSON.parse(JSON.stringify(t)))}catch(t){this.loggingService.catch("Error in ContactService setUserAccessFields: ",t)}}updateUserInGlobalContactsIfAvailable(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let i=new ra;i.userId=e?.userId,i.userSnippylyId=e?.userSnippylyId,i.email=e?.email,i.name=e?.name,i.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;i&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let i,a=t?.filter(s=>s?.visibility!=="group"),l=!1;this.authService.getUserOptions()&&(l=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(i={},a?.forEach(s=>{if(s?.userId){let d=It(s?.userId);i[d]=s}}),l?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})):l&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}})}}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",i)}}migrateGroupContactsFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(i=>Q(this,null,function*(){let a=t[i];a?.email&&a?.userId&&It(a?.email)===i&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:i,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return Q(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(ut(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let i=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===zr.PUBLIC)i=!0;else if(a===zr.RESTRICTED){let l=It(this.user?.userId);if(t?.users?.[l]&&(i=!0),this.user?.email){let s=It(this.user?.email);t?.users?.[s]&&(i=!0)}}if(i){let l=new im;l.email=this.user.email,l.visibility="group",l.name=this.user.name,l.photoUrl=this.user.photoUrl,l.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[l]),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,t){try{let i=t?.filter(a=>a?.visibility==="group");i?.length&&i.forEach(a=>Q(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:It(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:It(a?.email),skipFirestore:!0}}))}}))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",i)}}removeGroupContacts(e){return Q(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(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(i=>{i?.userId?(!i?.email||!t[i.email])&&(t[i.userId]=i):i?.email&&(!i?.userId||!t[i.userId])&&(t[i.email]=i)}),e=Object.values(t??{}),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:t,documentId:i,veltFolderId:a}=e||{};return t&&i?pn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ue(([l,s,d,g,u,b,E,A])=>{let M={},V=!1;b&&!b?.merge&&(V=!0);let q=xe=>E.some(ke=>xe.includes(ke)),ae=q([fo.ALL,fo.ORGANIZATION])?Object.keys(l?.[t]||{}):[],fe=a?q([fo.ALL,fo.FOLDER])?Object.keys(s?.[t]?.[a]||{}):[]:[],ie=q([fo.ALL,fo.DOCUMENT])?Object.keys(d?.[t]?.[i]||{}):[];if([...ae,...fe||[],...ie,...A].forEach(xe=>{let ke=g?.[xe];ke&&(M[xe]=ke)}),u){let{merge:xe,options:ke}=b||{},{organizationId:ye,documentId:Oe,folderId:Ne}=ke||{},Ue=Ne?Pr(Ne):void 0;(!ye||ye===t)&&(!Oe||Oe===i)&&(!Ue||Ue===a)&&(xe||(M={}),u.forEach(ze=>{ze?.userId&&(M[ze.userId]=ze)}))}return Object.values(M??{})})):this.userContacts$.asObservable().pipe(ue(l=>l))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),le([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getUserBySnippylyId(e){return this.userSnippylyIdContacts$.value?.[e]}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe($e(e=>!!e),_e(e=>this.docService.getDocumentPaths$().pipe($e(t=>!!t),on(t=>{this.documentPaths=t}),ue(()=>e))),_e(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return le();if(!this.documentPaths)return le();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>i?.data),on(i=>{i?(this.userGlobalContacts=Object.values(i??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ue(i=>i?.data),on(i=>{i?(this.userGroupContacts=Object.values(i??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:It(e?.userId)}}).pipe(ue(i=>i?.data),on(i=>{i?this.userPersonalContacts=Object.values(i??{}):this.userPersonalContacts=[]}))),Ro(...t).pipe(zo(this.authService.getUser$().pipe($e(i=>!i))))})).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(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(xt(Jt))}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(_e(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(ue(t=>t?.data),on(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],le()):le():le())).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(_e(e=>e?.organizationId?this.userById$.pipe(ue(t=>{let i={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(i[a?.userSnippylyId]=a)}),i})):this.users$.pipe(ue(t=>{let i={};return t.forEach(a=>{i[a.userSnippylyId]=a}),i}))))}getUserByEmail$(e){return this.users$.pipe(ue(t=>t.find(i=>i.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ue(t=>t.find(i=>i.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe($e(t=>!!t),ue(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let i=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(i?.length){let a=i.map(g=>g?.userId),l=ot(),s=xc.GET_TEMPORARY_USERS;this.coreActionsService.triggerAction(Qe.USER_RESOLVER,{event:K.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:l,moduleName:s,methodName:gi.GET_TEMPORARY_USERS,source:"internal",payload:{userIds:a}});let d=yield this.usersService.resolveUsers({userIds:a,uniqueId:l,moduleName:s});if(d){let g={};Object.entries(d).forEach(([b,E])=>{g[b]=E}),this.userById$.next(f(f({},this.userById$.value),g));let u=new Set([...this.temporaryUserIds$.value,...Object.keys(g)]);this.temporaryUserIds$.next(Array.from(u))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}searchUsers(e){return Q(this,null,function*(){try{if(!e||typeof e!="string"||!e.trim())return[];let t=e.trim();return this.searchUsersDebounced$||(this.searchUsersDebounced$=this.searchUsersSubject$.pipe(Qr(this.searchUsersDebounceTime),xt(),_e(i=>po(this.performSearch(i)).pipe(ue(a=>({searchText:i,results:a})),Jn(a=>(this.loggingService.catch("Error in ContactService performSearch: ",a),le({searchText:i,results:[]})))))),this.searchUsersDebounced$.subscribe({next:({searchText:i,results:a})=>{Array.from(this.pendingSearchPromises.keys()).forEach(d=>{if(d!==i){let g=this.pendingSearchPromises.get(d);g&&(g.forEach(({resolve:u})=>u([])),this.pendingSearchPromises.delete(d))}});let s=this.pendingSearchPromises.get(i);s&&(s.forEach(({resolve:d})=>d(a)),this.pendingSearchPromises.delete(i))},error:i=>{this.pendingSearchPromises.forEach(a=>{a.forEach(({reject:l})=>l(i))}),this.pendingSearchPromises.clear()}})),new Promise((i,a)=>{this.pendingSearchPromises.has(t)||this.pendingSearchPromises.set(t,[]),this.pendingSearchPromises.get(t).push({resolve:i,reject:a}),this.searchUsersSubject$.next(t)})}catch(t){return this.loggingService.catch("Error in ContactService searchUsers: ",t),[]}})}performSearch(e){return Q(this,null,function*(){try{let t=this.docService.getOrganizationConfig()?.organizationId;if(!t)return[];let i=this.documentPaths?.veltFolderId,a=this.docService.getDocumentIds().map(q=>q?.documentId),l=e.toLowerCase().trim(),s=l+"\uF8FF",d=[],g=a?.filter(q=>!!q)||[],u=g.length>0,b=!!i;if(u){let q=[];for(let fe=0;fe<g.length;fe+=20)q.push(g.slice(fe,fe+20));q.forEach(fe=>{let ie=[ft("documentIds","array-contains-any",fe),ft("viewerDocumentIds","array-contains-any",fe)],Ce=[ft("organizationIds","array-contains-any",[t]),ft("viewerOrganizationIds","array-contains-any",[t]),...ie];b&&Ce.push(ft("folderIds","array-contains-any",[i]),ft("viewerFolderIds","array-contains-any",[i])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[_r(N0(...Ce),ft("user.name_lowercase",">=",l),ft("user.name_lowercase","<",s)),lv(10)]}}).catch(()=>[])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[_r(N0(...Ce),ft("user.email_lowercase",">=",l),ft("user.email_lowercase","<",s)),lv(10)]}}).catch(()=>[]))})}let E=yield Promise.all(d),A=[];E.forEach(q=>{q&&Array.isArray(q)?q.forEach(ae=>{ae&&ae.user&&ae.user.userId&&A.push(ae)}):q&&typeof q=="object"&&Object.values(q).forEach(fe=>{fe&&fe.user&&fe.user.userId&&A.push(fe)})});let M=new Map;A.forEach(q=>{let ae=q.user?.userId;ae&&!M.has(ae)&&M.set(ae,q)});let V=Array.from(M.values());return this.setResolvedUsers(V,!0),V}catch(t){return this.loggingService.catch("Error in ContactService performSearch: ",t),[]}})}setResolvedUsers(e,t=!1){try{if(e?.length){let i=[],a=[],l=[],s=this.docService.getOrganizationConfig()?.organizationId,d=this.documentPaths?.veltFolderId,g=this.docService.getDocumentIds().map(E=>E?.documentId);e.forEach(E=>{this.userById$.value[E?.user?.userId]||(s&&E?.organizationIds?.includes(s)&&!i.find(A=>A?.user?.userId===E?.user?.userId)&&i.push(E),d&&E?.folderIds?.includes(d)&&!a.find(A=>A?.user?.userId===E?.user?.userId)&&a.push(E),g?.some(A=>E?.documentIds?.includes(A))&&!l.find(A=>A?.user?.userId===E?.user?.userId)&&l.push(E))}),i?.length&&this.setUserOrganizationContacts(i,s,t),a?.length&&this.setUserFolderContacts(a,t),l?.length&&this.setUserDocumentContacts(l,t);let b=[...i,...a,...l].filter((E,A,M)=>A===M.findIndex(V=>V.user.userId===E.user.userId));b?.length&&(this.setUserAccessFields(b),this.mergeOrganizationAndDocumentContacts())}}catch(i){this.loggingService.catch("Error in ContactService setResolvedUsers: ",i)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?.organizationId?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>this.usersService.getResolveOrganizationUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],i),t?i?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i]))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]}}).pipe(ue(a=>a?.data),_e(a=>this.commentService?.getPaginatedContactList()&&!Object.values(a??{}).find(l=>l?.user?.userId===this.authService.getUser()?.userId)?po(this.commonDbService.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i])),ft("user.userId","==",this.authService.getUser()?.userId))]}})).pipe(ue(l=>{if(l&&l.length>0){let s=l[0],d=s?.user?.userId||s?.id;if(d&&a){let g=It(d);return k(f({},a),{[g]:s})}}return a})):le(a)),ue(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let l=Object.values(a??{});this.setUserAccessFields(l),this.setUserOrganizationContacts(l,i)}else this.setUserOrganizationContacts([],i)})):le():le()}),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>this.usersService.getResolveFolderUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return le();if(!this.commonDbService.shouldUseFirestore())return le();if(!this.documentPaths?.veltFolderId)return le();let a=le([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:i,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[_r(N0(ft("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ft("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]}}).pipe(ue(l=>l?.data)),a.pipe(ue(l=>{if(l){typeof l=="object"&&(l?.undefined&&delete l.undefined,l?.null&&delete l.null);let s=Object.values(l??{});this.setUserAccessFields(s),this.setUserFolderContacts(s)}else this.setUserFolderContacts([])}))}),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(_e(e=>e?le(e).pipe(_e(t=>this.docService.getDocumentPaths$().pipe($e(i=>!!i),on(i=>{this.documentPaths=i}),ue(()=>t))),_e(t=>this.usersService.getResolveDocumentUsers$().pipe($e(i=>i),ue(()=>t))),_e(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(_e(i=>{let a=i?.length>0?i.map(g=>g.documentId):[this.documentPaths?.documentId??""];if(a.some(g=>!g)||!this.documentPaths)return le();let l=le([]),s={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(s.documentId=a?.length?a[0]:void 0,s.organizationId=this.documentPaths?.organizationId);let d=[];for(let g=0;g<a.length;g+=U.LISTENER_BATCH_SIZE)d.push(a.slice(g,g+U.LISTENER_BATCH_SIZE));return l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:k(f({},s),{firestoreQuery:[_r(N0(ft("documentIds","array-contains-any",g),ft("viewerDocumentIds","array-contains-any",g))),vo("id"),...this.commentService?.getPaginatedContactList()?[lv(10)]:[]]})}).pipe(la()))).pipe(ue(g=>Ra(g)?.data)),l.pipe(ue(g=>{if(g){typeof g=="object"&&(g?.undefined&&delete g.undefined,g?.null&&delete g.null);let u=Object.values(g??{});this.setUserAccessFields(u),this.setUserDocumentContacts(u)}else this.setUserDocumentContacts([])}))})):le():le())),_e(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),le()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t,i=!0){try{let a=e.find(s=>s.user.userId===this.user?.userId);a&&this.setCurrentOrganizationUserIAM(a);let l=e.map(s=>s.user)?.filter(s=>!this.userOrganizationContacts$.value.find(d=>d.userId===s.userId));if(this.userOrganizationContacts$.next([...this.userOrganizationContacts$.value,...l]),i&&this.usersService.setUserByIds(l),t){let s={};s[t]={};let d={};e.forEach(u=>{s[t][u.user.userId]=u,d[u.user.userId]=u.user}),this.userById$.next(f(f({},this.userById$.value),d));let g=this.usersByOrganizationId$.value?.[t];g&&(s[t]=f(f({},g),s[t])),this.usersByOrganizationId$.next(k(f({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(a){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",a)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION])?this.userOrganizationContacts$.asObservable():le([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userFolderContacts$.value.find(g=>g.userId===d.userId));this.userFolderContacts$.next([...this.userFolderContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndFolderId$.value||{},l=f({},a),s={};e?.forEach(d=>{let{organizationId:g}=d?.metadata||{};g&&(l[g]||(l[g]={}),d.folderIds?.forEach(u=>{l[g][u]||(l[g][u]={}),l[g][u]=k(f({},l[g][u]),{[d.user.userId]:d}),s[d.user.userId]=d.user}))}),this.userById$.next(f(f({},this.userById$.value),s)),this.usersByOrganizationIdAndFolderId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.FOLDER])?this.userFolderContacts$.asObservable():le([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userDocumentContacts$.value.find(g=>g.userId===d.userId));this.userDocumentContacts$.next([...this.userDocumentContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndDocumentId$.value||{},l=f({},a),s={};e?.forEach(d=>{let{organizationId:g}=d?.metadata||{};g&&(l[g]||(l[g]={}),d.documentIds?.forEach(u=>{l[g][u]||(l[g][u]={}),l[g][u]=k(f({},l[g][u]),{[d.user.userId]:d}),s[d.user.userId]=d.user}))}),this.userById$.next(f(f({},this.userById$.value),s)),this.usersByOrganizationIdAndDocumentId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.userDocumentContacts$.asObservable():le([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.userDocumentContacts$.value:[]}setCurrentOrganizationUserIAM(e){try{this.currentOrganizationUserIAM$.next(JSON.parse(JSON.stringify(e)))}catch(t){this.loggingService.catch("Error in ContactService setCurrentOrganizationUserIAM: ",t)}}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable().pipe(xt(Jt))}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{this.mergeContactsDebounceTimer&&clearTimeout(this.mergeContactsDebounceTimer),this.mergeContactsDebounceTimer=setTimeout(()=>{this.executeMergeContacts()},200)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}executeMergeContacts(){try{let e=this.getContactListScopeForOrganizationUsers(),t=[];e.includes(fo.ALL)?t=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:e.includes(fo.ORGANIZATION)?t=[...this.getUserOrganizationContacts()]:e.includes(fo.FOLDER)?t=[...this.getUserFolderContacts()]:e.includes(fo.DOCUMENT)&&(t=[...this.getUserDocumentContacts()]);let i=[...new Map(t.filter(a=>a?.userId).map(a=>[a.userId,a])).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(_e(e=>e?.organizationId?le(e).pipe(_e(t=>this.docService.getOrganizationConfig$().pipe($e(i=>!!i),ue(()=>t))),_e(t=>{if(this.setUserOrganizationGroups([]),!t)return le();let i=this.docService.getOrganizationConfig()?.organizationId;return i?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:i,isCollection:!0}}).pipe(ue(a=>a?.data),ue(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):le()})):(this.setUserOrganizationGroups([]),le()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),i=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case zr.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:i,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():le([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.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:je.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.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(_e(()=>this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.atHereEnabled$.asObservable():le(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([fo.ALL,fo.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return Q(this,null,function*(){try{this.analyticsService.trackEvent(K.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService.setUserByIds(e),this.customUserContacts$.next(e),this.customUserContactsConfig$.next(t)}catch(i){this.loggingService.catch("Error in CommentService updateContactList: ",i)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=k(f({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(_e(e=>e?pn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ue(([t,i,a,l,s])=>{let d={};d.organizationUsers=t?.map(u=>this.convertToClientUser(u)),d.folderUsers=i?.map(u=>this.convertToClientUser(u)),d.documentUsers=a?.map(u=>this.convertToClientUser(u)),d.updatedContactList=s?.map(u=>this.convertToClientUser(u));let g=[];return l?.forEach(u=>{let b=this.convertToClientUserGroup(u,d.organizationUsers||[]);b&&g.push(b)}),d.userGroups=g,d}),xt(Jt)):le(null)),Jn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),le(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),le(null)}}convertToClientUserGroup(e,t){try{let i={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(l=>{if(l?.userId){let s=It(l.userId);a[s]=l}}),Object.keys(e?.users??{}).forEach(l=>{a[l]&&i.users?.push(a[l])}),i}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",i),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(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(Ft),X(tr),X($n),X(ct),X(x),X(Tn),X(An))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ln=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g){this.analyticsService=e,this.authService=t,this.contactService=i,this.databaseService=a,this.docService=l,this.configService=s,this.loggingService=d,this.commonDbService=g,this.documentIAM$=new Se(null),this.workspaceIAM$=new Se(null),this.roles$=new Se([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe($e(u=>!!u),ut(1)).subscribe(u=>{u&&(this.getUser(),this.getDocumentPaths())},u=>{this.loggingService.catch("Error in CommentService getDb subscription: ",u)}),this.getRole$().pipe(ut(1)).subscribe(u=>{this.authService?.getUser()&&!u&&this.analyticsService.trackEvent(K.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(u=>{u?.accessType&&this.contactService.setDocumentAccessType(u.accessType)})}catch(u){this.loggingService.catch("Error in IamService constructor: ",u)}}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($e(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($e(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 t=e||new uL;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Jn(e=>le(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(ue(e=>!!e),xt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ue(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ue(e=>e?.features),_e(e=>this.getRole$().pipe(ue(t=>(t===Lo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(_e(()=>this.documentIAM$.pipe($e(t=>!!t),_e(()=>this.workspaceIAM$.pipe(ue(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),le(!1)}}getRole$(){try{return this.authService.getUser$().pipe(_e(()=>this.configService.getSF$()),_e(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():le(null)),_e(()=>this.configService.getSF()?this.documentIAM$.pipe($e(e=>!!e),xt(Jt)):le(null)),_e(()=>this.workspaceIAM$.pipe(xt(Jt))),ue(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),le(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return Lo.ADMIN;if(!e)return this.user?.isAdmin?Lo.ADMIN:Lo.COMMENTER;let t=null,i;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?zr.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||zr.PUBLIC:null){case zr.PUBLIC:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||Lo.COMMENTER;break;case zr.RESTRICTED:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ue(e=>e===Lo.ADMIN),xt())}isUserAdmin(){try{return this.getRole()===Lo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let i;return e&&(i=this.documentIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.documentIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",i)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let i;return e&&(i=this.workspaceIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.workspaceIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",i)}}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(We),X(dn),X($n),X(ct),X(Ft),X(x),X(Tn))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var UL="public",il=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b){this.authService=e,this.docService=t,this.loggingService=i,this.commonDbService=a,this.usersService=l,this.commentUtilsService=s,this.coreActionsService=d,this.functions=g,this.configService=u,this.contactService=b,this.currentUserPermissions$=new Se(null),this.permissionsCache$=new Se(null),this.permissionProvider$=new Se(null),this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(E){this.loggingService.catch("Error in UserPermissionService constructor:",E)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,t,i,a,l,s){try{return e.find(g=>g.resourceId===i&&g.type===a&&g.organizationId===l&&g.userId===s)?(t.push({userId:s,resourceId:i,organizationId:l,type:a,hasAccess:!1}),e.filter(g=>!(g.resourceId===i&&g.type===a&&g.organizationId===l&&g.userId===s))):e}catch(d){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",d),e}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled()||t.includes(U.DEFAULT_VELT_CONTEXT))return!0;let i=this.contactService.getUserAccessFieldsByUserId(e);return i?t.every(a=>i.includes(a)):!0}catch(i){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",i),!1}}organizationDetails(e){return Q(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e}});return t&&t?.errorCode?{errorCode:_o.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:_o.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return Q(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t}});if(a&&a?.errorCode)return{errorCode:_o.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:_o.DOES_NOT_EXIST,error:!0};let l=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},l),a?.metadata??{}));let s,d=a?.metadata?.veltFolderId;if(d)try{s=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:d,organizationId:t}}))?.folderIamConfig?.accessType}catch(g){this.loggingService.catch("Error fetching folder accessType for document:",g)}return s||(s=a?.docIamConfig?.accessType),{error:!1,accessType:s}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(i){return Q(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:_o.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:_o.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:a?.folderIamConfig?.accessType}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:_o.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let i=yield this.validateResources(t),[a,l]=yield this.fetchUserPermissionsFromDB(t),s=this.buildPermissionsResponse(t,i,a,l);return!e&&Object.keys(s).length>0&&this.setCurrentUserPermissions(s),s}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),i=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:i.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId,organizationId:e?.organizationId??t?.clientOrganizationId?Pa(e?.organizationId??t?.clientOrganizationId??""):void 0}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a,clientOrganizationId:l}=e,s=[],d=[];a&&(s.push(this.organizationDetails(a)),d.push({id:l??"",type:"organization"})),t.forEach(b=>{s.push(this.folderDetails({folderId:Pr(b),organizationId:a??""})),d.push({id:b,type:"folder"})}),i.forEach(b=>{s.push(this.documentDetails({documentId:mi(b),organizationId:a??""})),d.push({id:b,type:"document"})});let[g,u]=yield Promise.all([Promise.allSettled(s),this.getDefaultDocumentAccessType()]);return k(f({},this.processValidationResults(g,d)),{defaultDocumentAccessType:u})})}getDefaultDocumentAccessType(){return Q(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,t){let i=[],a=[],l,s={},d={};for(let g=0;g<e.length;g++){let u=e[g],b=t[g];if(u.status==="rejected"||u.status==="fulfilled"&&u.value.error){let A=u.status==="fulfilled"?u.value.errorCode??_o.SOMETHING_WENT_WRONG:_o.SOMETHING_WENT_WRONG,M={id:b.id,errorCode:A};switch(b.type){case"organization":if(l=M,A===_o.DOES_NOT_EXIST)throw new Error(`Organization with id '${b.id}' does not exist`);break;case"folder":i.push(M);break;case"document":a.push(M);break}}else if(u.status==="fulfilled")switch(b.type){case"folder":u.value.accessType&&(s[b.id]=u.value.accessType);break;case"document":u.value.accessType&&(d[b.id]=u.value.accessType);break}}return{failedFolderIds:i,failedDocumentIds:a,failedOrganizationId:l,folderAccessTypes:s,documentAccessTypes:d}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a}=e,l=[this.authService.getUser()?.userId??""],s=[...t.map(u=>Pr(u)),...i.map(u=>mi(u)),a??""],[d,g]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:l,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:l,organizationId:a,resourceIds:s})]);return[d.status==="fulfilled"?d.value:[],g.status==="fulfilled"?g.value:[]]})}buildPermissionsResponse(e,t,i,a){let{folderIds:l,documentIds:s,clientOrganizationId:d,organizationId:g}=e,{failedFolderIds:u,failedDocumentIds:b,failedOrganizationId:E}=t,A={};return this.processRegularUserPermissions(A,i,l,s,d??"",g??"",u,b,E,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.processTemporaryUserPermissions(A,a),this.processContextPermissions(A),A}processContextPermissions(e){try{let t=this.authService.getUser()?.userId;if(t){let i=this.contactService.getUserAccessFieldsByUserId(t);i?.length&&(e[t]||(e[t]={}),e[t].context={accessFields:i})}}catch(t){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",t);return}}processRegularUserPermissions(e,t,i,a,l,s,d,g,u,b,E,A){for(let M of t)for(let V of M)V?.user?.userId&&(e[V.user.userId]=k(f({},i.length&&{folders:this.buildFolderPermissions(i,V,d,b,A)}),{documents:this.buildDocumentPermissions(a,V,g,E,A),organization:{[l]:this.buildOrganizationPermission(s,V,u)}}))}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case _o.DOES_NOT_EXIST:return`${t} does not exist`;case _o.PERMISSION_DENIED:return`User does not have access to ${t}`;case _o.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(i){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",i),"Something went wrong"}}buildFolderPermissions(e,t,i,a,l){return e.reduce((s,d)=>{let g=i.find(u=>u.id===d);return g?s[d]=f({error:this.getErrorMessage(g.errorCode,"folder"),errorCode:g.errorCode},g.errorCode===_o.PERMISSION_DENIED&&{accessType:a[d]??l??UL}):s[d]={accessRole:t.viewerFolderIds?.includes(Pr(d))?$s.VIEWER:$s.EDITOR,accessType:a[d]??l??UL},s},{})}buildDocumentPermissions(e,t,i,a,l){return e.reduce((s,d)=>{let g=i.find(u=>u.id===d);return g?s[d]=f({error:this.getErrorMessage(g.errorCode,"document"),errorCode:g.errorCode},g.errorCode===_o.PERMISSION_DENIED&&{accessType:a[d]??l??UL}):s[d]={accessRole:t.viewerDocumentIds?.includes(mi(d))?$s.VIEWER:$s.EDITOR,accessType:a[d]??l??UL},s},{})}buildOrganizationPermission(e,t,i){return i?{error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?$s.VIEWER:$s.EDITOR}}processTemporaryUserPermissions(e,t){for(let i of t)if(i?.userId)switch(this.ensureUserPermissionStructure(e,i.userId),i.type){case"folder":this.addTemporaryFolderPermission(e,i);break;case"document":this.addTemporaryDocumentPermission(e,i);break;case"organization":this.addTemporaryOrganizationPermission(e,i);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].folders||(e[i].folders={}),e[i].folders[a]||(e[i].folders[a]={accessRole:l??$s.EDITOR,expiresAt:s})}addTemporaryDocumentPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].documents||(e[i].documents={}),e[i].documents[a]={accessRole:l??$s.EDITOR,expiresAt:s}}addTemporaryOrganizationPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:s}=t;e[i].organization||(e[i].organization={}),e[i].organization[a]={accessRole:l??$s.EDITOR,expiresAt:s}}hasEditAccess({organizationId:e,folderId:t,documentId:i}){try{let a=!0,l=this.getCurrentUserPermissionsWithServerIds(),s=this.authService.getUser()?.userId??"";return l&&(e&&typeof e=="string"&&l?.[s]?.organization?.[e]&&(l?.[s]?.organization?.[e]?.accessRole===$s.VIEWER||l?.[s]?.organization?.[e]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&l?.[s]?.folders?.[t]&&(l?.[s]?.folders?.[t]?.accessRole===$s.VIEWER||l?.[s]?.folders?.[t]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1),i&&typeof i=="string"&&l?.[s]?.documents?.[i]&&(l?.[s]?.documents?.[i]?.accessRole===$s.VIEWER||l?.[s]?.documents?.[i]?.errorCode===_o.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(xt(Jt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),i=this.authService.getUser()?.userId??"";if(t?.[i]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[i]?.organization?.[a]){let l=Pa(a);t[i].organization&&(t[i].organization[l]=t[i].organization[a],delete t[i].organization[a])}t?.[i]?.folders&&(t[i].folders=Object.fromEntries(Object.entries(t?.[i]?.folders??{}).map(([l,s])=>[Pr(l),s]))),t?.[i]?.documents&&(t[i].documents=Object.fromEntries(Object.entries(t?.[i]?.documents??{}).map(([l,s])=>[mi(l),s])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ue(e=>this.refactorPermissionsWithServerIds(e)),xt(Jt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let t=null;e&&(t=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(t)}catch(t){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",t)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.permissionProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",t)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===tS.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return Q(this,null,function*(){let e=ot();try{if(this.isRevokeAccessOnUserLogoutEnabled){let t=[],i=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(l=>{l.userId===i&&l.hasAccess&&(l.type===oa.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&t.push(k(f({},l),{hasAccess:!1})):t.push(k(f({},l),{hasAccess:!1})))}),t.length>0){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}}),this.setPermissionsCache([]),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}});let l=yield this.revokeAccess({requests:t,userId:this.authService.getUser()?.userId??""});l.success?this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!1,statusCode:500}}})}}}catch(t){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:t}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",t)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(t){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",t),""}}cancelPendingRevokes(e){try{e.forEach(t=>{let i=this.getRevokeKey({userId:t.userId,resourceId:t.resource.id,type:t.resource.type,organizationId:t.resource.organizationId});this.pendingRevokeRequests.has(i)&&this.pendingRevokeRequests.delete(i)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(t){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",t)}}flushPendingRevokes(){return Q(this,null,function*(){let e=this.pendingRevokeUniqueId,t=this.pendingRevokeUserId;try{let i=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",i.length===0)return;let a=this.getPermissionsCache()??[];i.forEach(d=>{a=a.filter(g=>!(g.resourceId===d.resourceId&&g.type===d.type&&g.organizationId===d.organizationId&&g.userId===d.userId))}),this.setPermissionsCache(a);let l=this.docService.getDocContext(),s=yield this.revokeAccess({requests:i,userId:t,currentContext:l});s.success?this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:s,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:s,success:!1,statusCode:500}}})}catch(i){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",i)}})}revokeAccessOnDocumentUnset(a){return Q(this,arguments,function*({documentIds:e,folderId:t,context:i}){let l=ot();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let s=[],d=this.docService.getOrganizationConfig()?.clientOrganizationId??"",g=this.authService.getUser()?.userId??"",u=this.getPermissionsCache()??[];e.forEach(b=>{u=this.collectRevokeRequest(u,s,b.clientDocumentId,oa.DOCUMENT,d,g)}),t&&(u=this.collectRevokeRequest(u,s,t,oa.FOLDER,d,g)),d&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(u=this.collectRevokeRequest(u,s,d,oa.ORGANIZATION,d,g)),i&&this.getIsContextEnabled()&&FN({input:i}).forEach(E=>{let A=JSON.stringify(E.access);u=this.collectRevokeRequest(u,s,A,oa.CONTEXT,d,g)}),this.setPermissionsCache(u),s.length>0&&(this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:s}}),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:s}}),s.forEach(b=>{this.pendingRevokeRequests.set(this.getRevokeKey(b),b)}),this.pendingRevokeUniqueId=l,this.pendingRevokeUserId=g,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(s){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ro.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",s)}})}getAccess(i){return Q(this,arguments,function*({requests:e,userId:t}){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield _l({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(a){return Q(this,arguments,function*({requests:e,userId:t,currentContext:i}){let l=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield _l({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:f({retryConfig:this.getPermissionProviderRetryConfig()},i?.access&&{currentContext:i})},getSdkProxy:l,userId:t})})}onResourceAccessRequired(s){return Q(this,arguments,function*({requests:e,uniqueId:t,methodName:i,userId:a,fromCache:l=!0}){try{if(!e?.length)return;let d=[],g=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&l&&(e.forEach(u=>{let b=g?.find(E=>E.resourceId===u.resource.id&&E.type===u.resource.type&&E.userId===u.userId&&E.organizationId===u.resource.organizationId);b&&d.push(b)}),d.length>0&&(e=e.filter(u=>!d.find(b=>b.resourceId===u.resource.id&&b.type===u.resource.type&&b.userId===u.userId&&b.organizationId===u.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{requests:e,fromCache:l}});let u=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{result:u}}),u?.success&&u?.data?.length&&(this.setPermissionsCache([...g,...u.data]),u.data=[...d,...u.data]),u}else if(d.length>0)return this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{results:{data:d,success:!0,statusCode:200}}}),{data:d,success:!0,statusCode:200};return}catch(d){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",d),this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{error:d,requests:e,fromCache:l}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let t=new Map;e.forEach(a=>{let l=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(l,a)});let i=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(i)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",t)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(We),X(ct),X(x),X(Tn),X(An),X(cv),X(tr),X(Do),X(Ft),X(dn))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hi=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.databaseService=l,this.commonDbService=s,this.docService=d,this.domService=g,this.emojiService=u,this.iamService=b,this.loggingService=E,this.userPermissionService=A,this.documentPaths=null,this.reactionAnnotationById$=new Se({}),this.customReactions$=new Se({}),this.commentService=null,this.darkMode$=new Se(null),this.loggingService.log("%c[WB] Creating CLASS: ReactionService","color: blue;"),this.analyticsService.setReactionService(this),this.authService.setReactionService(this),this.databaseService.getDb().pipe($e(M=>!!M),ut(1)).subscribe(M=>{M&&this.getAllReactionAnnotations(void 0,void 0,!0).subscribe()},M=>{this.loggingService.catch("Error in ReactionService getDb subscription: ",M)})}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in ReactionService setCommentService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ReactionService","color: green;");try{this.reactionAnnotationById$.next({}),this.customReactions$.next({}),this.documentPaths=null}catch(e){this.loggingService.catch("Error in ReactionService clearCache: ",e)}}getAllReactionAnnotations(e,t,i,a,l){this.loggingService.log("%c[WB] Calling FUNCTION: getAllReactionAnnotations","color: green;");let s,d;try{if(e&&(d=`${Qn(e)}`),t&&typeof t=="object"){let g=Oi(t);s=Qn(JSON.stringify(g))}}catch(g){this.loggingService.catch("Error in ReactionService getAllReactionAnnotations: ",g)}return fr(this.afAuth).pipe($e(g=>!!g),_e(g=>this.isFeatureAllowed({firebaseUser:g,annotations:[],filteredAnnotations:[]})),_e(g=>g.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(u=>(g.featureAllowed=u,g))):le(g)),_e(g=>g.featureAllowed?le(g).pipe(_e(u=>this.docService.getDocumentPaths$().pipe(ue(b=>(this.documentPaths=b,u.documentPaths=b,u)))),_e(u=>d?this.getDataFromDocumentIds([d]).pipe(ue(b=>(u.annotations=b||[],f({},u)))):this.docService.getDocumentIds$().pipe(_e(b=>{let E=b?.length>0?b.map(A=>A.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(E).pipe(ue(A=>(u.annotations=A||[],f({},u))))}))),_e(u=>this.docService.getLocation$().pipe(ue(b=>(u.location=b,u)))),_e(u=>this.docService.getLocations$().pipe(ue(b=>(u.customLocations=b,u)))),ue(u=>{if(u.filteredAnnotations=[],d&&!s)return u.filteredAnnotations=u.annotations?.slice(),u;{let b=[];return s?b.push(s):(b.push(u?.location?.locationId),b.push(...Object.values(u?.customLocations||[]).map(E=>E.locationId))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,b),u}}),_e(u=>i?le(u):u?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>u)):le(u)),_e(u=>i?le(u):le(u)),ue(u=>u),_e(u=>u?.filteredAnnotations?le(u?.filteredAnnotations||[]):le([]))):le([])),xt(Jt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.REACTION)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Reaction feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))),xt((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return le([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=le([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=t?.length?t[0]:void 0,s.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[U.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],g=[];for(let u=0;u<(d?.length??0);u+=U.LISTENER_CONTEXT_BATCH_SIZE)g.push(d?.slice(u,u+U.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=pn(g.map(u=>this.commonDbService.dbListener({feature:"allReactions",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Ra(u)))}else{let d=[];for(let g=0;g<(t?.length??0);g+=U.LISTENER_BATCH_SIZE)d.push(t?.slice(g,g+U.LISTENER_BATCH_SIZE)??[]);l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allReactions",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",g),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(g=>Ra(g)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:g})=>{let u=[];return d&&(u=Object.values(d??{}).filter(b=>typeof b=="object")),u?.forEach(b=>{this.sanitizeReactionAnnotation(b)}),{data:u,operation:g}}),ue(({data:d,operation:g})=>{if(!t)return{data:d,documentMap:{},operation:g};let u=d.reduce((b,E)=>{let A=E.metadata?.documentId;return A&&(b[A]||(b[A]=[]),b[A].push(E)),b},{});return{data:d,documentMap:u,operation:g}}),ue(({data:d,documentMap:g,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let b=this.reactionAnnotationById$.value;u?.ids?.forEach(E=>{delete b?.[E]}),this.reactionAnnotationById$.next(b)}}else Object.entries(g??{}).forEach(([b,E])=>{this.setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:b,annotations:E})});return d}),Jn(d=>(this.loggingService.catch("Error in ReactionService getDataFromDocumentId: ",d),le([]))))}else return le([])}setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let s=f(f({},this.reactionAnnotationById$.value),l);this.reactionAnnotationById$.next(s)}}catch(l){this.loggingService.catch("Error in ReactionService setReactionAnnotationsByOrganizationIdAndDocumentId:",l)}}getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.reactionAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getLocations$(){return this.docService.getLocation$().pipe(_e(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ReactionService filterAnnotationsByLocations:",i),[]}}getAnnotationById(e,t){try{let i=this.reactionAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in ReactionService getAnnotationById: ",i);return}}getBaseMetadataFromReactionAnnotationId(e){try{let t=this.reactionAnnotationById$.value?.[e];return t?t.metadata:void 0}catch(t){this.loggingService.catch("Error in ReactionService getBaseMetadataFromReactionAnnotationId: ",t);return}}getReactionAnnotationByAnnotationId(e,t){try{return this.reactionAnnotationById$.pipe(ue(()=>this.getAnnotationById(e,t)),_e(i=>i?le(i):le(i)))}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationByAnnotationId: ",i),le(void 0)}}getReactionAnnotationsBySectionId(e){try{return this.reactionAnnotationById$.pipe(_e(t=>this.docService.getDocumentPaths$().pipe(ue(i=>({documentPaths:i,sectionId:e,reactionAnnotationsMap:t})))),_e(t=>{let i=tl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(s=>{let g=Object.values(s||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return k(f({},t),{additionalLocation:g,locationOnElement:!!a})}))}}return le(k(f({},t),{additionalLocation:null,element:i}))}),_e(t=>t?.locationOnElement?le(t):this.docService.getLocation$().pipe(ue(i=>k(f({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:s})=>{let d=null,g=this.docService.getAdditionalDocumentIdFromElement(s),u=g?this.docService.generateDocumentId(g):t?.documentId,b=t?.organizationId;if(u){let E=this.getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:b,documentId:u});if(E){d=[];for(let A of E)A?.targetElementId===e&&(l?a&&s0({location:a?.location,locationId:a?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):i?s0({location:i?.location,locationId:i?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):A?.locationId||d.push(A))}}return d}))}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsBySectionId: ",t),le(null)}}addOrUpdateReaction(e,t,i,a,l,s,d,g){return Q(this,null,function*(){try{let u=t?.map(b=>this.getAnnotationById(b)).find(b=>b?.icon===e);if(u){if(!d||d==="delete")return yield this.updateUserInReaction(u)}else if(!d||d==="add")return yield this.addReaction(void 0,e,i,a,l,s,g)}catch(u){this.loggingService.catch("Error in ReactionService addOrUpdateReaction: ",u)}})}addReaction(e,t,i,a,l,s,d){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{let g=this.authService.getUser();if(g)if(g.isReadOnly||g.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add reactions.");else{let u=new dL;if(u.from=g,u.lastUpdated=this.timestamp,u.reactions=[],u.reactions.push({from:g,lastUpdated:this.timestamp}),a&&(u.targetElementId=a),l){u.commentAnnotationId=l;let b=this.commentService?.getAnnotationById(l);if(b?.context?.access&&b?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:g.userId,accessFields:b.context.accessFields})){this.loggingService.catch("User does not have context access to add reaction annotation.",void 0,void 0,!0);return}u.context={access:b.context.access,accessFields:b.context.accessFields}}}if(this.setLocationToReactionAnnotation(u),u.pageInfo=to(),u.pageInfo&&(u.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),t)if(u.icon=t,s)u.iconUrl=s?.url,u.iconEmoji=s?.emoji;else{let b=this.customReactions$.value;if(b){let E=b[t];E?.url&&(u.iconUrl=E?.url),E?.emoji&&(u.iconEmoji=E?.emoji)}}return i&&(u.location={},u.location=f({},i),u.locationId=this.docService.genarateLocationId(u.location)),yield this.saveReactionToDb(u)}}catch(g){this.loggingService.catch("Error in ReactionService addReaction: ",g)}})}setLocationToReactionAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?.xpath?i=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId&&(i=tl(e.targetElementId,["id","data-id"]));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in ReactionService setLocationToReactionAnnotation:",t)}}getElementForReactionAnnotation(e){try{let t;return e.targetElementId&&(t=tl(e.targetElementId,["id","data-id"])),t}catch(t){return this.loggingService.catch("Error in ReactionService getElementForReactionAnnotation: ",t),null}}saveReactionToDb(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: saveReactionToDb","color: green;");try{if(this.authService.getUser()){let t=yield this.docService.getDocumentPaths$().pipe($e(a=>!!a),ut(1)).toPromise();if(!t)throw new Error("Document paths not found.");if(this.documentPaths=t,this.loggingService.log(this.documentPaths),!(yield this.databaseService.getDb().pipe($e(a=>!!a),ut(1)).toPromise()))throw new Error("Database not found.");if(this.documentPaths?.reaction){if(e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo,!e?.metadata?.documentId){e?.metadata||(e.metadata={});let g=this.getElementForReactionAnnotation(e),u=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId,element:g});e.metadata=f(f({},e?.metadata),u)}let a=JSON.parse(JSON.stringify(e));a.position=null;let{documentId:l,organizationId:s}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(e),d=e.commentAnnotationId?void 0:{annotationData:a,actionType:"add",notificationSource:"reaction"};return yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:a,extraData:d}),a}else return}}catch(t){this.loggingService.catch("Error in ReactionService saveReactionToDb: ",t)}})}getDocumentIdAndOrganizationIdFromReactionAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in ReactionService getDocumentIdAndOrganizationIdFromReactionAnnotation: ",t),{}}}updateUserInReaction(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(t)return e?.reactions||(e.reactions=[]),e?.reactions?.find(a=>a?.from?.userId===t?.userId)?e.reactions=e?.reactions?.filter(a=>a?.from?.userId!==t?.userId):e.reactions.push({from:t,lastUpdated:this.timestamp}),e.reactions.length?yield this.updateReaction(e):yield this.deleteReactionPinAnnotation(e?.annotationId),e}catch(t){this.loggingService.catch("Error in ReactionService updateUserInReaction: ",t)}})}removeUserFromReaction(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeUserFromReaction","color: green;");try{let t=this.authService.getUser();t&&(e?.reactions||(e.reactions=[]),e.reactions=e?.reactions?.filter(i=>i?.from?.userId!==t?.userId),this.updateReaction(e))}catch(t){this.loggingService.catch("Error in ReactionService removeUserFromReaction: ",t)}}updateReaction(e,t,i){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateReaction","color: green;");try{if(this.authService.getUser()){if(e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let g=d.iterateNext();g&&(Zr(g)||(e.targetElement=null))}}let a=JSON.parse(JSON.stringify(e));if(a.position=null,a.lastUpdated=this.timestamp,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId});a.metadata=f(f({},a?.metadata),d)}let{documentId:l,organizationId:s}=a?.metadata||{};return i?yield this.commonDbService.updateData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))}):yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))}),a}}catch(a){this.loggingService.catch("Error in ReactionService updateReaction: ",a)}})}deleteReactionPinAnnotation(e,t){return Q(this,null,function*(){try{let i=this.getAnnotationById(e),{documentId:a,organizationId:l}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(i),s=i&&!i.commentAnnotationId?{annotationData:i,actionType:"delete",notificationSource:"reaction"}:void 0;yield this.commonDbService.deleteData({feature:"reaction",properties:{id:e,documentId:a,organizationId:l},extraData:s})}catch(i){this.loggingService.catch("Error in ReactionService deleteReactionPinAnnotation: ",i)}})}setCustomReactions(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;"),this.customReactions$.next(e),this.emojiService.setEmojiList(e)}catch(t){this.loggingService.catch("Error in ReactionService setCustomReactions: ",t)}}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in ReactionService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in ReactionService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}sanitizeReactionAnnotation(e){try{e&&(e.iconUrl&&(e.iconUrl=this.domService.sanitizeHtml(e.iconUrl)),e.iconEmoji&&(e.iconEmoji=this.domService.sanitizeHtml(e.iconEmoji)),e.icon&&(e.icon=this.domService.sanitizeHtml(e.icon)))}catch(t){this.loggingService.catch("Error in ReactionService sanitizeReactionAnnotation: ",t)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getReactionAnnotationForClient(e){try{let t=["isReactionResolverUsed","pageInfo","from","involvedUserIds","position"],i=JSON.parse(JSON.stringify(e)),a={};return Object.keys(i).forEach(l=>{t.includes(l)||(l==="reactions"?a.fromUsers=i[l]:a[l]=i[l])}),a}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationForClient: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(lt),X(We),X(Ft),X($n),X(Tn),X(ct),X(Be),X(vv),X(Ln),X(x),X(il))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tg={user:"componentConfigSignal.appState.user",isUserAdmin:"componentConfigSignal.appState.isUserAdmin",isKnownUser:"componentConfigSignal.appState.isKnownUser",repliesUniqueUsers:"componentConfigSignal.appState.repliesUniqueUsers",annotation:"componentConfigSignal.data.annotation",annotations:"componentConfigSignal.data.annotations",allAnnotations:"componentConfigSignal.data.allAnnotations",ghostComment:"componentConfigSignal.data.ghostComment",selectedFiles:"parentLocalUIState.selectedFiles",invalidSelectedFiles:"parentLocalUIState.invalidSelectedFiles",selectedAttachments:"parentLocalUIState.selectedAttachments",editComment:"parentLocalUIState.editComment",editCommentIndex:"parentLocalUIState.editCommentIndex",assignTo:"componentConfigSignal.data.assignTo",selectedUserContacts:"componentConfigSignal.data.selectedUserContacts",localRecordedData:"parentLocalUIState.localRecordedData",customList:"componentConfigSignal.data.customList",toOrganizationUserGroup:"componentConfigSignal.data.toOrganizationUserGroup",taggedUserContacts:"componentConfigSignal.data.taggedUserContacts",taggedGroups:"componentConfigSignal.data.taggedGroups",attachmentsToDelete:"parentLocalUIState.attachmentsToDelete",customChipData:"componentConfigSignal.data.customChipData",selectedCustomChipSet:"componentConfigSignal.data.selectedCustomChipSet",currentDialogView:"componentConfigSignal.data.currentDialogView",sidebarMode:"parentLocalUIState.sidebarMode",inboxMode:"parentLocalUIState.inboxMode",dialogMode:"parentLocalUIState.dialogMode",inlineCommentMode:"parentLocalUIState.inlineCommentMode",inlineCommentSectionMode:"parentLocalUIState.inlineCommentSectionMode",focusedThreadMode:"parentLocalUIState.focusedThreadMode",isFocusedThreadEnabled:"parentLocalUIState.isFocusedThreadEnabled",pageModeComposer:"parentLocalUIState.pageModeComposer",darkMode:"parentLocalUIState.darkMode",variant:"parentLocalUIState.variant",disabled:"parentLocalUIState.disabled",commentPinSelected:"parentLocalUIState.commentPinSelected",fullExpanded:"parentLocalUIState.fullExpanded",commentDialogSelected:"parentLocalUIState.commentDialogSelected",readOnly:"parentLocalUIState.readOnly",dialogShadowDOM:"parentLocalUIState.dialogShadowDOM",locationVersion:"parentLocalUIState.locationVersion",composerPosition:"parentLocalUIState.composerPosition",dialogOpenedInSidebar:"parentLocalUIState.dialogOpenedInSidebar",expandOnSelection:"parentLocalUIState.expandOnSelection",selectedVisibility:"parentLocalUIState.selectedVisibility",selectedVisibilityUsers:"parentLocalUIState.selectedVisibilityUsers",containerComponentId:"componentConfigSignal.uiState.containerComponentId",isPrivateComment:"componentConfigSignal.uiState.isPrivateComment",assignToMenuOpened:"parentLocalUIState.assignToMenuOpened",showGhostCommentMessage:"componentConfigSignal.uiState.showGhostCommentMessage",showReplies:"componentConfigSignal.uiState.showReplies",collapsedComments:"componentConfigSignal.uiState.collapsedComments",showAllComments:"componentConfigSignal.uiState.showAllComments",composerContent:"parentLocalUIState.composerContent",composerContentHTML:"parentLocalUIState.composerContentHTML",composerInOpenState:"parentLocalUIState.composerInOpenState",composerMode:"componentConfigSignal.uiState.composerMode",multiThreadAnnotationId:"componentConfigSignal.uiState.multiThreadAnnotationId",maxReplyAvatars:"componentConfigSignal.uiState.maxReplyAvatars",showSuggestionModeActions:"componentConfigSignal.uiState.showSuggestionModeActions",uploadingAttachments:"componentConfigSignal.uiState.uploadingAttachments",playVideoInFullScreen:"componentConfigSignal.uiState.playVideoInFullScreen",commentDialogUniqueId:"componentConfigSignal.uiState.commentDialogUniqueId",recorderInitConfig:"componentConfigSignal.uiState.recorderInitConfig",isInputFocused:"componentConfigSignal.uiState.isInputFocused",showCommentButtons:"componentConfigSignal.uiState.showCommentButtons",isAutocompleteDropdownOpen:"componentConfigSignal.uiState.isAutocompleteDropdownOpen",bottomSheetMode:"componentConfigSignal.uiState.bottomSheetMode",commentComposerMode:"componentConfigSignal.uiState.commentComposerMode",shouldScrollToBottom:"componentConfigSignal.uiState.shouldScrollToBottom",deviceType:"componentConfigSignal.uiState.deviceType",showReplyComposer:"componentConfigSignal.uiState.showReplyComposer",reactionToolOpenIndex:"componentConfigSignal.uiState.reactionToolOpenIndex",openDropdownIndexValue:"componentConfigSignal.uiState.openDropdownIndexValue",hasReactionsByCommentId:"componentConfigSignal.uiState.hasReactionsByCommentId",newComment:"parentLocalUIState.composerContent",newCommentHTML:"parentLocalUIState.composerContentHTML",canResolveAnnotation:"componentConfigSignal.featureState.canResolveAnnotation",canUnresolveAnnotation:"componentConfigSignal.featureState.canUnresolveAnnotation",dialogSelectedByKnownUser:"componentConfigSignal.featureState.dialogSelectedByKnownUser",resolveStatusAccessAdminOnly:"componentConfigSignal.featureState.resolveStatusAccessAdminOnly",enableResolve:"componentConfigSignal.featureState.enableResolve",isPlanExpired:"componentConfigSignal.featureState.isPlanExpired",moderatorMode:"componentConfigSignal.featureState.moderatorMode",enableAutoCategorize:"componentConfigSignal.featureState.enableAutoCategorize",suggestionMode:"componentConfigSignal.featureState.suggestionMode",commentAcceptedStatus:"componentConfigSignal.featureState.commentAcceptedStatus",commentRejectedStatus:"componentConfigSignal.featureState.commentRejectedStatus",enableSignInButton:"componentConfigSignal.featureState.enableSignInButton",enableUpgradeButton:"componentConfigSignal.featureState.enableUpgradeButton",enableGhostCommentsMessage:"componentConfigSignal.featureState.enableGhostCommentsMessage",replyAvatars:"componentConfigSignal.featureState.replyAvatars",userMentions:"componentConfigSignal.featureState.userMentions",recordingSummaryEnabled:"componentConfigSignal.featureState.recordingSummaryEnabled",enableAttachment:"componentConfigSignal.featureState.enableAttachment",allowedFileTypes:"componentConfigSignal.featureState.allowedFileTypes",allowedRecordings:"componentConfigSignal.featureState.allowedRecordings",screenSharingSupported:"componentConfigSignal.featureState.screenSharingSupported",enterKeyToSubmit:"componentConfigSignal.featureState.enterKeyToSubmit",deleteOnBackspace:"componentConfigSignal.featureState.deleteOnBackspace",showScreenSizeInfo:"componentConfigSignal.uiState.showScreenSizeInfo",enableReactions:"componentConfigSignal.featureState.enableReactions",isInsidePdfViewer:"componentConfigSignal.featureState.isInsidePdfViewer",sidebarButtonOnCommentDialogVisible:"componentConfigSignal.uiState.sidebarButtonOnCommentDialogVisible",enableStatus:"componentConfigSignal.featureState.enableStatus",customStatusesShown:"componentConfigSignal.featureState.customStatusesShown",statusOptions:"componentConfigSignal.featureState.statusOptions",enablePriority:"componentConfigSignal.featureState.enablePriority",visibilityOptions:"componentConfigSignal.featureState.visibilityOptions",priorityOptions:"componentConfigSignal.featureState.priorityOptions",enableAssignment:"componentConfigSignal.featureState.enableAssignment",enableNotifications:"componentConfigSignal.featureState.enableNotifications",enableEdit:"componentConfigSignal.featureState.enableEdit",enableDelete:"componentConfigSignal.featureState.enableDelete",enablePrivateMode:"componentConfigSignal.featureState.enablePrivateMode",deleteThreadWithFirstComment:"componentConfigSignal.featureState.deleteThreadWithFirstComment",seenByUsers:"componentConfigSignal.featureState.seenByUsers",allowAssignment:"componentConfigSignal.featureState.enableAssignment",allowToggleNotification:"componentConfigSignal.featureState.enableNotifications",allowEdit:"componentConfigSignal.featureState.enableEdit",allowChangeCommentAccessMode:"componentConfigSignal.featureState.enablePrivateMode",notificationEnabled:"notificationEnabled",mainCommentId:"componentConfigSignal.data.annotation.comments.0.commentId",commentObj:"commentObj",commentIndex:"commentIndex",userContact:"selectorItem.contact",comment:"commentObj",commentAnnotation:"componentConfigSignal.data.annotation",commentAnnotations:"componentConfigSignal.data.annotations",context:"parentLocalUIState.context",focusedAnnotation:"focusedAnnotation",notification:"notification",notificationsPanel:"notificationsPanel",selectedMinimalFilterDropdownOption:"selectedMinimalFilterDropdownOption",appliedFiltersCount:"appliedFiltersCount",filteredCommentAnnotationsCount:"filteredCommentAnnotationsCount",unreadCommentAnnotationCount:"unreadCommentAnnotationCount"},FWe=["user","annotation","annotations","allAnnotations","userContact","comment","commentAnnotation","commentAnnotations","recorderInitConfig","ghostComment","editComment","assignTo","customChipData","currentDialogView","context","focusedAnnotation","notification","notificationsPanel","selectedMinimalFilterDropdownOption"],I=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(n,o,r,e,t,i){this.authService=n,this.commentService=o,this.loggingService=r,this.injector=e,this.docService=t,this.configService=i,this.subscriptions=[],this.commonData$=new Se({}),this.evaluateConditionTriggered=new Le,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=Ae({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(k(f({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(f(f({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(l=>(l=f(f({},l),a),l)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(n=>n.unsubscribe())}catch(n){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",n)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(n,o){try{return Object.keys(o).forEach(r=>{o[r].path=this.modifyPathBasedOnCondition(r,n)}),o}catch(r){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",r)}}getComputedValues(n,o,r,e,t,i){try{Object.keys(r).forEach(a=>{let l;if(lo(n)?l=ce(()=>Cl(n(),r[a].path)):l=ce(()=>Cl(n,r[a].path)),lo(l()))On(()=>{try{let s=l()();r[a].value=s,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}catch{}},{injector:this.injector,allowSignalWrites:!0});else{let s=l();r[a].value=s,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(n,o){try{let r=n.match(/^([^\.\[]+)/),e=r?r[1]:n,t=n.slice(e.length);if(Tg[n])return Tg[n];if(["commentDialogOptionsDropdownConfigSignal","commentDialogStatusDropdownConfigSignal"].includes(e)&&t.startsWith(".")){let a=t.slice(1),l=a.match(/^([^\.\[]+)/),s=l?l[1]:a,d=a.slice(s.length);return Tg[s]?Tg[s]+d:"componentConfigSignal."+a}if(e&&o&&typeof o=="function"){let a=o();if(a&&e in a){let s=n.match(/\[(.*?)\]/);if(s&&s[1]){let d=s[1];if(d.includes(".")){let g=d.split(".")[0];if(Tg[g]){let u=d.replace(g,Tg[g]);return n.replace(`[${d}]`,`[${u}]`)}return g&&a&&g in a?n:n.replace(`[${d}]`,`[componentConfigSignal.${d}]`)}}return n}let l=a?.componentConfigSignal;if(l&&typeof l=="function"){let s=l();if(s&&e in s)return"componentConfigSignal."+n}}return Tg[e]?FWe.includes(e)?Tg[e]+t:Tg[e]:"componentConfigSignal."+n}catch(r){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",r),n}}applyConditionalClasses(n,o){try{this.elementRef=n,this.data=o}catch(r){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",r)}}executeConditionalClasses(){try{let n=this.getHostElementAttributes(this.elementRef),r=[...Object.keys(n).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:n[e]}))];if(n["velt-class"]){let e=n["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,i=[],a=0,l=100,s;for(;(s=t.exec(e))!==null;){if(a++>l){this.loggingService.catch("Too many class definitions detected.");break}if(s.length<3)continue;let[,d,g]=s;!d||!g||d.split(" ").forEach(u=>{u.trim()&&i.push({name:`velt-class-${u.trim()}`,value:g.trim()})})}r=[...r,...i]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),r.forEach(e=>{let t=e.name.replace("velt-class-","");this.condition=e.value,this.condition&&(this.extractProps(),this.extractedProps=this.getModifiedPathBasedOnCondition(this.dataComponentConfigSignal,this.extractedProps),this.getComputedValues(this.dataComponentConfigSignal,this.evaluateCondition,this.extractedProps,t,this.elementRef,e.value))})}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}updateDataComponentConfigSignal(n,o){try{n==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(r=>k(f({},r),{[n]:o}))}catch(r){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",r)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let n;for(;(n=this.conditionRegex.exec(this.condition))!==null;){let o=n[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(n){this.loggingService.catch("Error in DynamicDataService extractProps: ",n)}}hasDynamicParts(n){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(n),r=/\[[^[\]]*[\.\[][^[\]]*\]/.test(n);return o||r}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(n,o,r){try{if(r){let e=this.extractedProps,t=r.replace(this.conditionRegex,(l,s)=>{let d=e[s];if(d&&d.value!==void 0){let g=d.value;return typeof g=="string"?`'${g}'`:typeof g=="boolean"||typeof g=="number"?String(g):g===null?"null":typeof g=="object"?g?"true":"false":String(g)}return"false"}),i=this.sanitizeCondition(t),a=this.safeEval(i);return n&&o&&(a?this.setHostElementClasses(o,n):this.removeHostElementClasses(o,n)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(n){try{return n.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let n=this.tokenize(expression.trim());return this.evaluateTokens(n)}else return eval(expression)}catch(n){return this.loggingService.catch("safeEval error",n),!1}}tokenize(n){try{if(!n||n.trim()==="")return[];let o=[],r=0;for(;r<n.length;){let e=n[r];if(/\s/.test(e)){r++;continue}if(e==='"'||e==="'"){let t=e,i="";for(r++;r<n.length;)if(n[r]==="\\"&&r+1<n.length)i+=n[r+1],r+=2;else if(n[r]===t){r++;break}else i+=n[r],r++;o.push({type:"string",value:i});continue}if(e==="("){o.push({type:"lparen",value:"("}),r++;continue}if(e===")"){o.push({type:"rparen",value:")"}),r++;continue}if(r<n.length-2&&n.substring(r,r+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),r+=3;continue}if(r<n.length-2&&n.substring(r,r+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),r+=3;continue}if(r<n.length-1&&n.substring(r,r+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)===">="){o.push({type:"operator",value:">=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),r+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),r++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),r++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),r++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;r<n.length&&/[a-zA-Z0-9._]/.test(n[r]);)t+=n[r],r++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}r++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(n){try{if(!n||n.length===0)return!1;let o=this.infixToPostfix(n);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(n){try{let o=[],r=[];for(let e of n)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")r.push(e);else if(e.type==="operator"){for(;r.length>0;){let t=r[r.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(r.pop())}r.push(e)}else if(e.type==="lparen")r.push(e);else if(e.type==="rparen"){for(;r.length>0&&r[r.length-1].type!=="lparen";)o.push(r.pop());r.length>0&&r.pop()}for(;r.length>0;){let e=r.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(n){try{let o=[];for(let r of n)if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="null"||r.type==="undefined"||r.type==="identifier")o.push(r.value);else if(r.type==="unary"){if(o.length>=1){let e=o.pop();r.value==="!"&&o.push(!this.isTruthy(e))}}else if(r.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();r.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):r.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,r.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(n){try{let o=n.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),n}}compare(n,o,r){try{switch(r){case"===":return n===o;case"!==":return n!==o;case"==":return n==o;case"!=":return n!=o;case"<":return n<o;case">":return n>o;case"<=":return n<=o;case">=":return n>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(n){try{return n==null||n===""||n==="false"?!1:n==="true"?!0:typeof n=="number"?n!==0:!!n}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(n){try{let o=n,r={};for(let e of o.attributes)r[e.name]=e.value;return r}catch{return{}}}setHostElementClasses(n,o){try{n.classList.add(o)}catch{}}removeHostElementClasses(n,o){try{n.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(X(We),X(Pe),X(x),X(Ot),X(ct),X(Ft))},_DynamicDataService.\u0275prov=Me({token:_DynamicDataService,factory:_DynamicDataService.\u0275fac,providedIn:"root"});let DynamicDataService=_DynamicDataService;return DynamicDataService})();var oe=(()=>{let o=class o{set veltIf(e){try{e&&this.setIfCondition(e)}catch(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,i){this._elementRef=e,this._dynamicDataService=t,this._loggingService=i,this.componentConfigSignal=Ae({}),this.veltElement=!0,this.conditionSignal=Ae(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}ngOnInit(){try{this._dynamicDataService.applyConditionalClasses(this._elementRef?.nativeElement,{componentConfigSignal:this.componentConfigSignal})}catch(e){this._loggingService.catch("Error in BaseComponent ngOnInit:",e)}}ngOnDestroy(){}setIfCondition(e){try{this.conditionSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(y(Z),y(I),y(x))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,i){},encapsulation:2});let n=o;return n})();var _t=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.configService=t,this.darkMode$=new Se(!1)}setDarkMode(e){try{let t=document.documentElement;if(!t)return;e?t.setAttribute(U.ATTRIBUTES.VELT_THEME,"dark"):t.removeAttribute(U.ATTRIBUTES.VELT_THEME),this.darkMode$.next(e)}catch(t){this.loggingService.catch("Error in theme service setDarkMode: ",t)}}getDarkMode$(){return this.darkMode$.asObservable()}updateListenerOnConfigChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.usePrefersColorScheme){this.enablePrefersColorScheme();return}this.disablePrefersColorScheme()})}catch(e){this.loggingService.catch("Error in theme service updateListenerOnConfigChange: ",e)}}enablePrefersColorScheme(){try{if(this.disablePrefersColorScheme(),!window.matchMedia)return;this.darkModeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.setDarkMode(this.darkModeQuery.matches),this.darkModeQueryListener=e=>{this.setDarkMode(e.matches)},this.darkModeQuery.addEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service enablePrefersColorScheme: ",e)}}disablePrefersColorScheme(){try{this.darkModeQuery&&this.darkModeQueryListener&&this.darkModeQuery.removeEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service disablePrefersColorScheme: ",e)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(Ft))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wt=(()=>{let o=class o extends oe{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,i,a,l,s,d){super(e,s,d),this._elementRef=e,this._themeService=t,this._changeDetector=i,this._featureService=a,this._componentDarkModeObservable=l,this._componentDarkMode=null,this._globalDarkMode=!1,this._featureDarkMode=!1,this._themeSubscriptions=[],this._darkMode=!1,this.darkMode=!1,this.darkModeSubject$=new Se(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(g=>{this._globalDarkMode=g,this.setDarkMode()})),this._featureService&&(this._featureService instanceof Pe?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(g=>{this._featureDarkMode=g,this.setDarkMode()})):this._featureService instanceof Hi&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(g=>{g!==null&&(this._featureDarkMode=g),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Gt&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(g=>{this._componentDarkMode=g,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,this.setDarkMode()}}catch{}}setComponentDarkMode(e){try{this._componentDarkMode=e,this.setDarkMode()}catch{}}setDarkMode(){try{this._componentDarkMode===null?this._featureDarkMode?this.darkMode=!0:this.darkMode=!!this._globalDarkMode:this.darkMode=!!this._componentDarkMode,this.darkMode?this._elementRef.nativeElement.hasAttribute("dark")||this._elementRef.nativeElement.setAttribute("dark",""):this._elementRef.nativeElement.hasAttribute("dark")&&this._elementRef.nativeElement.removeAttribute("dark"),this.darkModeSubject$.next(this.darkMode),this._changeDetector&&this._changeDetector.markForCheck()}catch{}}ngOnDestroy(){try{super.ngOnDestroy(),this._themeSubscriptions.forEach(e=>{e.unsubscribe()})}catch{}}};o.\u0275fac=function(t){return new(t||o)(y(Z),y(_t),y(Qt),y("FeatureService",8),y(Gt),y(I),y(x))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[P,st],decls:0,vars:0,template:function(t,i){},encapsulation:2,changeDetection:0});let n=o;return n})();var Ze=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new Se(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let i=this.wireframeMap.value,a=i.get(e),l=t.children.length>0||t.innerHTML?.trim()?.length>0,s=a&&(a.children.length>0||a.innerHTML?.trim()?.length>0);(!a||l&&!s)&&(i.set(e,t),this.wireframeMap.next(i))}catch(i){this.loggingService.catch("Error in WireframeService setWireframe: ",i)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((i,a)=>{let l=t.get(a),s=i.children.length>0||i.innerHTML?.trim()?.length>0,d=l&&(l.children.length>0||l.innerHTML?.trim()?.length>0);(!l||s&&!d)&&t.set(a,i)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a&&(a?.children?.length>0||a?.innerHTML?.trim()?.length>0)?a:void 0}catch(i){this.loggingService.catch("Error in WireframeService getWireframe: ",i);return}}getConditionElement(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a}catch(i){this.loggingService.catch("Error in WireframeService getConditionElement: ",i);return}}getWireframe$(e,t=!0){return this.wireframeMap.asObservable().pipe(ue(i=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var L_e=n=>({componentConfigSignal:n}),LWe=(n,o)=>({condition:n,data:o}),UWe=(n,o,r,e,t)=>({template:n,context:o,componentName:"velt-confirm-dialog-wireframe",variant:r,setIfCondition:e,componentElementRef:t});function VWe(n,o){if(n&1&&(C(0),D(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),h(3,"div",6),D(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),S(),_()),n&2){let r=c(3);m(),v("componentConfigSignal",r.componentConfigSignal),m(),v("componentConfigSignal",r.componentConfigSignal),m(2),v("componentConfigSignal",r.componentConfigSignal),m(),v("componentConfigSignal",r.componentConfigSignal)}}function BWe(n,o){if(n&1&&(C(0),p(1,VWe,6,4,"ng-container",4),_()),n&2){let r=c().ngIf,e=c();m(),v("veltDynamicTemplate",j(3,UWe,e.template,G(1,L_e,e.componentConfigSignal),r==null?null:r.variant,e.setIfCondition.bind(e),e.elementRef))}}function jWe(n,o){if(n&1&&(C(0),p(1,BWe,2,9,"ng-container",3),_()),n&2){let r=c();m(),v("veltIf",w(3,LWe,r.conditionSignal(),G(1,L_e,r.componentConfigSignal)))}}var xl=(()=>{let o=class o extends wt{constructor(e,t,i,a,l,s,d){super(l,a,void 0,void 0,void 0,d,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=i,this.themeService=a,this.elementRef=l,this.dynamicDataService=d,this.subscriptions=[],this.componentConfigSignal=Ae({title:"",message:"",yesButton:"",noButton:"",variant:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{s&&(this.componentConfigSignal.update(g=>(g=f(f({},g),s),g)),s?.darkMode&&[!0,!1].includes(s?.darkMode)&&super.setComponentDarkMode(s?.darkMode)),this.setZIndex()}catch(g){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",g)}}ngOnInit(){try{this.loggingService.log("%c[WB] Calling FUNCTION: ngOnInit","color: green;");let e="velt-confirm-dialog-wireframe";super.ngOnInit(),this.componentConfigSignal()?.variant&&(e+=`---${this.componentConfigSignal()?.variant}`),this.subscriptions.push(this.wireframeService.getWireframe$(e).subscribe(t=>{if(t){let i=document.createElement(t.tagName);i.innerHTML=t.innerHTML,this.template=i}}))}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnInit: ",e)}}ngOnDestroy(){super.ngOnDestroy();try{this.subscriptions.forEach(e=>e.unsubscribe())}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnDestroy: ",e)}}setZIndex(){try{if(this.dialogRef){let e=this.dialogRef._overlayRef;e&&(e.backdropElement&&(e.backdropElement.style.zIndex="2147483647"),e.hostElement&&(e.hostElement.style.zIndex="2147483647"))}}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent setZIndex: ",e)}}closeDialog(e){try{this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}};o.\u0275fac=function(t){return new(t||o)(y(x),y(Vi),y(Ze),y(_t),y(Z),y(Yc,8),y(I))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},standalone:!1,features:[B([I]),P],decls:3,vars:5,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,i){if(t&1&&(h(0,"div",1,0),p(2,jWe,2,6,"ng-container",2),S()),t&2){let a=Ie(1);v("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),T("data-testid",i.componentId),m(2),v("ngIf",i.componentConfigSignal())}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%] *[_ngcontent-%COMP%]{outline:0}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)}.velt-confirm-dialog[_ngcontent-%COMP%]{width:455px;padding:40px;display:block;box-sizing:border-box;background-color:var(--velt-background-0)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface:has(snippyly-confirm-dialog){border-radius:var(--velt-border-radius-xl);padding:0}@media (max-width: 768px){.velt-confirm-dialog[_ngcontent-%COMP%]{width:auto;max-width:455px;padding:24px}}"],changeDetection:0});let n=o;return n})();var xn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M,V,q,ae,fe,ie,Ce){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.commonDbService=l,this.commonDbUtilsService=s,this.commentUtilsService=d,this.commentAnnotationsResolverService=g,this.notificationResolverService=u,this.databaseService=b,this.docService=E,this.domService=A,this.iamService=M,this.loggingService=V,this.notificationUtilsService=q,this.usersService=ae,this.functions=fe,this.userPermissionService=ie,this.coreActionsService=Ce,this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new Se([]),this.rawNotificationsByIdMap$=new Se(new Map),this.processedNotifications$=new Se([]),this.userNotificationsFromServer$=new Se(null),this.readNotificationsOnForYouTab$=new Se(!1),this.currentDocumentOnly$=new Se(!1),this.notificationViews$=new Se({}),this.notificationsByIdMap$=new Se(new Map),this.historyPanelVisible$=new Se(!1),this.notificationsForYou$=new Se(null),this.notificationsByDocumentIdMap$=new Se(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new Se(null),this.maxNotificationDays$=new Se(15),this.tabConfig$=new Se({people:{enable:!1}}),this.settingsConfig$=new Se(null),this.setSettingsConfigByOrganization$=new Se(!1),this.muteAllNotifications$=new Se(!1),this.enableSettings$=new Se(!1),this.selfNotifications$=new Se(!1),this.settingsInitialConfig$=new Se([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new Se(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe($e(xe=>!!xe),ut(1)).subscribe(xe=>{if(xe){this.db=xe;try{let ke=this.configService.getProxyConfig(),ye=En.firebaseNotificationsDatabaseURL;ke?.v1DbHost&&ye&&(ye=kN(ye,ke.v1DbHost)),this.notificationsDb=x1(void 0,ye),ke?.v1DbHost&&ye&&this.databaseService.lockDatabaseHost(this.notificationsDb)}catch(ke){this.loggingService.catch("Error initializing notifications DB, using default: ",ke),this.notificationsDb=xe}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},xe=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",xe)}),this.authService.getUser$().subscribe(xe=>{xe?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(ke=>{this.notificationsByDocumentIdSubscription[ke]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(xe=>{if(xe){let ke=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(xe||{}).forEach(ye=>{let Oe=ke?.[ye]?.notifications;Oe?.length&&Oe.forEach(Ne=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Ne},xe)?.notification})}),this.notificationsByDocumentIdMap$.next(ke)}})}catch(xe){this.loggingService.catch("Error in NotificationService constructor: ",xe)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([i,a])=>{t[i]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=++this.settingsConfigGeneration,i=It(this.authService.getUser()?.userId??""),a=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:e?.documentId,organizationId:e?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:i}});if(t!==this.settingsConfigGeneration)return;if(a?.notificationsConfig)this.setDBConfigDataToInitialConfig(a?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let l={};this.settingsInitialConfig$.getValue().forEach(d=>{if(d.enable){let g=d?.values?.find(u=>u.id===d.default);l[d.id]=g||d?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(l).forEach(d=>{s[d]=l[d].id}),yield this.updateSettingsConfigToDb(s)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=It(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe($e(t=>t===!0),_e(()=>pn([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe($e(([t,i,a])=>(i||!!t)&&!!a?.organizationId),_e(([t,i,a])=>po(this.getInitialConfigFromDB(t)).pipe(_e(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?void 0:t?.documentId,organizationId:t?.organizationId??a?.organizationId,userId:e}}).pipe(ue(l=>{l?.data?.notificationsConfig&&!Mr(l?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(l?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.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(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(_e(()=>this.getCurrentDocumentOnly$().pipe(_e(e=>e?this.docService.getDocumentPaths$().pipe(ue(t=>{})):le(void 0)))),on(()=>{this.notificationsByDocumentIdMap$.next(null)}),_e(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Nr(),ue(([e,t])=>{let i=e?.map(g=>g.documentId),a=t?.map(g=>g.documentId),l=i?.filter(g=>!a?.includes(g)),s=a?.map(g=>({documentId:g,timestamp:t?.find(u=>u.documentId===g)?.timestamp})).filter(g=>!i?.includes(g.documentId)),d=a?.map(g=>{let u=t?.find(b=>b.documentId===g)?.timestamp;return{documentId:g,timestamp:u}}).filter(g=>{let u=e?.find(b=>b.documentId===g.documentId)?.timestamp;return u&&g.timestamp&&u!==g.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),d?.length&&this.fetchNotificationsForDocumentIds(d,1),l?.forEach(g=>{this.removeNotificationsForDocumentId(g)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).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(_e(t=>this.docService.getOrganizationConfig$().pipe(ue(i=>{let a=null,l=this.configService.getApiKey(),s=i?.organizationId||t?.organizationId;return l&&s&&(a=new dv({apiKey:l,organizationId:s})),{user:t,documentPaths:a}}))),_e(t=>{let{user:i,documentPaths:a}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return le(null);if(i&&a?.organizationNotificationsLastNotificationTimestamp){let l=new Date,s=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;l.setDate(l.getDate()-s);let d=l.getTime(),g=[_r(ft("timestamp",">=",d),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ft("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];return this.getCurrentDocumentOnly()||(g.push(vo("timestamp","desc")),g.push(lv(e))),this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:g}}).pipe(ue(u=>u?.data),ue(u=>{let b=[];return Object.keys(u||{}).forEach(E=>{let A=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],M=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(M&&M.id&&M?.timestamp===A){let V=M.id,q=u[E]?.metadata?.documentId,ae=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),fe=ae?.[q]??{documentMetadata:null,notifications:[]},ie=fe.notifications??[],Ce=ie?.findIndex(xe=>xe.id===V);Ce!==-1&&(ie.splice(Ce,1),this.notificationsByDocumentIdMap$.next(k(f({},ae),{[q]:k(f({},fe),{notifications:ie})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(V)&&this.notificationResolverService.deleteNotification(V,this.docService.getDocumentPaths()?.clientOrganizationId??"")}b.push({documentId:E,timestamp:A})}),b}),Jn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),le([]))))}return le(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),le([])}}resolveAndUpdateDocumentNotifications(e,t){try{Object.keys(e).forEach(i=>{let a=e[i]?.documentMetadata||{},l;if(t==="user")l=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:e[i]?.notifications||[]});else if(t==="notification"){let s=e[i]?.notifications?.reduce((g,u)=>(g[u.notificationId]=u,g),{}),d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:s});l=Object.values(d??{})}else{let s=e[i]?.notifications?.reduce((g,u)=>(g[u.notificationId]=u,g),{}),d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:s});l=Object.values(d??{})}l.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),this.setNotificationForDocumentIdInCache(i,a,l)})}catch(i){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",i)}}resolveAndMergeUserNotifications(e,t,i=!1){try{let a=e;if(i&&t==="comment"){let u=this.getUserNotificationsFromServer()??[],b=new Set(e.map(E=>E.notificationId));a=u.filter(E=>b.has(E.notificationId)).concat(e.filter(E=>!u.some(A=>A.notificationId===E.notificationId)))}let l=a.reduce((u,b)=>(u[b.notificationId]=b,u),{}),s;if(t==="user"){let u=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}else if(t==="notification"){let u=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}else{let u=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l});s=Object.values(u??{})}s.forEach(u=>{u.notification=this.getClientNotificationObject(u)});let d=this.getUserNotificationsFromServer()??[],g=new Map(d.map(u=>[u.notificationId,u]));s.forEach(u=>{g.set(u.notificationId,u)}),this.setUserNotificationsFromServer(Array.from(g.values()))}catch(a){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",a)}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let i=Gr(this.functions,Wr({url:En.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let l=this.getStartAtTimestamp(),s={};if(e.forEach(ie=>{if(ie?.documentId){let Ce=this.getAllowedDocumentMetadataByDocumentId(ie.documentId);Ce&&(s[ie.documentId]=Ce)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let ie=[];if(e.forEach(Oe=>{this.docService.getDocumentMetadata(Oe.documentId)||ie.push(Oe.documentId)}),ie.length){let Oe=this.authService.getUser(),Ne=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let Ue=yield _l({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Oe?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:ie},getSdkProxy:Ne,userId:Oe?.userId??""});if(Ue?.data?.length){let ze={};Ue.data.forEach(Ge=>{Ge?.documentId&&(ze[Ge.documentId]=Ge)}),this.docService.setAllDocumentMetadata(f(f({},this.docService.getAllDocumentMetadataMap()),ze))}}catch(Ue){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",Ue)}}let Ce=[],xe=[];e.forEach(Oe=>{let Ne=this.docService.getDocumentMetadata(Oe.documentId);Ne?.clientDocumentId?Ce.push({userId:this.authService.getUser()?.userId??"",resource:{id:Ne.clientDocumentId,type:oa.DOCUMENT,source:ro.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):xe.push(Oe.documentId)}),xe.length&&(e=e.filter(Oe=>!xe.includes(Oe.documentId)));let ke=ot();this.coreActionsService.triggerAction(Qe.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ke,methodName:ro.GET_NOTIFICATIONS,source:"internal",payload:{requests:Ce}});let ye=yield this.userPermissionService?.onResourceAccessRequired({requests:Ce,uniqueId:ke,methodName:ro.GET_NOTIFICATIONS});ye?.success&&ye?.data?.length?ye.data.forEach(Oe=>{!Oe.hasAccess&&Oe.resourceId&&(e=e.filter(Ne=>Ne.documentId!==mi(Oe.resourceId)))}):e=[]}catch(ie){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",ie),e=[]}if(!e.length)return[];let d=this.userPermissionService?.getPermissionsCache()?.filter(ie=>ie.type===oa.CONTEXT),g={organizationId:a,documentIds:e.filter(ie=>!!ie.documentId&&!!ie.timestamp).map(ie=>({documentId:ie.documentId,timestamp:ie.timestamp??0})),timestamp:l,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:d,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},u=yield this.notificationUtilsService.handleNotificationEncryption({data:g}),b=yield i({veltData:u}),E=b?.data?.data?.veltData||{},A=b?.data?.data?.veltAdditionalData||{},M="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),V=yield Q1(E,M),{userNotifications:q=[],userNotificationIdsInDocNotifications:ae=[],permissionResults:fe=[]}=yield Q1(A,M);if(this.userPermissionService?.getIsContextEnabled()){let ie=[...this.userPermissionService?.getPermissionsCache()??[],...fe??[]];this.userPermissionService?.setPermissionsCache(ie)}if(V&&typeof V=="object"){let ie=this.usersService.userDataProviderAvailable(),Ce=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),xe=this.notificationResolverService.notificationDataProviderAvailable(),ke=[],ye=[],Oe=[];Object.keys(V).forEach((ze,Ge)=>{let $r=V[ze].documentMetadata;if($r){let Tt=this.allowedDocumentMetadataMap$.value||{};(!Tt?.[ze]||!Mr(Tt?.[ze],$r))&&this.allowedDocumentMetadataMap$.next(k(f({},Tt),{[ze]:$r}))}let et=V[ze].notifications||[];et.forEach(Tt=>{ae.includes(Tt.notificationId)&&!q.find(Xe=>Xe.notificationId===Tt.notificationId)&&q.push(JSON.parse(JSON.stringify(Tt))),Tt.notification=this.getClientNotificationObject(Tt)}),this.setNotificationForDocumentIdInCache(ze,$r,et),ie&&(ke.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldAwait:!0,forceResolve:!0})),ke.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldAwait:!0,forceResolve:!0}))),Ce&&(ye.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldCommentAnnotationsResolverAwait:!0})),ye.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldCommentAnnotationsResolverAwait:!0}))),xe&&(Oe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:et,shouldNotificationResolverAwait:!0})),Oe.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldNotificationResolverAwait:!0})))});let Ne=JSON.parse(JSON.stringify(q));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...q]),(xe||ie||Ce)&&(()=>{let ze=Promise.resolve();if(xe&&(ze=ze.then(()=>Promise.allSettled(Oe)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"notification"),this.resolveAndMergeUserNotifications(Ne,"notification")})),ie&&(ze=ze.then(()=>Promise.allSettled(ke)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"user"),this.resolveAndMergeUserNotifications(Ne,"user")})),Ce){let Ge=xe||ie;ze=ze.then(()=>Promise.allSettled(ye)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"comment"),this.resolveAndMergeUserNotifications(Ne,"comment",Ge)})}return ze})().catch(ze=>{this.loggingService.catch("Error in NotificationService resolveChain: ",ze)})}}}catch(i){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t?.filter((i,a,l)=>a===l.findIndex(s=>s.notificationId===i.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,i,a){try{let l=this.docService.getOrganizationConfig()?.organizationId??"",s=this.docService.getOrganizationMetadata(l);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(l)||{})));let d=this.notificationsByDocumentIdMap$.getValue(),g=d?.[e]?.notifications||[],u=this.docService.getLocationMetadatas(),b=i?.map(M=>{let V=M?.notification;return V?(V.metadata&&(V.metadata.documentName=t?.documentName||V.metadata.documentName,V.metadata.organizationMetadata=s||V.metadata.organizationMetadata,V.metadata.documentMetadata=t||V.metadata.documentMetadata),u&&(V=this.notificationUtilsService.mergeLocationWithNotification({notification:V},u)?.notification),V):null})?.filter(M=>!!M)||[],E=new Map(g.map(M=>[M.id,M]));b.forEach(M=>{E.set(M.id,M)});let A=Array.from(E.values()).sort((M,V)=>(V.timestamp||0)-(M.timestamp||0));this.notificationsByDocumentIdMap$.next(k(f({},d),{[e]:{notifications:A,documentMetadata:t}}))}catch(l){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",l)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(_e(e=>le(e).pipe($e(t=>!!t),ue(t=>{let i=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),l=this.notificationResolverService?.notificationDataProviderAvailable();if(l||i||a){let d=t?.reduce((g,u)=>(g[u.notificationId]=u,g),{});l&&(d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:d||[]})),i&&(d=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:d||[]})),a&&(d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:d||[]})),t=Object.values(d??{})}return t.forEach(d=>{d.notification=this.getClientNotificationObject(d)}),t.sort((d,g)=>g.timestamp-d.timestamp),t.map(d=>d.notification).filter(d=>!!d)}),_e(t=>{let i={data:t?.reduce((a,l)=>(a[l.id]={notification:l},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:i,feature:"allUserNotifications"}).pipe(ue(a=>Object.values(a?.data||{}).map(l=>l?.notification)))}))),_e(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ue(()=>e))}),_e(e=>this.allowedDocumentMetadataMap$.pipe(ue(()=>e))),ue(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let i=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),l=this.docService.getOrganizationMetadata(i);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),l||(l=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(i)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=l||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),le(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),le({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let i,a;try{if(e&&(a=Qn(e)),t&&typeof t=="object"){let l=Oi(t);i=Qn(JSON.stringify(l))}}catch(l){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",l)}return fr(this.afAuth).pipe($e(l=>!!l),_e(l=>this.isFeatureAllowed({firebaseUser:l})),_e(l=>l.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(s=>(l.featureAllowed=s,l))):le(l)),_e(l=>!l.featureAllowed||l?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),le([])):le(l).pipe(_e(s=>this.docService.getDocumentPaths$().pipe(ue(d=>(this.documentPaths=d,s.documentPaths=d,s)))),_e(s=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.NOTIFICATION)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe($e(t=>!!t),_e(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let i=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(i+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=Ur(this.db,`${e?i+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return f8(a).pipe(Jn(l=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",l),le(null))),ue(l=>{let s=[],d=new Map;l?.raw&&(Object.keys(l?.raw||{}).forEach(u=>{let b=l?.raw[u];b?.id&&s.push(b)}),s.forEach(u=>{u.id&&d.set(u.id,u)})),this.notifications$.next(s),this.rawNotificationsByIdMap$.next(d);let g=[];l?.processed&&Object.keys(l?.processed||{}).forEach(u=>{let b=l?.processed[u];b?.id&&g.push(b)}),this.processedNotifications$.next(g),this.setNotificationsByIdMap()}))}else return le(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),i;e?.email&&(i=It(e?.email));let a;e?.userId&&(a=It(e?.userId));let l=new Map;this.processedNotifications$.getValue().forEach(d=>{if(d.id&&d?.displayHeadlineMessageTemplate){let g=!1;(i&&d.notifyUsers?.[i]||a&&d.notifyUsers?.[a])&&(g=!0);let u={id:d.id,notificationSource:d.notificationSource,actionType:d.actionType,actionUser:d.actionUser,timestamp:d.timestamp,targetAnnotationId:d.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(d),displayBodyMessage:this.getNotificationBodyMessage(d),forYou:g,notificationSourceData:d.notificationSourceData},b=this.getRawNotificationById(u.id);if(b?.metadata&&(u.metadata={apiKey:b.metadata.apiKey,organizationId:b.metadata.organizationId,clientOrganizationId:b.metadata.clientOrganizationId,documentId:b.metadata.documentId,clientDocumentId:b.metadata.clientDocumentId,location:b?.location,locationId:b?.locationId}),u?.notificationSource==="comment"&&u?.targetAnnotationId){let E=this.commentService?.getAnnotationById(u.targetAnnotationId);E||b?.annotationData&&(E=b.annotationData),E&&(u.notificationSourceData=this.commentService?.getCommentAnnotationForClient(E))}l.set(d.id,u)}}),l.forEach((d,g)=>{d.isUnread=d?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[g]?.views?.[e?.userSnippylyId],l.set(g,d)}),this.notificationsByIdMap$.next(l)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:i,views:a,notification:l}){try{let s=this.authService.getUser(),d=l||e;if(d.id&&d?.displayHeadlineMessageTemplate&&s){let g=null;s?.email&&(g=It(s?.email));let u=null;s?.userId&&(u=It(s?.userId));let b=!1,E=!0;(g&&d.notifyUsers?.[g]||u&&d.notifyUsersByUserId?.[u])&&(b=!0),u&&a?.[u]&&(E=!1);let A={id:d.id};if(l?A=k(f(f({},A),l),{displayHeadlineMessage:this.getNotificationHeadlineMessage(l),displayBodyMessage:this.getNotificationBodyMessage(l),forYou:b,isUnread:E}):A={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:b,isUnread:E,metadata:i},A?.notificationSource==="comment"&&A?.targetAnnotationId){let M=this.commentService?.getAnnotationById(A.targetAnnotationId);M||l?.notificationSourceData&&(M=l?.notificationSourceData),M||t?.annotationData&&(M=t.annotationData),M&&(A.notificationSourceData=this.commentService?.getCommentAnnotationForClient(M))}return t?.targetAnnotationData?.isCommentResolverUsed&&(A.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),l?.isNotificationResolverUsed&&(A.isNotificationResolverUsed=l.isNotificationResolverUsed),A}return}catch(s){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",s);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ue(e=>e?Object.keys(e??{}).map(t=>{let i=e[t].notifications||[],a=i.filter(s=>s.isUnread).length,l=i.length>0&&i[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:l,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,i)=>i.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ue(e=>{let t=null;return e?(t=[],e.forEach(i=>{i.notifications.forEach(a=>{t?.push(a)})}),t?.sort((i,a)=>a.timestamp-i.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,i=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.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(t?.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(i?this.docService.getOrganizationMetadata(i)||{}:{})),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 l=t?.documentId?new dv({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=l?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=l?.clientOrganizationId||e.actionUser.clientOrganizationId);let s=this.docService.getLocation();s&&(e.location=s?.location,e.locationId=s?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let d=this.commonDbService.getServerTimestamp(),g=this.notificationUtilsService.formatNotification(e,d);return JSON.parse(JSON.stringify(g))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{if(!this.notificationsDb)return;let t=Ur(this.notificationsDb),i=this.processNotificationData(e);s8(t,JSON.parse(JSON.stringify(i)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(_e(t=>t?t.organizationId?this.getAllNotifications$().pipe(_e(i=>this.notificationsForYou$.pipe(ue(a=>{if(i||a){let l=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(i||[]).forEach(s=>{s.id&&l.set(s.id,s)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(s=>{s.id&&!l.has(s.id)&&l.set(s.id,s)}),Array.from(l.values()).sort((s,d)=>(d.timestamp||0)-(s.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ue(i=>Array.from(i.values())),ue(i=>i.sort((a,l)=>l.timestamp-a.timestamp)),Vh()):le(null)),xt(Jt))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let i=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,l=/\{(\w+)\}/g,s=i.replace(l,(d,g)=>(g==="actionUser"||g==="recipientUser")&&a[g]?t?.email&&a[g].email===t?.email||t?.userId&&a[g]?.userId===t?.userId?"You":a[g].name||a[g].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[g]?a[g]:d);return this.domService.sanitizeHtml(s)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(i=>{if(i?.userId){let a=this.usersService.getUserById(i?.userId);t=t?.replaceAll(`{{${i.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${i.userId}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,i=!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(K.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(K.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,t=!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(K.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(K.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 Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(e?.length){for(let s=0;s<e.length;s+=50){let g=e.slice(s,s+50).filter(E=>E?.id),u=g.map(E=>this.setNotificationAsRead({notification:E,userNotifications:JSON.parse(JSON.stringify(t))})),b=yield Promise.all(u);g.forEach((E,A)=>{let M=b[A];if(!M.some(q=>q.notificationId===E.id))t=t.filter(q=>q.notificationId!==E.id);else{let q=t.find(fe=>fe.notificationId===E.id),ae=M.find(fe=>fe.notificationId===E.id);q&&ae?.views&&(q.views=ae.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(s=>{let d=s.metadata?.documentId;if(d&&a?.[d]){let g=a?.[d]?.notifications||[],u=g.find(b=>b.id===s.id);u&&(u.isUnread=!1),a[d].notifications=g}}),this.notificationsByDocumentIdMap$.next(a),!Mr(t,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(t)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return Q(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(ut(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ue(e=>e?.filter(i=>i?.isUnread)?.length??null),_e(e=>this.getNotifications$().pipe(ue(t=>{let i=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:i}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),le({forYou:null,all:null})}}setNotificationAsRead(i){return Q(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let l=It(a?.userId),{metadata:s}=e;if(s){let{apiKey:d,organizationId:g,documentId:u}=s;if(d&&g&&u&&l){let b=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:g,documentId:u,apiKey:d}});b?.notificationId&&(b?.views?.[l]||(b.views||(b.views={}),b.views[l]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:g,documentId:u,apiKey:d},data:b})));let E=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:g}});if(E?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:g}}),t=t.filter(A=>A.notificationId!==e.id);else if(!E?.views?.[l]){E.views||(E.views={}),E.views[l]={timestamp:Date.now()};let A=t.find(M=>M.notificationId===e.id);A&&(A.views=E.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:l,documentId:u,organizationId:g},data:E})}}}}}return t}catch(a){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",a),t}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}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}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",e)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",e)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(e){return Q(this,null,function*(){try{this.getNotifications$().pipe(ut(1)).subscribe(t=>{if(t){let i=t.filter(a=>a.id===e);this.setNotificationsAsRead(i)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",e)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",e)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(i=>{["email","inbox"].includes(i.id)&&(t=!i.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return Q(this,null,function*(){try{let t=this.authService.getUser(),i=It(t?.userId??""),a=this.docService.getDocumentPaths(),l=this.docService.getOrganizationConfig(),s=a?.organizationId??l?.organizationId,d=a?.clientOrganizationId??l?.clientOrganizationId,g={apiKey:this.configService.getApiKey(),organizationId:s,documentId:a?.documentId,clientOrganizationId:d,clientDocumentId:a?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:d??t?.clientOrganizationId??"",user:{userId:t?.userId??""},notificationsConfig:e||this.settingsConfig$.getValue()}):a?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:a?.documentId,userId:i},data:{id:a?.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:g}})))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(lt),X(We),X(Ft),X(Tn),X(rd),X(cv),X(rl),X(mv),X($n),X(ct),X(Be),X(Ln),X(x),X(LL),X(An),X(Do),X(il),X(tr))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lm=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,g,u,b,E,A,M){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=s,this.domService=d,this.afAuth=g,this.iamService=u,this.dialog=b,this.loggingService=E,this.notificationService=A,this.userPermissionService=M,this.areaAnnotationById$=new Se({}),this.documentPaths=null,this.areaEnabled$=new Se(!0),this.allowedElementIds$=new Se([]),this.addAreaMode$=new Se(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe($e(V=>!!V),ut(1)).subscribe(V=>{V&&this.getDocumentPaths()},V=>{this.loggingService.catch("Error in AreaService getDb subscription: ",V)}),this.domService.onWindowPointerMove$().subscribe(V=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&(this.isElementInsideAllowedElements(q)?wN(V.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,U.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},V=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",V)}),this.domService.onWindowKeyupEsc$().subscribe(V=>{this.addAreaMode$.value&&this.disableAddAreaMode()},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",V)}),this.domService.onDocumentClick$().subscribe(V=>{if(V&&this.addAreaMode$.value){if(V.preventDefault(),V.stopPropagation(),!wN(V.target)){let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&this.isElementInsideAllowedElements(q)&&this.addArea(V)}this.disableAddAreaMode()}},V=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",V)}),this.addAreaMode$.subscribe(V=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),V?this.domService.addClassToElement(document.body,"snippyly-add-area-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-area-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},V=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",V)}),this.domService.onWindowKeyupBackspace$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupBackspace")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",V)}),this.domService.onWindowKeyupDelete$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupDelete")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",V)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in AreaService","color: green;");try{this.areaAnnotationById$.next({}),this.areaEnabled$.next(!0),this.allowedElementIds$.next([]),this.addAreaMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in AreaService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllAreaAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,l;try{if(e&&(l=Qn(e)),t&&typeof t=="object"){let s=Oi(t);a=Qn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",s)}return fr(this.afAuth).pipe($e(s=>!!s),_e(s=>this.isFeatureAllowed({firebaseUser:s,annotations:[],filteredAnnotations:[]})),_e(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(s.featureAllowed=d,s))):le(s)),_e(s=>s.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(s.featureAllowed=!d,s))):le(s)),_e(s=>s.featureAllowed?le(s).pipe(_e(d=>this.docService.getDocumentPaths$().pipe(ue(g=>(this.documentPaths=g,d.documentPaths=g,d)))),_e(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(g=>(d.annotations=g||[],f({},d)))):this.docService.getDocumentIds$().pipe(_e(g=>{let u=g?.length>0?g.map(b=>b.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(b=>(d.annotations=b||[],f({},d))))}))),_e(d=>this.docService.getLocation$().pipe(ue(g=>(d.location=g,d)))),_e(d=>this.docService.getLocations$().pipe(ue(g=>(d.customLocations=g,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let g=[],u=[];return a?g.push(a):(g.push(d?.location?.locationId),g.push(...Object.values(d?.customLocations||[]).map(b=>b.locationId)),d?.location?.location?.id&&u.push(d?.location?.location?.id)),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,g,u),d}}),_e(d=>i?le(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):le(d)),_e(d=>i?le(d):d?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ue(()=>d)):le(d)),ue(d=>(d.filteredAnnotations=d.filteredAnnotations?.map(g=>{let u=Object.assign({},g);return u.areaProperties=this.calculateAreaAnnotationPosition(u),u}),d)),_e(d=>d?.filteredAnnotations?le(d?.filteredAnnotations||[]):le([])),_e(d=>{if(this.authService.isFeatureAllowed(je.COMMENT))return le(d);{let g=d?.filter(u=>!u?.targetAnnotations?.filter(b=>b?.type===je.COMMENT)?.length);return le(g)}})):le([])),xt(Jt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe($e(t=>!!t),ue(t=>k(f({},e),{config:t})),_e(t=>this.authService.getUser$().pipe(ue(i=>k(f({},t),{user:i})))),_e(t=>Ao(t.config,t.user,je.AREA)?le(k(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),le(k(f({},t),{featureAllowed:!1})))),xt((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return le([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=le([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=t?.length?t[0]:void 0,s.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[U.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],g=[];for(let u=0;u<(d?.length??0);u+=U.LISTENER_CONTEXT_BATCH_SIZE)g.push(d?.slice(u,u+U.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=pn(g.map(u=>this.commonDbService.dbListener({feature:"allAreas",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Ra(u)))}else{let d=[];for(let g=0;g<(t?.length??0);g+=U.LISTENER_BATCH_SIZE)d.push(t?.slice(g,g+U.LISTENER_BATCH_SIZE)??[]);l=pn(d.map(g=>this.commonDbService.dbListener({feature:"allAreas",properties:k(f({},s),{firestoreQuery:[_r(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",g),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(g=>Ra(g)))}return l.pipe(ue(({data:d,operation:g})=>{let u=[];return d&&(u=Object.values(d??{}).filter(b=>typeof b=="object")),{data:u,operation:g}}),ue(({data:d,operation:g})=>{if(!t)return{data:d,documentMap:{},operation:g};let u=d.reduce((b,E)=>{let A=E.metadata?.documentId;return A&&(b[A]||(b[A]=[]),b[A].push(E)),b},{});return{data:d,documentMap:u,operation:g}}),ue(({data:d,documentMap:g,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let b=this.areaAnnotationById$.value;u?.ids?.forEach(E=>{delete b?.[E]}),this.areaAnnotationById$.next(b)}}else Object.entries(g??{}).forEach(([b,E])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:b,annotations:E})});return d}))}else return le([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let s=f(f({},this.areaAnnotationById$.value),l);this.areaAnnotationById$.next(s)}}catch(l){this.loggingService.catch("Error in AreaService setAreaAnnotationsByOrganizationIdAndDocumentId:",l)}}getAnnotationById(e){try{return this.areaAnnotationById$.value?.[e]?this.areaAnnotationById$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in AreaService filterAnnotationsByLocations:",a),[]}}calculateAreaAnnotationPosition(e,t=!1){try{if(e.targetElements?.length){let i=e.targetElements[0],a=e.targetElements[1];if(i?.xpath&&a?.xpath||i?.anchor&&a?.anchor){let l=null,s=null;if(i?.anchor){let d=this.domService.resolveAnchorRecord(i.anchor);d?.element&&d?.element instanceof HTMLElement&&!Co(d.element)&&this.domService.isElementVisible(d.element)&&Zr(d.element)&&(l=d.element)}else i?.xpath&&(l=this.domService.getElementFromXPath(i.xpath),l&&Co(l)&&(l=null),this.domService.isXpathWithId(i.xpath)||(!l&&i.cfXpath&&(l=this.domService.getElementFromXPath(i.cfXpath),l&&Co(l)&&(l=null)),!l&&i.fXpath&&(l=this.domService.getElementFromXPath(i.fXpath),l&&Co(l)&&(l=null))));if(a?.anchor){let d=this.domService.resolveAnchorRecord(a.anchor);d?.element&&d?.element instanceof HTMLElement&&!Co(d.element)&&this.domService.isElementVisible(d.element)&&Zr(d.element)&&(s=d.element)}else a?.xpath&&(s=this.domService.getElementFromXPath(a.xpath),s&&Co(s)&&(s=null),this.domService.isXpathWithId(a.xpath)||(!s&&a.cfXpath&&(s=this.domService.getElementFromXPath(a.cfXpath),s&&Co(s)&&(s=null)),!s&&a.fXpath&&(s=this.domService.getElementFromXPath(a.fXpath),s&&Co(s)&&(s=null))));if(l&&s){let d=ZK(l,s);if(d){let g=l,u=s,b=g.getBoundingClientRect(),E=u.getBoundingClientRect(),A=t?b.width:g.offsetWidth||b.width,M=t?b.height:g.offsetHeight||b.height,V=t?E.width:u.offsetWidth||E.width,q=t?E.height:u.offsetHeight||E.height,ae={};A&&M&&(ae={top:M*i.topPercentage/100,left:A*i.leftPercentage/100});let fe={};V&&q&&(fe={top:q*a.topPercentage/100,left:V*a.leftPercentage/100});let ie=!t,Ce=JK(ae.left,ae.top,l,d,ie),xe=JK(fe.left,fe.top,s,d,ie),ke,ye,Oe,Ne,Ue={};Ce.x>xe.x?Ce.y>xe.y?(Ne={x:Ce.x,y:Ce.y},ke={x:xe.x,y:xe.y},Ue.handle1=Ne,Ue.handle2=ke):(ye={x:Ce.x,y:Ce.y},Oe={x:xe.x,y:xe.y},Ue.handle1=ye,Ue.handle2=Oe):Ce.y>xe.y?(Oe={x:Ce.x,y:Ce.y},ye={x:xe.x,y:xe.y},Ue.handle1=Oe,Ue.handle2=ye):(ke={x:Ce.x,y:Ce.y},Ne={x:xe.x,y:xe.y},Ue.handle1=ke,Ue.handle2=Ne);let ze={topLeft:ke||{x:Oe?.x,y:ye?.y},bottomRight:Ne||{x:ye?.x,y:Oe?.y},topRight:ye||{x:Ne?.x,y:ke?.y},bottomLeft:Oe||{x:ke?.x,y:Ne?.y}};return Ue.coordinates=ze,Ue.targetElement=this.domService.getXPath(d),Ue}}}}return}catch(i){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",i);return}}addArea(e,t=[],i,a,l,s){this.loggingService.log("%c[WB] Calling FUNCTION: addArea","color: green;");try{let d=this.authService.getUser();if(d)if(d.isReadOnly||d.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add areas.");else{let g=new mL;a&&(g.annotationId=a),g.from=d,g.color=U.DEFAULT_ANNOTATION_COLOR,g.lastUpdated=this.timestamp,i&&(g.targetAnnotations=[i]),g.props=new td;let u=this.domService.getCurrentWindowSizeValue();if(g.props.screenWidth=u.screenWidth,g.props.screenHeight=u.screenHeight,g.props.screenScrollHeight=u.screenScrollHeight,g.props.viewportWidth=window.innerWidth,g.props.viewportHeight=window.innerHeight,e||t?.length>0){let A=e?this.getPointsForAreaPinAnnotation(e):t;g.targetElements=[],A.forEach(M=>{g.targetElements.push(this.domService.getTargetElementForCursorPosition(e,void 0,void 0,void 0,void 0,!0,{clientX:M.x,clientY:M.y}))})}this.setLocationToAreaAnnotation(g),l&&(g.locationId=l.locationId,g.location=l.location),g.pageInfo=to(),g.pageInfo&&(g.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let b=this.getElementForAreaAnnotation(g),E=this.docService.getBaseMetadata("area",{element:b});if(g?.metadata||(g.metadata={}),g.metadata=f(f({},g.metadata),E),s?.access&&s?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:d.userId,accessFields:s.accessFields})){this.loggingService.catch("User does not have context access to add area annotation.",void 0,void 0,!0);return}g.context={access:s.access,accessFields:s.accessFields}}return this.saveAreaToDb(g),g}return}catch(d){this.loggingService.catch("Error in AreaService addArea: ",d);return}}setLocationToAreaAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,i,a;if(e.targetElements?.length){if(e.targetElements[0]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[0].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Zr(l.element)&&(i=l.element)}else e.targetElements[0]?.xpath&&(i=this.domService.getElementFromXPath(e.targetElements[0].xpath));if(e.targetElements[1]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[1].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Zr(l.element)&&(a=l.element)}else e.targetElements[1]?.xpath&&(a=this.domService.getElementFromXPath(e.targetElements[1].xpath))}return i&&a&&(t=ZK(i,a)),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)&&pn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe($e(([t,i])=>!!t&&!!i),ut(1),_e(([t,i])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("area");a.metadata=f(f({},a?.metadata),d)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(K.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:l,organizationId:s}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:l,organizationId:s},data:JSON.parse(JSON.stringify(a))})}else return le(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,i){try{i&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,_N.UPDATED),this.updateAreaToDb(e)}catch(a){this.loggingService.catch("Error in AreaService updateArea: ",a)}}updateAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateAreaToDb","color: green;");try{if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("area");t.metadata=f(f({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(l=>Q(this,null,function*(){let s=t[l];s.type==="area"&&i&&s.from&&(i?.isAdmin||s.from.userId===i.userId)&&a.push(s)})),a?.length&&(this.analyticsService.trackEvent(K.Events.Area.AREA_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(xl,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(s=>Q(this,null,function*(){yield this.deleteAreaPinAnnotation(s)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i??{})}catch(i){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",i),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),l;t?l=a.find(s=>s?.annotationId===t):l=a.find(s=>s?.targetAnnotations?.find(d=>d?.annotationId===e)),l&&(l.targetAnnotations=l.targetAnnotations?.filter(s=>s?.annotationId!==e),l.targetAnnotations?.length?this.updateAreaToDb(l):this.deleteAreaPinAnnotation(l))}}catch(i){this.loggingService.catch("Error in AreaService onDeleteTargetAnnotation: ",i)}}deleteAreaPinAnnotation(e){if(this.authService.isFeatureAllowed(je.AREA)&&this.documentPaths?.area&&e?.annotationId){this.updateNotificationsDatabase(e,_N.DELETED),this.analyticsService.trackEvent(K.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:i}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,organizationId:i}})}else return Promise.resolve()}enableArea(){try{this.areaEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in AreaService enableArea: ",e)}}disableArea(){try{this.areaEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in AreaService disableArea: ",e)}}getAreaEnabled$(){try{return this.areaEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled$: ",e),le(!1)}}getAreaEnabled(){try{return this.areaEnabled$.value}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled: ",e),!1}}enableAddAreaMode(){this.authService.isFeatureAllowed(je.AREA)?(this.analyticsService.trackEvent(K.Events.Area.AREA_ADD_MODE_ENABLED),this.addAreaMode$.next(!0)):this.loggingService.catch("Error in AreaService enableAddAreaMode: ","Area feature is not enabled.")}disableAddAreaMode(){this.analyticsService.trackEvent(K.Events.Area.AREA_ADD_MODE_DISABLED),this.addAreaMode$.next(!1)}addAreaModeChange(){return this.addAreaMode$.asObservable()}getPointsForAreaPinAnnotation(e){let t=[],i=e,a=i?.touches?.length?i.touches[0]?.clientX:i.clientX,l=i?.touches?.length?i.touches[0]?.clientY:i.clientY;return t.push({x:a,y:l}),t.push({x:a+100,y:l+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"area"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in AreaService updateNotificationsDatabase: ",i)}}getAreaUrl(e){try{return e?.pageInfo?.areaUrl?e.pageInfo.areaUrl:(e?.pageInfo||(e.pageInfo=to(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(U.URL_PARAMS.TAG_ID),t.searchParams.append(U.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return Q(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield Hu(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(X(lt),X(Ft),X(ct),X($n),X(Tn),X(We),X(Be),X(eo),X(Ln),X(Fo),X(x),X(xn),X(il))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var U_e=n=>{try{let o={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return g3.sanitize(n,o)}catch(o){return at.catch("Error in File utils sanitizeSvg: ",o),""}},V_e=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){at.catch("Error in File utils getFileName: ",o);return}},xQ=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){at.catch("Error in File utils getFileExtension: ",o);return}},B_e=(n,o)=>{try{let r=n.slice(0,-1,n.type);return new File([r],o+"."+xQ(n),{type:n.type})}catch(r){at.catch("Error in File utils updateFile: ",r);return}};var kQ={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 yp=(()=>{let o=class o{constructor(e,t,i,a,l){this.authService=e,this.configService=t,this.coreActionsService=i,this.loggingService=a,this.attachmentResolverService=l,this.storage=hw();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{if(s&&s.firebaseOptions?.storageBucket){this.storage=hw(void 0,s?.firebaseOptions?.storageBucket);let d=this.configService.getProxyConfig();d?.storageHost&&(this.storage.host=d.storageHost)}},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:t}){try{let i=new Zb;i.name=t.name;let a=B_e(t,`${i.attachmentId}_${V_e(t)}`),l=`${this.apiKey}/${e}/${a?.name}`;return i.bucketPath=l,i.size=t.size,i.type=xQ(t),i?.type&&(i.mimeType=kQ[i?.type]),i}catch(i){return this.loggingService.catch("Error in StorageService createAttachment: ",i),null}}sanitizeSvgFile(e){return Q(this,null,function*(){if(e.type===kQ.svg)try{let t=yield e.text(),i=U_e(t);return new File([i],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return Q(this,arguments,function*({attachment:e,file:t,resolve:i,reject:a}){try{let s=fw(this.storage,e.bucketPath),d=kY(s,t,{cacheControl:"public,max-age=3600"});d.on("state_changed",g=>{let u=g.bytesTransferred/g.totalBytes*100},g=>{a(g)},()=>{xY(d.snapshot.ref).then(g=>{e.url=g,i(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}})}uploadToResolver(d){return Q(this,arguments,function*({file:e,attachment:t,metadata:i,resolve:a,reject:l,scope:s}){try{i.attachmentId=t.attachmentId;let g={attachmentId:t.attachmentId,name:t.name,file:e,metadata:i,mimeType:t.mimeType},u=ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:kc.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:g,eventType:Io.ATTACHMENT_ADD}});let b=yield this.attachmentResolverService.saveAttachment({attachment:g,eventType:Io.ATTACHMENT_ADD},u,s);b&&b.data?.url?(t.url=b.data?.url,a(t)):l(new Error("Failed to upload attachment to resolver"))}catch(g){this.loggingService.catch("Error in StorageService uploadToResolver: ",g),l(g)}})}uploadFile({path:e,file:t,useAttachmentResolver:i,metadata:a,attachmentScope:l}){return new Promise((s,d)=>Q(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let g=yield this.sanitizeSvgFile(t),u=this.createAttachment({path:e,file:g});if(!u)throw new Error("Attachment not created");i?this.uploadToResolver({file:g,attachment:u,metadata:a,resolve:s,reject:d,scope:l}):this.uploadAttachmentToStorage({attachment:u,file:g,resolve:s,reject:d})}catch(g){this.loggingService.catch("Error in StorageService uploadFile:",g),d(g)}}))}uploadChunk(e,t,i,a){return new Promise((l,s)=>{try{if(a?.useAttachmentResolver){let d=this.createAttachment({path:e,file:t});if(!d){s(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:d,metadata:a.metadata,resolve:g=>l(g.url),reject:s,scope:a.attachmentScope});return}if(this.apiKey){let d=`${this.apiKey}/${e}/${t.name}`,g=fw(this.storage,d),u=kY(g,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",b=>{let E=b.bytesTransferred/b.totalBytes*100},b=>{s(b)},()=>{xY(u.snapshot.ref).then(b=>{l(b)}).catch(b=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${i}:`,b),s(b)})})}else{let d=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",d),s(d)}}catch(d){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${i}: `,d),s(d)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let i=t.response,a=document.createElement("a"),l=window.URL.createObjectURL(i);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=l,e?.name&&(a.download=e?.name),document.body.appendChild(a);let s=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(s),window.URL.revokeObjectURL(l),a.remove()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:i,attachmentScope:a}){return new Promise((l,s)=>{if(i){let d=ot();this.coreActionsService.triggerAction(Qe.ATTACHMENT_RESOLVER,{event:K.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:kc.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},d,a).then(()=>{l(null)}).catch(g=>{s(g)})}else{let d=fw(this.storage,e.bucketPath);yY(d).then(()=>{l(null)}).catch(g=>{l(null)})}})}deleteFileFromPath(e){return new Promise((t,i)=>{let a=fw(this.storage,e);yY(a).then(()=>{t(null)}).catch(l=>{i(l)})})}};o.\u0275fac=function(t){return new(t||o)(X(We),X(Ft),X(tr),X(x),X(Gs))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var go=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new Se(U.CommentAnnotationStatusMap),this._customPriorityMap=new Se(U.CommentAnnotationPriorityMap),this._customCategoryMap=new Se(U.CommentCategoryMap);try{let t=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);i&&this._customStatusMap.next(JSON.parse(i));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}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 t={};e.forEach(i=>{t[i.id]=i,i.type||(i.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}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 t={};e.forEach(i=>{t[i.id]=i}),this._customPriorityMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(i=>{t[i.id]=i}),this._customCategoryMap.next(t),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([i,a])=>a.type==="ongoing");if(t)return t.map(i=>i[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 t=Object.entries(this._customStatusMap.value),i=t.find(([a,l])=>l.type==="default");switch(e.status){case"open":i&&(e.status=i[1]);break;case"inProgress":let a=t.find(([s,d])=>d.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let l=t.find(([s,d])=>d.type==="terminal");l&&(e.status=l[1]);break;default:i&&(e.status=i[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}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(t=>U.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var j_e=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new it;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(Vh()),this.domService.onWindowKeydown$().subscribe(i=>{this.keyEventSubject$.next(i)})}catch(i){this.loggingService.catch("Error in HotkeyService constructor: ",i)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe($e(i=>i?.key===e),$e(i=>!(!!t?.includeCtrl!==i.ctrlKey||!!t?.includeAlt!==i.altKey||!!t?.includeShift!==i.shiftKey||!!t?.includeMeta!==i.metaKey)),$e(()=>this.isNoInputFocused()))}catch(i){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",i),new Gt}}isNoInputFocused(){try{let e=document.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e?.parentElement}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(Be),X(x))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function HWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",17)(2,"path",18)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function GWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",22)(2,"path",23)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function zWe(n,o){if(n&1&&(C(0),h(1,"div",6)(2,"div",7),p(3,HWe,6,0,"svg",8)(4,GWe,6,0,"ng-template",null,1,Ve),S(),h(6,"div",9),ne(7),R(8,"translate"),D(9,"br"),ne(10),R(11,"translate"),S(),h(12,"div",10)(13,"p"),ne(14),R(15,"translate"),de(),h(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),ne(21),R(22,"translate"),S(),St(),h(23,"p"),ne(24),R(25,"translate"),S()()(),_()),n&2){let r=Ie(5),e=c();m(3),v("ngIf",e.darkMode)("ngIfElse",r),m(4),Ee(" ",N(8,7,"Allow mic permission to")),m(3),Ee("",N(11,9,"enable your audio")," "),m(4),Ee(" ",N(15,11,"1. Click the")," "),m(7),Ee(" ",N(22,13,"page info icon in your browser\u2019s address bar")," "),m(3),Ee(" ",N(25,15,"2. Turn on Microphone")," ")}}function WWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",17)(2,"path",24)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function qWe(n,o){n&1&&(de(),h(0,"svg",16),D(1,"rect",22)(2,"path",25)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function YWe(n,o){if(n&1&&(C(0),h(1,"div",6)(2,"div",7),p(3,WWe,6,0,"svg",8)(4,qWe,6,0,"ng-template",null,2,Ve),S(),h(6,"div",9),ne(7),R(8,"translate"),D(9,"br"),ne(10),R(11,"translate"),S(),h(12,"div",10)(13,"p"),ne(14),R(15,"translate"),de(),h(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),ne(21),R(22,"translate"),S(),St(),h(23,"p"),ne(24),R(25,"translate"),S()()(),_()),n&2){let r=Ie(5),e=c();m(3),v("ngIf",e.darkMode)("ngIfElse",r),m(4),Ee(" ",N(8,7,"Allow camera permission")),m(3),Ee("",N(11,9,"to enable your video")," "),m(4),Ee(" ",N(15,11,"1. Click the")," "),m(7),Ee(" ",N(22,13,"page info icon in your browser\u2019s address bar")," "),m(3),Ee(" ",N(25,15,"2. Turn on Camera")," ")}}var jL=(()=>{let o=class o{constructor(e,t,i,a,l){this.loggingService=e,this.themeService=t,this.elementRef=i,this.matDialogRef=a,this.data=l,this.veltElement=!0,this.darkMode=!0;try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionDeniedDialogComponent","color: blue;"),this.type=this.data?.type,[!0,!1].includes(this.data?.darkMode)&&(this.darkMode=this.data?.darkMode)}catch(s){this.loggingService.catch("Error in DevicePermissionDeniedDialogComponent constructor: ",s)}}ngOnDestroy(){}};o.\u0275fac=function(t){return new(t||o)(y(x),y(_t),y(Z),y(Vi,8),y(Yc,8))},o.\u0275cmp=O({type:o,selectors:[["velt-device-permission-denied-dialog-internal"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{type:"type"},standalone:!1,decls:5,vars:5,consts:[["devicePermissionDialogRef",""],["defaultAudioIcon",""],["defaultVideoIcon",""],[1,"velt-device-permission-denied-dialog--container",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"ngSwitch"],[4,"ngSwitchCase"],[1,"velt-device-permission-denied-dialog"],[1,"velt-device-permission-denied-dialog--icon"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg",4,"ngIf","ngIfElse"],[1,"velt-device-permission-denied-dialog--header"],[1,"velt-device-permission-denied-dialog--content"],["width","13","height","12","viewBox","0 0 13 12","fill","none","xmlns","http://www.w3.org/2000/svg",1,"velt-device-permission-denied-dialog--page-info-icon"],["d","M4.375 2.5C4.375 3.53553 3.53553 4.375 2.5 4.375C1.46447 4.375 0.625 3.53553 0.625 2.5C0.625 1.46447 1.46447 0.625 2.5 0.625C3.53553 0.625 4.375 1.46447 4.375 2.5Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M5 2.5H12.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M0 8.75H7.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M11.875 8.75C11.875 9.78553 11.0355 10.625 10 10.625C8.96447 10.625 8.125 9.78553 8.125 8.75C8.125 7.71447 8.96447 6.875 10 6.875C11.0355 6.875 11.875 7.71447 11.875 8.75Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg"],["x","0.5","y","4","width","56","height","56","rx","28","fill","white","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M13.5 17L43.5 47","stroke","currentColor","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","36.5","width","24","height","24","rx","12","fill","currentColor"],["d","M48.5 18.99V19M48.5 14V5","stroke","white","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","0.5","y","4","width","56","height","56","rx","28","fill","black","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","black","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","currentColor","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"]],template:function(t,i){if(t&1&&(h(0,"div",3,0),C(2,4),p(3,zWe,26,17,"ng-container",5)(4,YWe,26,17,"ng-container",5),_(),S()),t&2){let a=Ie(1);v("snippylyOverlay",a)("snippylyOverlayZIndex",3e3),m(2),v("ngSwitch",i.type),m(),v("ngSwitchCase","audio"),m(),v("ngSwitchCase","video")}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.velt-device-permission-denied-dialog--panel mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{padding:0;background-color:transparent;box-shadow:none;overflow:unset}.velt-device-permission-denied-dialog[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:var(--velt-spacing-lg);align-items:center;justify-content:center;padding:4rem;box-sizing:border-box;word-break:break-word;max-width:600px;max-height:400px;text-align:center;background-color:var(--velt-background-0);border-radius:var(--velt-border-radius-2xl);box-shadow:0 calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((-3rem + 0px) * var(--velt-base-rem-unit)) #1f2f461f}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--icon[_ngcontent-%COMP%]{color:var(--velt-error)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--header[_ngcontent-%COMP%]{font-size:var(--velt-font-size-lg);font-weight:600;line-height:36px;letter-spacing:-.02em;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%]{font-size:var(--velt-font-size-sm);font-weight:400;line-height:21px;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--page-info-icon[_ngcontent-%COMP%]{margin-left:var(--velt-spacing-sm);margin-right:var(--velt-spacing-sm);color:var(--velt-error)}"],changeDetection:0});let n=o;return n})();var gv=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.matDialog=t,this.audioPermissionState$=new Se(null),this.videoPermissionState$=new Se(null);try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionService","color: blue;"),this.checkPermissions()}catch(i){this.loggingService.catch("Error in DevicePermissionService constructor: ",i)}}checkPermissions(){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: checkPermissions","color: green;"),new ur().browserName!=="Firefox"&&(navigator.permissions.query({name:"microphone"}).then(t=>{this.audioPermissionState$.next(t.state),t.onchange=()=>{this.audioPermissionState$.next(t.state)}}).catch(t=>{}),navigator.permissions.query({name:"camera"}).then(t=>{this.videoPermissionState$.next(t.state),t.onchange=()=>{this.videoPermissionState$.next(t.state)}}).catch(t=>{}))}catch(e){this.loggingService.catch("Error in DevicePermissionService checkPermissions: ",e)}}getPermissionState$(e){try{switch(this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: getPermissionState$","color: green;"),e){case"audio":return this.getAudioPermissionState$();case"video":return this.getVideoPermissionState$();default:return le(null)}}catch(t){return this.loggingService.catch("Error in DevicePermissionService getPermissionState$: ",t),le(null)}}getAudioPermissionState$(){return this.audioPermissionState$.asObservable()}getVideoPermissionState$(){return this.videoPermissionState$.asObservable()}openDevicePermissionDeniedDialog(e,t){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: openDevicePermissionDeniedDialog","color: green;"),this.matDialog.open(jL,{panelClass:["velt-device-permission-denied-dialog--panel","velt-mat-dialog-container"],backdropClass:["velt-device-permission-denied-dialog--backdrop","s-background-blur-1"],data:f({type:e},t||{})})}catch(i){this.loggingService.catch("Error in DevicePermissionService openDevicePermissionDeniedDialog: ",i)}}};o.\u0275fac=function(t){return new(t||o)(X(x),X(Fo))},o.\u0275prov=Me({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var KWe=()=>["video","screen"];function ZWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-video",4),n&2){let r=c(2);v("componentConfigSignal",r.componentConfigSignal)}}function JWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-audio",4),n&2){let r=c(2);v("componentConfigSignal",r.componentConfigSignal)}}function XWe(n,o){if(n&1&&(C(0),h(1,"div",2,0),p(3,ZWe,1,1,"app-recording-preview-steps-dialog-video",3)(4,JWe,1,1,"app-recording-preview-steps-dialog-audio",3),S(),_()),n&2){let r=o.ngIf,e=Ie(2),t=c();m(),v("snippylyOverlay",e)("snippylyOverlayZIndex",2e3),T("aria-label","Recording preview - "+r.type+" mode")("data-testid",t.componentId),m(2),v("ngIf",Et(6,KWe).includes(r.type)),m(),v("ngIf",r.type==="audio")}}var $L=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.loggingService=e,this.recorderService=t,this.dialog=i,this.devicePermissionService=a,this.dialogRef=l,this.elementRef=s,this.data=d,this.darkMode=!1,this.shadowDom=!0,this.startCountdownFrom=3,this.defaultMediaSourceOptions=Qd(),this.recordingCountdownEnabled=!1,this.subscriptions=[],this.veltElement=!0,this.componentId="velt-recording-preview-steps-dialog",this.componentConfigSignal=Ae({closeDialog:this.closeDialog.bind(this),startCountdown:this.startCountdown.bind(this),toggleAudio:this.toggleAudio.bind(this),toggleVideo:this.toggleVideo.bind(this),toggleSettings:this.toggleSettings.bind(this),cancelCountdown:this.cancelCountdown.bind(this),updateMediaConfig:this.updateMediaConfig.bind(this),handleOverlayClick:this.handleOverlayClick.bind(this),countdownStarted:!1,mediaConfig:{audio:{enabled:!1},video:{enabled:!1}},mediaState:{audio:{enabled:!1},video:{enabled:!1}},type:"video",countdown:this.startCountdownFrom,mediaStream:void 0,isSettingsOpen:!1,darkMode:this.darkMode,shadowDom:this.shadowDom,isExplicitShadowDom:!1});try{this.devicePermissionService.getPermissionState$("video").subscribe(g=>{this.componentConfigSignal.update(u=>(u=k(f({},u),{mediaState:k(f({},u.mediaState),{video:{enabled:g!=="denied"}})}),u))}),this.devicePermissionService.getPermissionState$("audio").subscribe(g=>{this.componentConfigSignal.update(u=>(u=k(f({},u),{mediaState:k(f({},u.mediaState),{audio:{enabled:g!=="denied"}})}),u))}),this.subscriptions.push(this.recorderService.getRecordingCountdownEnabled$().subscribe(g=>{this.recordingCountdownEnabled=g})),this.subscriptions.push(this.recorderService.getRecordingMicEnabled$().subscribe(g=>{g!==null&&(g?this.toggleAudioOn():this.toggleAudioOff())})),d&&(d.type&&this.componentConfigSignal.update(g=>(g=k(f({},g),{type:d.type}),g)),d.recordingCountdown!==void 0&&(this.recordingCountdownEnabled=!!d.recordingCountdown),d.mediaConfig&&(d.mediaConfig?.audio?.enabled&&!d.mediaConfig?.audio?.deviceId&&(d.mediaConfig.audio.deviceId=this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId),d.mediaConfig?.video?.enabled&&!d.mediaConfig?.video?.deviceId&&(d.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId),d?.darkMode?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark"),this.componentConfigSignal.update(g=>(g=k(f({},g),{shadowDom:d?.shadowDom!==!1,isExplicitShadowDom:!!d?.isExplicitShadowDom,darkMode:d.darkMode||!1}),g)),this.updateMediaConfig(d.mediaConfig)))}catch(g){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent constructor: ",g)}}ngOnInit(){try{this.setupA11yAttributes(),this.componentConfigSignal().type==="screen"&&this.subscriptions.push(this.recorderService.getScreenStream$().subscribe(e=>{e&&e.active&&e.getVideoTracks().some(t=>t.readyState==="live")&&this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig.screen={enabled:!0,stream:e},t))}))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnInit:",e)}}setupA11yAttributes(){try{let e=this.elementRef.nativeElement;e.setAttribute("data-testid",this.componentId+"-container"),e.setAttribute("role","dialog"),e.setAttribute("aria-label","Recording preview steps dialog")}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent setupA11yAttributes:",e)}}ngOnChanges(e){try{e&&Object.keys(e).forEach(t=>{this.componentConfigSignal.update(i=>(i=k(f({},i),{[t]:e[t].currentValue}),i))})}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.dialogRef.addPanelClass("snippyly-recording-preview-steps-dialog"),this.dialogRef.disableClose=!0}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngAfterViewInit: ",e)}}toggleSettings(e){try{e.stopPropagation(),this.componentConfigSignal.update(t=>(t=k(f({},t),{isSettingsOpen:!t.isSettingsOpen}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleSettings: ",t)}}toggleAudio(){try{this.componentConfigSignal().mediaConfig.audio||this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:{enabled:!0}})}),i));let e=!this.componentConfigSignal().mediaConfig.audio?.enabled;this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:{enabled:e}})}),i));let t=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];t?t.enabled=e:e&&(this.componentConfigSignal.update(i=>(i=k(f({},i),{mediaConfig:k(f({},i.mediaConfig),{audio:k(f({},i.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),i)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudio: ",e)}}toggleAudioOn(){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:{enabled:!0}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e?e.enabled=!0:(this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:k(f({},t.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),t)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleAudioOff(){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaConfig:k(f({},t.mediaConfig),{audio:{enabled:!1}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e&&(e.enabled=!1)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleVideo(){try{this.componentConfigSignal.update(e=>(e=f({},e),e.mediaConfig.video||(e.mediaConfig.video={enabled:!0}),e.mediaConfig.video.enabled=!e.mediaConfig.video.enabled,e.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId,e)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleVideo: ",e)}}updateMediaConfig(e){try{this.stopMediaStream(),this.getMediaStream(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent updateMediaConfig: ",t)}}getMediaStream(e){try{if(!navigator.mediaDevices){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No media devices");return}if(!navigator.mediaDevices.getUserMedia){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No getUserMedia");return}if(e.audio?.enabled||e.video?.enabled){let t=$_e(e);navigator.mediaDevices.getUserMedia(t).then(i=>{this.componentConfigSignal.update(a=>(a=k(f({},a),{mediaConfig:e,mediaStream:i}),a))}).catch(i=>{this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream catch: ",i)})}else this.componentConfigSignal.update(t=>(t=k(f({},t),{mediaStream:void 0,mediaConfig:e}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ",t)}}stopMediaStream(){try{this.componentConfigSignal.update(e=>(e=f({},e),e.mediaStream?.getTracks().forEach(t=>{t.stop()}),e.mediaStream=void 0,e))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent stopMediaStream: ",e)}}startCountdown(){return Q(this,null,function*(){try{let t=new ur().getBrowserName()==="Firefox",i=null;if(t&&this.componentConfigSignal().type==="screen")try{let a=this.componentConfigSignal().mediaConfig,l=$_e(a);Object.keys(l).length>0&&(i=yield navigator.mediaDevices.getUserMedia(l))}catch(a){this.loggingService.catch("Error getting Firefox user media stream:",a),i=null}if(this.componentConfigSignal().type==="screen"){if(!this.componentConfigSignal().mediaConfig.screen?.stream)try{let l=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});this.componentConfigSignal.update(s=>(s=f({},s),s.mediaConfig.screen={enabled:!0,stream:l},s))}catch(l){this.loggingService.catch("Error getting screen media stream:",l),this.cancelCountdown();return}this.componentConfigSignal.update(l=>(l=f({},l),i&&(l.mediaConfig.audio?.enabled&&(l.mediaConfig.audio.stream=i),l.mediaConfig.video?.enabled&&(l.mediaConfig.video.stream=i)),l)),this.componentConfigSignal().mediaConfig.screen?.stream?.getTracks().forEach(l=>{l&&(l.onended=()=>{this.cancelCountdown()})})}this.recordingCountdownEnabled?(this.componentConfigSignal.update(a=>(a=k(f({},a),{countdownStarted:!0}),a)),this.countdownInterval=setInterval(()=>{this.componentConfigSignal().countdown>1?this.componentConfigSignal.update(a=>(a=k(f({},a),{countdown:a.countdown-1}),a)):this.closeDialog(this.componentConfigSignal().mediaConfig)},1e3)):this.closeDialog(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent startCountdown: ",e)}})}cancelCountdown(){try{if(this.componentConfigSignal.update(e=>(e=k(f({},e),{countdownStarted:!1,countdown:this.startCountdownFrom}),e)),this.clearInterval(),this.componentConfigSignal().type==="screen"){let e=this.componentConfigSignal().mediaConfig.screen?.stream;e&&e.getTracks().forEach(t=>{t.stop()}),this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig.screen=void 0,t))}}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent cancelCountdown: ",e)}}closeDialog(e){return Q(this,null,function*(){try{this.clearInterval(),e||(this.stopMediaStream(),this.componentConfigSignal.update(t=>(t=f({},t),t.mediaConfig&&(t.mediaConfig.screen?.stream&&(t.mediaConfig.screen.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.screen.stream=void 0),t.mediaConfig.audio?.stream&&(t.mediaConfig.audio.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.audio.stream=void 0),t.mediaConfig.video?.stream&&(t.mediaConfig.video.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.video.stream=void 0)),t))),this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent closeDialog: ",t)}})}handleOverlayClick(e){try{this.componentConfigSignal.update(t=>(t=k(f({},t),{isSettingsOpen:!1}),t)),e.stopPropagation()}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent handleOverlayClick: ",t)}}clearInterval(){try{this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=void 0)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent clearInterval: ",e)}}ngOnDestroy(){try{this.clearInterval(),this.stopMediaStream(),this.subscriptions.forEach(e=>{e?.unsubscribe()})}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(y(x),y(Fn),y(Fo),y(gv),y(Vi),y(Z),y(Yc,8))},o.\u0275cmp=O({type:o,selectors:[["snippyly-recording-preview-steps-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&T("data-velt-element",i.veltElement)},inputs:{darkMode:"darkMode",shadowDom:"shadowDom"},standalone:!1,features:[st],decls:1,vars:1,consts:[["recordingPreviewDialogRef",""],[4,"ngIf"],["role","dialog","aria-modal","true",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"componentConfigSignal",4,"ngIf"],[3,"componentConfigSignal"]],template:function(t,i){t&1&&p(0,XWe,5,7,"ng-container",1),t&2&&v("ngIf",i.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog{max-width:none} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{background:transparent;padding:0;margin:0;border-radius:var(--velt-border-radius-lg)}"],changeDetection:0});let n=o;return n})();function $_e(n){try{let o={};return n.audio?.enabled&&(o.audio={deviceId:n.audio.deviceId?{exact:n.audio.deviceId}:void 0}),n.video?.enabled&&(o.video={deviceId:n.video.deviceId?{exact:n.video.deviceId}:void 0}),o}catch{return{}}}var Kl=(()=>{let o=class o{constructor(e){this.loggingService=e,this.isPipActive$=new Se(!1),this.pipStopRecordingTriggered$=new Se(!1),this.pipPauseRecordingTriggered$=new Se(!1),this.pictureInPicture$=new Se(!1),this.pipClearRecordingTriggered$=new Se(!1)}getPipClearRecordingTriggered$(){return this.pipClearRecordingTriggered$.asObservable()}resetPipClearRecordingTriggered(){this.pipClearRecordingTriggered$.next(!1)}openPictureInPicture(e,t){return Q(this,null,function*(){try{if(!this.isPictureInPictureEnabled()||!e||document.pictureInPictureElement||window.documentPictureInPicture?.window)return;if("documentPictureInPicture"in window){yield this.createDocumentPip(e,t);return}if(document.pictureInPictureEnabled){let i=yield this.findVideoElement();if(!i){this.loggingService.warn("No video element found for Picture-in-Picture");return}yield i.requestPictureInPicture(),this.isPipActive$.next(!0);return}}catch(i){this.loggingService.catch("Error in PipService openPictureInPicture:",i)}})}createDocumentPip(e,t){return Q(this,null,function*(){try{let i=window.documentPictureInPicture;this.pipWindow=yield i.requestWindow({width:320,height:288}),yield this.addStylesToPip(),yield this.createControlPanelInPip(e,t),this.pipWindow?.addEventListener("unload",()=>{try{this.isPipActive$.next(!1),this.pipWindow=void 0}catch(a){this.loggingService.catch("Error in PipService createDocumentPip unload:",a)}}),this.isPipActive$.next(!0)}catch{this.isPipActive$.next(!1),this.pipWindow=void 0}})}addStylesToPip(){return Q(this,null,function*(){try{if(!this.pipWindow)return;this.pipWindow.document.body.style.margin="0",this.pipWindow.document.body.style.padding="0",this.pipWindow.document.body.style.backgroundColor="#000",this.pipWindow.document.body.style.display="flex",this.pipWindow.document.body.style.alignItems="center",this.pipWindow.document.body.style.justifyContent="center"}catch(e){this.loggingService.catch("Error in PipService copyStylesToPip:",e)}})}createControlPanelInPip(e,t){return Q(this,null,function*(){if(this.pipWindow)try{let i=this.pipWindow.document.createElement("div");i.style.cssText=`
409
409
  display: flex;
410
410
  flex-direction: column;
411
411
  `;let a=this.pipWindow.document.createElement("div");a.style.cssText=`